diff --git a/sopt_29th_Assignment/Podfile b/sopt_29th_Assignment/Podfile new file mode 100644 index 0000000..201527c --- /dev/null +++ b/sopt_29th_Assignment/Podfile @@ -0,0 +1,21 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'sopt_29th_Assignment' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + # Pods for sopt_29th_Assignment + pod 'SnapKit', '~> 5.0.0' + pod 'Alamofire', '~> 5.1' + pod 'lottie-ios' + pod 'Kingfisher', '~> 5.0' + pod 'Alamofire', '~> 5.1' + pod 'Then' + pod 'Moya', '~> 14.0' + pod 'SwiftyJSON', '~> 4.0' + pod 'RxSwift', '6.2.0' + pod 'RxCocoa', '6.2.0' + pod 'SkeletonView' + pod 'ListPlaceholder' +end diff --git a/sopt_29th_Assignment/Podfile.lock b/sopt_29th_Assignment/Podfile.lock new file mode 100644 index 0000000..3a0bb64 --- /dev/null +++ b/sopt_29th_Assignment/Podfile.lock @@ -0,0 +1,67 @@ +PODS: + - Alamofire (5.4.4) + - Kingfisher (5.15.8): + - Kingfisher/Core (= 5.15.8) + - Kingfisher/Core (5.15.8) + - ListPlaceholder (1.5) + - lottie-ios (3.2.3) + - Moya (14.0.0): + - Moya/Core (= 14.0.0) + - Moya/Core (14.0.0): + - Alamofire (~> 5.0) + - RxCocoa (6.2.0): + - RxRelay (= 6.2.0) + - RxSwift (= 6.2.0) + - RxRelay (6.2.0): + - RxSwift (= 6.2.0) + - RxSwift (6.2.0) + - SkeletonView (1.25.1) + - SnapKit (5.0.1) + - SwiftyJSON (4.3.0) + - Then (2.7.0) + +DEPENDENCIES: + - Alamofire (~> 5.1) + - Kingfisher (~> 5.0) + - ListPlaceholder + - lottie-ios + - Moya (~> 14.0) + - RxCocoa (= 6.2.0) + - RxSwift (= 6.2.0) + - SkeletonView + - SnapKit (~> 5.0.0) + - SwiftyJSON (~> 4.0) + - Then + +SPEC REPOS: + trunk: + - Alamofire + - Kingfisher + - ListPlaceholder + - lottie-ios + - Moya + - RxCocoa + - RxRelay + - RxSwift + - SkeletonView + - SnapKit + - SwiftyJSON + - Then + +SPEC CHECKSUMS: + Alamofire: f3b09a368f1582ab751b3fff5460276e0d2cf5c9 + Kingfisher: a3c03d702433fa6cfedabb2bddbe076fb8f2e902 + ListPlaceholder: 2d7950014852ee5613d636cf14fd1bb93419e330 + lottie-ios: c058aeafa76daa4cf64d773554bccc8385d0150e + Moya: 5b45dacb75adb009f97fde91c204c1e565d31916 + RxCocoa: 4baf94bb35f2c0ab31bc0cb9f1900155f646ba42 + RxRelay: e72dbfd157807478401ef1982e1c61c945c94b2f + RxSwift: d356ab7bee873611322f134c5f9ef379fa183d8f + SkeletonView: 77079530e1348a72f48b79ae30dcb966c1b18b6a + SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb + SwiftyJSON: 6faa0040f8b59dead0ee07436cbf76b73c08fd08 + Then: acfe0be7e98221c6204e12f8161459606d5d822d + +PODFILE CHECKSUM: ac49fa414015d8736c33eef0212216c73de9a897 + +COCOAPODS: 1.11.2 diff --git a/sopt_29th_Assignment/Pods/Alamofire/LICENSE b/sopt_29th_Assignment/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..6b4d719 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +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. diff --git a/sopt_29th_Assignment/Pods/Alamofire/README.md b/sopt_29th_Assignment/Pods/Alamofire/README.md new file mode 100644 index 0000000..26e1c58 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/README.md @@ -0,0 +1,221 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png) + +[![Swift](https://img.shields.io/badge/Swift-5.1_5.2_5.3_5.4-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.1_5.2_5.3_5.4-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) +- [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) + - **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] 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.1 | [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! +- If you **want to contribute**, submit a pull request! + +## 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', '~> 5.4' +``` + +### 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" ~> 5.4 +``` + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.4.0")) +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for 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. + +## 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. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. +Donating to the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate today to help us reach our goal would be greatly appreciated. + +[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) + +## 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/sopt_29th_Assignment/Pods/Alamofire/Source/AFError.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..8cd60c7 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/Alamofire.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..630e169 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,35 @@ +// +// 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 + +/// 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.4.4" diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/AlamofireExtended.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/AlamofireExtended.swift new file mode 100644 index 0000000..280c6de --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/AuthenticationInterceptor.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/AuthenticationInterceptor.swift new file mode 100644 index 0000000..9d7f836 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/AuthenticationInterceptor.swift @@ -0,0 +1,404 @@ +// +// 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.credential = credential + mutableState.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/sopt_29th_Assignment/Pods/Alamofire/Source/CachedResponseHandler.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/CachedResponseHandler.swift new file mode 100644 index 0000000..8465ed7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/CachedResponseHandler.swift @@ -0,0 +1,91 @@ +// +// 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) + } + } +} diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/Combine.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Combine.swift new file mode 100644 index 0000000..b5e5044 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/Combine.swift @@ -0,0 +1,622 @@ +// +// 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 { $0.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 { $0.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, Cancellable + 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) + } + + /// 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, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + 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 { $0.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, Cancellable + 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 { $0.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 { $0.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, Cancellable + 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 `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 `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) + } + + /// 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 `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, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + 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/sopt_29th_Assignment/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..10cd273 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/EventMonitor.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/EventMonitor.swift new file mode 100644 index 0000000..3b09671 --- /dev/null +++ b/sopt_29th_Assignment/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. + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + 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) + } + + 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/sopt_29th_Assignment/Pods/Alamofire/Source/HTTPHeaders.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/HTTPHeaders.swift new file mode 100644 index 0000000..cd90fcf --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/HTTPHeaders.swift @@ -0,0 +1,449 @@ +// +// 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 { $0.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-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/sopt_29th_Assignment/Pods/Alamofire/Source/HTTPMethod.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/HTTPMethod.swift new file mode 100644 index 0000000..4867c1e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/HTTPMethod.swift @@ -0,0 +1,54 @@ +// +// 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") + /// `TRACE` method. + public static let trace = HTTPMethod(rawValue: "TRACE") + + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/MultipartFormData.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..8f72860 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,557 @@ +// +// 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.. 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" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> 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) + } +} diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/MultipartUpload.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/MultipartUpload.swift new file mode 100644 index 0000000..606bd33 --- /dev/null +++ b/sopt_29th_Assignment/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.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.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/sopt_29th_Assignment/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..deeb3a4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,267 @@ +// +// 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 + } + + var context = SCNetworkReachabilityContext(version: 0, + info: Unmanaged.passUnretained(self).toOpaque(), + retain: nil, + release: nil, + copyDescription: nil) + let callback: SCNetworkReachabilityCallBack = { _, flags, info in + guard let info = info else { return } + + let instance = Unmanaged.fromOpaque(info).takeUnretainedValue() + instance.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) } + } + } +} + +// 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/sopt_29th_Assignment/Pods/Alamofire/Source/Notifications.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..66434b6 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/OperationQueue+Alamofire.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/OperationQueue+Alamofire.swift new file mode 100644 index 0000000..b06a0cc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/ParameterEncoder.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/ParameterEncoder.swift new file mode 100644 index 0000000..f4facbe --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/ParameterEncoder.swift @@ -0,0 +1,184 @@ +// +// 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 + } +} + +/// 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 + } +} diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/ParameterEncoding.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..6e72604 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,317 @@ +// +// 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 + + func encode(key: String) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + } + } + } + + /// 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 value in array { + components += queryComponents(fromKey: arrayEncoding.encode(key: key), 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 { + // 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 } + + 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 } + + 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 + } +} + +// 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/sopt_29th_Assignment/Pods/Alamofire/Source/Protected.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Protected.swift new file mode 100644 index 0000000..b673a1b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/Protected.swift @@ -0,0 +1,197 @@ +// +// 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: () -> T) -> T { + lock(); defer { unlock() } + return closure() + } + + /// Execute a closure while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + func around(_ closure: () -> Void) { + lock(); defer { unlock() } + 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) -> U) -> U { + lock.around { closure(self.value) } + } + + /// Synchronously modify the protected value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The modified value. + @discardableResult + func write(_ closure: (inout T) -> U) -> U { + lock.around { closure(&self.value) } + } + + subscript(dynamicMember keyPath: WritableKeyPath) -> Property { + get { lock.around { value[keyPath: keyPath] } } + set { lock.around { value[keyPath: keyPath] = newValue } } + } +} + +extension Protected where T: RangeReplaceableCollection { + /// Adds a new element to the end of this protected collection. + /// + /// - Parameter newElement: The `Element` to append. + func append(_ newElement: T.Element) { + write { (ward: inout T) in + ward.append(newElement) + } + } + + /// Adds the elements of a sequence to the end of this protected collection. + /// + /// - Parameter newElements: The `Sequence` to append. + func append(contentsOf newElements: S) where S.Element == T.Element { + write { (ward: inout T) in + ward.append(contentsOf: newElements) + } + } + + /// Add the elements of a collection to the end of the protected collection. + /// + /// - Parameter newElements: The `Collection` to append. + func append(contentsOf newElements: C) where C.Element == T.Element { + write { (ward: inout T) in + ward.append(contentsOf: newElements) + } + } +} + +extension Protected where T == Data? { + /// Adds the contents of a `Data` value to the end of the protected `Data`. + /// + /// - Parameter data: The `Data` to be appended. + func append(_ data: Data) { + write { (ward: inout T) in + ward?.append(data) + } + } +} + +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/sopt_29th_Assignment/Pods/Alamofire/Source/RedirectHandler.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/RedirectHandler.swift new file mode 100644 index 0000000..b6c069c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/RedirectHandler.swift @@ -0,0 +1,95 @@ +// +// 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) + } + } +} diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/Request.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..5ac2929 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,1893 @@ +// +// 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 + } + + /// 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 { $0.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` crated 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 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 + + /// Final cleanup step executed when the instance finishes response serialization. + func cleanup() { + delegate?.cleanup(after: self) + // No-op: override in subclass + } +} + +// 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 updated 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 self.error == nil, let response = self.response else { return } + + let result = validation(self.request, response, self.data) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + self.eventMonitor?.request(self, + didValidateRequest: self.request, + response: response, + data: self.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 self.error == nil, let response = self.response else { return } + + let result = validation(self.request, response) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + self.eventMonitor?.request(self, + didValidateRequest: self.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(byProducingResumeData: { _ in }) + 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 self.error == nil, let response = self.response else { return } + + let result = validation(self.request, response, self.fileURL) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + self.eventMonitor?.request(self, + didValidateRequest: self.request, + response: response, + fileURL: self.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. + /// - 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 = self.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/sopt_29th_Assignment/Pods/Alamofire/Source/RequestInterceptor.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/RequestInterceptor.swift new file mode 100644 index 0000000..1912e9c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/RequestInterceptor.swift @@ -0,0 +1,244 @@ +// +// 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 + +/// 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) +} + +// 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) + } +} + +// 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) + } +} + +// 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 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) + } + } + } +} diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/RequestTaskMap.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/RequestTaskMap.swift new file mode 100644 index 0000000..85b58f3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/Response.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..92e9c44 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,454 @@ +// +// 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. + /// - temporaryURL: The temporary destination `URL` of the data returned from the server. + /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved. + /// - resumeData: The resume `Data` generated if the request was cancelled. + /// - 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/sopt_29th_Assignment/Pods/Alamofire/Source/ResponseSerialization.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..1b77016 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,1116 @@ +// +// 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 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 { $0.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.flatMap { $0.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 + } + + /// 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 { + 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 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 + } +} + +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 + } + + /// 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 { + 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 + } +} + +// 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 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 an instance using 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. + 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 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 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. +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. + /// - 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. + /// - 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. + @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. + /// - 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. + /// - 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. + @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 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. + /// - 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. + /// - 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. + @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. + /// - 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. + /// - 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. + @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`. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the `decoder`. + 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 { + public func serialize(_ data: Data) throws -> Data { data } +} + +/// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values. +public struct StringStreamSerializer: DataStreamSerializer { + public func serialize(_ data: Data) throws -> String { + String(decoding: data, as: UTF8.self) + } +} + +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 + self.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 + self.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/sopt_29th_Assignment/Pods/Alamofire/Source/Result+Alamofire.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Result+Alamofire.swift new file mode 100644 index 0000000..39ac286 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/RetryPolicy.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/RetryPolicy.swift new file mode 100644 index 0000000..e9cbcaf --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/RetryPolicy.swift @@ -0,0 +1,370 @@ +// +// 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 an `ExponentialBackoffRetryPolicy` 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) + } + } +} + +// 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]) + } +} diff --git a/sopt_29th_Assignment/Pods/Alamofire/Source/ServerTrustEvaluation.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/ServerTrustEvaluation.swift new file mode 100644 index 0000000..e5c955a --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/ServerTrustEvaluation.swift @@ -0,0 +1,623 @@ +// +// 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`. + /// + /// - 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)) + } + } + } +} + +/// 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`. + /// + /// - 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)) + } + } +} + +/// 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`. + /// + /// - 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)) + } + } +} + +/// 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`. + /// + /// - 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) + } +} + +/// 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 i `self`. + public var certificates: [SecCertificate] { + (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 { $0.af.publicKey } + } +} + +extension SecCertificate: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecCertificate { + /// The public key for `self`, if it can be extracted. + 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 } + + 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/sopt_29th_Assignment/Pods/Alamofire/Source/Session.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Session.swift new file mode 100644 index 0000000..ac0ab22 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/Session.swift @@ -0,0 +1,1258 @@ +// +// 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.") + + let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.session.sessionDelegateQueue") + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) + + self.init(session: session, + delegate: delegate, + rootQueue: rootQueue, + 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. + /// + /// - 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. + /// - convertible: `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 + } + + adapter.adapt(initialRequest, for: self) { 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/sopt_29th_Assignment/Pods/Alamofire/Source/SessionDelegate.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..a794d83 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/StringEncoding+Alamofire.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/StringEncoding+Alamofire.swift new file mode 100644 index 0000000..8fa6133 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 0000000..455c4bc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/URLEncodedFormEncoder.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/URLEncodedFormEncoder.swift new file mode 100644 index 0000000..a631f75 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Alamofire/Source/URLEncodedFormEncoder.swift @@ -0,0 +1,976 @@ +// +// 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. +/// +/// 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 `Bool` values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +/// +/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` +/// strategy is used, which formats dates from their structure. +/// +/// `SpaceEncoding` can be used to configure how spaces are encoded. Modern encodings use percent replacement (`%20`), +/// while older encodings may expect spaces to be replaced with `+`. +/// +/// 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 + + /// Encodes the key according to the encoding. + /// + /// - Parameter key: The `key` to encode. + /// - Returns: The encoded key. + func encode(_ key: String) -> String { + switch self { + case .brackets: return "\(key)[]" + case .noBrackets: return key + } + } + } + + /// 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 { + 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 `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. + /// - 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, + 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.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) + 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, + 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 + + init(context: URLEncodedFormContext, + codingPath: [CodingKey] = [], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } +} + +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) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func singleValueContainer() -> SingleValueEncodingContainer { + _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } +} + +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 + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } + + private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { + codingPath + [key] + } + } +} + +extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { + func encodeNil(forKey key: Key) throws { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "URLEncodedFormEncoder cannot encode nil values.") + throw EncodingError.invalidValue("\(key): nil", context) + } + + 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) + + return container + } + + func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { + let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + + 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) + + return KeyedEncodingContainer(container) + } + + func superEncoder() -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func superEncoder(forKey key: Key) -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } +} + +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 + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } + + 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 { + try checkCanEncode(value: nil) + defer { canEncodeNewValue = false } + + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "URLEncodedFormEncoder cannot encode nil values.") + throw EncodingError.invalidValue("nil", context) + } + + 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) + 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 + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } + } +} + +extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { + func encodeNil() throws { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "URLEncodedFormEncoder cannot encode nil values.") + throw EncodingError.invalidValue("nil", context) + } + + 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) + } + + 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) + + return KeyedEncodingContainer(container) + } + + func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func superEncoder() -> Encoder { + defer { count += 1 } + + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } +} + +final class URLEncodedFormSerializer { + private let alphabetizeKeyValuePairs: Bool + private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding + private let keyEncoding: URLEncodedFormEncoder.KeyEncoding + private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding + private let allowedCharacters: CharacterSet + + init(alphabetizeKeyValuePairs: Bool, + arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, + keyEncoding: URLEncodedFormEncoder.KeyEncoding, + spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, + allowedCharacters: CharacterSet) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.keyEncoding = keyEncoding + 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 = "[\(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.map { component in + let keyPath = arrayEncoding.encode(key) + 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/sopt_29th_Assignment/Pods/Alamofire/Source/URLRequest+Alamofire.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/URLRequest+Alamofire.swift new file mode 100644 index 0000000..be27c8e --- /dev/null +++ b/sopt_29th_Assignment/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.flatMap(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/sopt_29th_Assignment/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 0000000..292a8fe --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Alamofire/Source/Validation.swift b/sopt_29th_Assignment/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..bd2a279 --- /dev/null +++ b/sopt_29th_Assignment/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: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success(()) + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates 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 statusCode: `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 + self.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 statusCode: `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 + self.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 statusCode: `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 + self.acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/LICENSE b/sopt_29th_Assignment/Pods/Kingfisher/LICENSE new file mode 100644 index 0000000..80888ba --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Kingfisher/README.md b/sopt_29th_Assignment/Pods/Kingfisher/README.md new file mode 100644 index 0000000..f846fd0 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/README.md @@ -0,0 +1,168 @@ +

+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 cache to boost your app. +- [x] View extensions for `UIImageView`, `NSImageView`, `NSButton` and `UIButton` 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] SwiftUI support. + +### Kingfisher 101 + +The simplest use-case is setting an image to an image view with the `UIImageView` extension: + +```swift +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 with the same URL later, the image will be retrieved from cache and shown immediately. + +It also works if you use SwiftUI: + +```swift +import KingfisherSwiftUI + +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 really a very common situation I can meet in my daily work. Think about how many lines you need to write without Kingfisher. You will fall in love with it if you give it a try! + +### Learn More + +To learn the use of Kingfisher by more examples, take a look at the [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet). There we summarized most common tasks in Kingfisher, you can get a better idea on what this framework can do. There are also some tips for performance in the same page, remember to check them too. + +## Requirements + +- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ +- Swift 4.0+ + +[Kingfisher 5.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-5.0-Migration-Guide) - Kingfisher 5.x is NOT fully compatible with version 4.x. However, the 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-5.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 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 has been removed, so please ensure you have no warning left before you migrate from Kingfisher 3 to Kingfisher 4. If you have any trouble in 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](http://onevcat.github.io/Kingfisher/) - Lastly, please remember to read the full whenever you may need a more detailed reference. + +## Other + +### Future of Kingfisher + +I want to keep Kingfisher lightweight. This framework will focus 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 and 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, just [open a ticket](https://github.com/onevcat/Kingfisher/issues/new). Pull requests are warmly welcome as well. + +## Contributors + +This project exists thanks to all the people who contribute. [[Contribute]](https://github.com/onevcat/Kingfisher/blob/master/CONTRIBUTING.md). + + + +## Backers + +Thank you to all our backers! Your support is really important for the project and encourages us to continue. 🙏 [[Become a backer](https://opencollective.com/kingfisher#backer)] + + + + +## Sponsors + +Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/kingfisher#sponsor)] + + + + + + + + + + + + +### License + +Kingfisher is released under the MIT license. See LICENSE for details. diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift new file mode 100644 index 0000000..2290c16 --- /dev/null +++ b/sopt_29th_Assignment/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 + +/// 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? + + /// 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. + /// - Note: + /// This method is deprecated. Please implement the version with + /// `KingfisherParsedOptionsInfo` as parameter instead. + @available(*, deprecated, + message: "Deprecated. Implement the method with same name but with `KingfisherParsedOptionsInfo` instead.") + func image(with data: Data, options: KingfisherOptionsInfo?) -> KFCrossPlatformImage? +} + +extension CacheSerializer { + public func image(with data: Data, options: KingfisherOptionsInfo?) -> KFCrossPlatformImage? { + return image(with: data, options: KingfisherParsedOptionsInfo(options)) + } +} + +/// 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 + + /// 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/DiskStorage.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/DiskStorage.swift new file mode 100644 index 0000000..686928d --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/DiskStorage.swift @@ -0,0 +1,493 @@ +// +// 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") + + /// 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 init(config: Config) throws { + + self.config = config + + let url: URL + if let directory = config.directory { + url = directory + } else { + url = try config.fileManager.url( + for: .cachesDirectory, + in: .userDomainMask, + appropriateFor: nil, + create: true) + } + + let cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)" + directoryURL = config.cachePathBlock(url, cacheName) + + metaChangingQueue = DispatchQueue(label: cacheName) + + try prepareDirectory() + + maybeCachedCheckingQueue.async { + do { + self.maybeCached = Set() + try 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. + 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 { + throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error)) + } + } + + func store( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil) throws + { + 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) + } catch { + 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) + } + } + + 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? + { + 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)) + } + } + + func isCached(forKey key: String) -> Bool { + return isCached(forKey: key, referenceDate: Date()) + } + + 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 + } + } + + 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) + } + + 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`. + /// + /// - 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. + /// + /// - 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. + 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)" + } + 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 + } + + func removeExpiredValues(referenceDate: Date = 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 + } + + 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 + } + + /// Get the total file size of the folder in bytes. + 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 + + let name: String + let fileManager: FileManager + let directory: URL? + + var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = { + (directory, cacheName) in + return directory.appendingPathComponent(cacheName, isDirectory: true) + } + + /// 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) + } + } +} + diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift new file mode 100644 index 0000000..cdfb7c3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift @@ -0,0 +1,118 @@ +// +// 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 + +/// `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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/ImageCache.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/ImageCache.swift new file mode 100644 index 0000000..d99a16c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/ImageCache.swift @@ -0,0 +1,854 @@ +// +// 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 disk 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) + #if swift(>=4.2) + notifications = [ + (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)), + (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)), + (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache)) + ] + #else + notifications = [ + (NSNotification.Name.UIApplicationDidReceiveMemoryWarning, #selector(clearMemoryCache)), + (NSNotification.Name.UIApplicationWillTerminate, #selector(cleanExpiredDiskCache)), + (NSNotification.Name.UIApplicationDidEnterBackground, #selector(backgroundCleanExpiredDiskCache)) + ] + #endif + #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) { + try! self.init(name: 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 totalMemory = ProcessInfo.processInfo.physicalMemory + let costLimit = totalMemory / 4 + let memoryStorage = MemoryStorage.Backend(config: + .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit))) + + var diskConfig = DiskStorage.Config( + name: name, + sizeLimit: 0, + directory: cacheDirectoryURL + ) + if let closure = diskCachePathClosure { + diskConfig.cachePathBlock = closure + } + let diskStorage = try DiskStorage.Backend(config: diskConfig) + diskConfig.cachePathBlock = nil + + self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) + } + + 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, + 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, + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + let computedKey = key.computedKey(with: identifier) + let result: CacheStoreResult + do { + try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration) + 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 { + try? 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() } + } + } + } + + 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) { + let image = options.imageModifier?.modify(image) ?? image + 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 + } + + let finalImage = options.imageModifier?.modify(image) ?? image + // 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( + finalImage, + forKey: key, + options: cacheOptions, + toDisk: false) + { + _ in + callbackQueue.execute { completionHandler(.success(.disk(finalImage))) } + } + case .failure(let error): + callbackQueue.execute { completionHandler(.failure(error)) } + } + } + } + } + + // 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 `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. + 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) + } + + 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. + 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) + } + callbackQueue.execute { completionHandler(.success(image)) } + } catch { + if let error = error as? KingfisherError { + callbackQueue.execute { completionHandler(.failure(error)) } + } else { + 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() { + try? 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) + #if swift(>=4.2) + task = UIBackgroundTaskIdentifier.invalid + #else + task = UIBackgroundTaskInvalid + #endif + } + + 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 { + if let error = error as? KingfisherError { + DispatchQueue.main.async { handler(.failure(error)) } + } else { + assertionFailure("The internal thrown error should be a `KingfisherError`.") + } + + } + } + } + + /// 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 + } +} + +extension Dictionary { + func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { + return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } + } +} + +#if !os(macOS) && !os(watchOS) +// MARK: - For App Extensions +extension UIApplication: KingfisherCompatible { } +extension 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)") + } + } +} + +extension ImageCache { + + /// 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. + /// - path: Location of cache URL on disk. It will be internally pass to the initializer of `DiskStorage` as the + /// disk cache directory. + /// - 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. + @available(*, deprecated, message: "Use `init(name:cacheDirectoryURL:diskCachePathClosure:)` instead", + renamed: "init(name:cacheDirectoryURL:diskCachePathClosure:)") + public convenience init( + name: String, + path: String?, + diskCachePathClosure: DiskCachePathClosure? = nil) throws + { + let directoryURL = path.flatMap { URL(string: $0) } + try self.init(name: name, cacheDirectoryURL: directoryURL, diskCachePathClosure: diskCachePathClosure) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift new file mode 100644 index 0000000..b4abc71 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift @@ -0,0 +1,237 @@ +// +// 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() + } + } + + 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.estimatedExpiration.isPast { + storage.removeObject(forKey: nsKey) + keys.remove(key) + } + } + } + + // Storing in memory will not throw. It is just for meeting protocol requirement and + // forwarding to no throwing method. + func store( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil) throws + { + 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(value, key: key, expiration: expiration) + storage.setObject(object, forKey: key as NSString, cost: value.cacheCost) + keys.insert(key) + } + + /// Use this when you actually access the memory cached item. + /// By default, this will extend the expired data for the accessed item. + /// + /// - Parameters: + /// - key: Cache Key + /// - extendingExpiration: expiration value to extend item expiration time: + /// * .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. + /// - Returns: cached object or nil + func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? { + guard let object = storage.object(forKey: key as NSString) else { + return nil + } + if object.expired { + return nil + } + object.extendExpiration(extendingExpiration) + return object.value + } + + func isCached(forKey key: String) -> Bool { + guard let _ = value(forKey: key, extendingExpiration: .none) else { + return false + } + return true + } + + func remove(forKey key: String) throws { + lock.lock() + defer { lock.unlock() } + storage.removeObject(forKey: key as NSString) + keys.remove(key) + } + + func removeAll() throws { + 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 let cleanInterval: TimeInterval + + /// 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 StorageObject { + let value: T + let expiration: StorageExpiration + let key: String + + private(set) var estimatedExpiration: Date + + init(_ value: T, key: String, expiration: StorageExpiration) { + self.value = value + self.key = key + 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 expired: Bool { + return estimatedExpiration.isPast + } + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/Storage.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/Storage.swift new file mode 100644 index 0000000..fb2b423 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Cache/Storage.swift @@ -0,0 +1,113 @@ +// +// 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 secondsInOneMinute = 60 + static let minutesInOneHour = 60 + static let hoursInOneDay = 24 + 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(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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift new file mode 100644 index 0000000..019158b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift @@ -0,0 +1,420 @@ +// +// 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? + { + var mutatingSelf = self + guard let source = source else { + mutatingSelf.placeholder = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + + 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)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.image = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + 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 { + 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 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 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) + } + + // 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) + 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 } +} + +extension KingfisherWrapper where Base: KFCrossPlatformImageView { + /// Gets the image URL bound to this image view. + @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.") + public private(set) var webURL: URL? { + get { return nil } + set { } + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift new file mode 100644 index 0000000..79b9029 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift @@ -0,0 +1,355 @@ +// +// 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? + { + var mutatingSelf = self + guard let source = source else { + base.image = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.image = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + 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 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) + } + + // 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? + { + var mutatingSelf = self + guard let source = source else { + base.alternateImage = placeholder + mutatingSelf.alternateTaskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + 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 + } + + /// 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) + } + + // 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)} + } +} + +extension KingfisherWrapper where Base: NSButton { + + /// Gets the image URL bound to this button. + @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.") + public private(set) var webURL: URL? { + get { return nil } + set { } + } + + + /// Gets the image URL bound to this button. + @available(*, deprecated, message: "Use `alternateTaskIdentifier` instead to identify a setting task.") + public private(set) var alternateWebURL: URL? { + get { return nil } + set { } + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift new file mode 100644 index 0000000..b3f12bb --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift @@ -0,0 +1,257 @@ +// +// 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: KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + 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 = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.image = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + 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 + #if canImport(UIKit) + attributedView.setNeedsDisplay() + #else + attributedView.setNeedsDisplay(attributedView.bounds) + #endif + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + } + completionHandler?(result) + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + /// 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: KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource.map { .network($0) }, + attributedView: attributedView, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + // 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift new file mode 100644 index 0000000..3fda9a3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift @@ -0,0 +1,398 @@ +// +// 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? + { + guard let source = source else { + base.setImage(placeholder, for: state) + setTaskIdentifier(nil, for: state) + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + 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)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.setImage(image, for: state) + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier(for: state) } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + 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 + } + + /// 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) + } + + // 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? + { + guard let source = source else { + base.setBackgroundImage(placeholder, for: state) + setBackgroundTaskIdentifier(nil, for: state) + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + 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)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.setBackgroundImage(image, for: state) + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.backgroundTaskIdentifier(for: state) } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.backgroundImageTask = $0 }, + 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 + } + + /// 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) + } + + // 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) } + } +} + +extension KingfisherWrapper where Base: UIButton { + + /// Gets the image URL of this button for a specified state. + /// + /// - Parameter state: The state that uses the specified image. + /// - Returns: Current URL for image. + @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.") + public func webURL(for state: UIControl.State) -> URL? { + return nil + } + + /// Gets the background image URL of this button for a specified state. + /// + /// - Parameter state: The state that uses the specified background image. + /// - Returns: Current URL for image. + @available(*, deprecated, message: "Use `backgroundTaskIdentifier` instead to identify a setting task.") + public func backgroundWebURL(for state: UIControl.State) -> URL? { + return nil + } +} +#endif + +#endif diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift new file mode 100644 index 0000000..328facb --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift @@ -0,0 +1,205 @@ +// +// 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? + { + var mutatingSelf = self + guard let source = source else { + base.setImage(placeholder) + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + if !options.keepCurrentImageWhileLoading { + base.setImage(placeholder) + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.setImage(image) + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + 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 + } + + /// 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 +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)} + } +} + +extension KingfisherWrapper where Base: WKInterfaceImage { + /// Gets the image URL bound to this image view. + @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.") + public private(set) var webURL: URL? { + get { return nil } + set { } + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/Deprecated.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/Deprecated.swift new file mode 100644 index 0000000..e0724b5 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/Deprecated.swift @@ -0,0 +1,681 @@ +// +// Deprecated.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. + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#elseif canImport(UIKit) +import UIKit +#endif + +// MARK: - Deprecated +extension KingfisherWrapper where Base: KFCrossPlatformImage { + @available(*, deprecated, message: + "Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `image(with:options:)` instead.") + public static func image( + data: Data, + scale: CGFloat, + preloadAllAnimationData: Bool, + onlyFirstFrame: Bool) -> KFCrossPlatformImage? + { + let options = ImageCreatingOptions( + scale: scale, + duration: 0.0, + preloadAll: preloadAllAnimationData, + onlyFirstFrame: onlyFirstFrame) + return KingfisherWrapper.image(data: data, options: options) + } + + @available(*, deprecated, message: + "Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `animatedImage(with:options:)` instead.") + public static func animated( + with data: Data, + scale: CGFloat = 1.0, + duration: TimeInterval = 0.0, + preloadAll: Bool, + onlyFirstFrame: Bool = false) -> KFCrossPlatformImage? + { + let options = ImageCreatingOptions( + scale: scale, duration: duration, preloadAll: preloadAll, onlyFirstFrame: onlyFirstFrame) + return animatedImage(data: data, options: options) + } +} + +@available(*, deprecated, message: "Will be removed soon. Use `Result` based callback instead") +public typealias CompletionHandler = + ((_ image: KFCrossPlatformImage?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> Void) + +@available(*, deprecated, message: "Will be removed soon. Use `Result` based callback instead") +public typealias ImageDownloaderCompletionHandler = + ((_ image: KFCrossPlatformImage?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> Void) + +// MARK: - Deprecated +@available(*, deprecated, message: "Will be removed soon. Use `DownloadTask` to cancel a task.") +extension RetrieveImageTask { + @available(*, deprecated, message: "RetrieveImageTask.empty will be removed soon. Use `nil` to represent a no task.") + public static let empty = RetrieveImageTask() +} + +// MARK: - Deprecated +extension KingfisherManager { + /// Get an image with resource. + /// If `.empty` is used as `options`, Kingfisher will seek the image in memory and disk first. + /// If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`. + /// These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. + /// + /// - Parameters: + /// - resource: Resource object contains information such as `cacheKey` and `downloadURL`. + /// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called every time downloaded data changed. This could be used as a progress UI. + /// - completionHandler: Called when the whole retrieving process finished. + /// - Returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. + @available(*, deprecated, message: "Use `Result` based callback instead.") + @discardableResult + public func retrieveImage(with resource: Resource, + options: KingfisherOptionsInfo?, + progressBlock: DownloadProgressBlock?, + completionHandler: CompletionHandler?) -> DownloadTask? + { + return retrieveImage(with: resource, options: options, progressBlock: progressBlock) { + result in + switch result { + case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url) + case .failure(let error): completionHandler?(nil, error as NSError, .none, resource.downloadURL) + } + } + } +} + +// MARK: - Deprecated +extension ImageDownloader { + @available(*, deprecated, message: "Use `Result` based callback instead.") + @discardableResult + open func downloadImage(with url: URL, + retrieveImageTask: RetrieveImageTask? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: ImageDownloaderProgressBlock? = nil, + completionHandler: ImageDownloaderCompletionHandler?) -> DownloadTask? + { + return downloadImage(with: url, options: options, progressBlock: progressBlock) { + result in + switch result { + case .success(let value): completionHandler?(value.image, nil, value.url, value.originalData) + case .failure(let error): completionHandler?(nil, error as NSError, nil, nil) + } + } + } +} + +@available(*, deprecated, message: "RetrieveImageDownloadTask is removed. Use `DownloadTask` to cancel a task.") +public struct RetrieveImageDownloadTask { +} + +@available(*, deprecated, message: "RetrieveImageTask is removed. Use `DownloadTask` to cancel a task.") +public final class RetrieveImageTask { +} + +@available(*, deprecated, message: "Use `DownloadProgressBlock` instead.", renamed: "DownloadProgressBlock") +public typealias ImageDownloaderProgressBlock = DownloadProgressBlock + +#if !os(watchOS) +// MARK: - Deprecated +extension KingfisherWrapper where Base: KFCrossPlatformImageView { + @available(*, deprecated, message: "Use `Result` based callback instead.") + @discardableResult + public func setImage(with resource: Resource?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler?) -> DownloadTask? + { + return setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock) { + result in + switch result { + case .success(let value): + completionHandler?(value.image, nil, value.cacheType, value.source.url) + case .failure(let error): + completionHandler?(nil, error as NSError, .none, nil) + } + } + } +} +#endif + +#if canImport(UIKit) && !os(watchOS) +// MARK: - Deprecated +extension KingfisherWrapper where Base: UIButton { + @available(*, deprecated, message: "Use `Result` based callback instead.") + @discardableResult + public func setImage( + with resource: Resource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler?) -> DownloadTask? + { + return setImage( + with: resource, + for: state, + placeholder: placeholder, + options: options, + progressBlock: progressBlock) + { + result in + switch result { + case .success(let value): + completionHandler?(value.image, nil, value.cacheType, value.source.url) + case .failure(let error): + completionHandler?(nil, error as NSError, .none, nil) + } + } + } + + @available(*, deprecated, message: "Use `Result` based callback instead.") + @discardableResult + public func setBackgroundImage( + with resource: Resource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler?) -> DownloadTask? + { + return setBackgroundImage( + with: resource, + for: state, + placeholder: placeholder, + options: options, + progressBlock: progressBlock) + { + result in + switch result { + case .success(let value): + completionHandler?(value.image, nil, value.cacheType, value.source.url) + case .failure(let error): + completionHandler?(nil, error as NSError, .none, nil) + } + } + } +} +#endif + +#if os(watchOS) +import WatchKit +// MARK: - Deprecated +extension KingfisherWrapper where Base: WKInterfaceImage { + @available(*, deprecated, message: "Use `Result` based callback instead.") + @discardableResult + public func setImage(_ resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler?) -> DownloadTask? + { + return setImage( + with: resource, + placeholder: placeholder, + options: options, + progressBlock: progressBlock) + { + result in + switch result { + case .success(let value): + completionHandler?(value.image, nil, value.cacheType, value.source.url) + case .failure(let error): + completionHandler?(nil, error as NSError, .none, nil) + } + } + } +} +#endif + +#if os(macOS) +// MARK: - Deprecated +extension KingfisherWrapper where Base: NSButton { + @discardableResult + @available(*, deprecated, message: "Use `Result` based callback instead.") + public func setImage(with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler?) -> DownloadTask? + { + return setImage( + with: resource, + placeholder: placeholder, + options: options, + progressBlock: progressBlock) + { + result in + switch result { + case .success(let value): + completionHandler?(value.image, nil, value.cacheType, value.source.url) + case .failure(let error): + completionHandler?(nil, error as NSError, .none, nil) + } + } + } + + @discardableResult + @available(*, deprecated, message: "Use `Result` based callback instead.") + public func setAlternateImage(with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: CompletionHandler?) -> DownloadTask? + { + return setAlternateImage( + with: resource, + placeholder: placeholder, + options: options, + progressBlock: progressBlock) + { + result in + switch result { + case .success(let value): + completionHandler?(value.image, nil, value.cacheType, value.source.url) + case .failure(let error): + completionHandler?(nil, error as NSError, .none, nil) + } + } + } +} +#endif + +// MARK: - Deprecated +extension ImageCache { + /// The largest cache cost of memory cache. The total cost is pixel count of + /// all cached images in memory. + /// Default is unlimited. Memory cache will be purged automatically when a + /// memory warning notification is received. + @available(*, deprecated, message: "Use `memoryStorage.config.totalCostLimit` instead.", + renamed: "memoryStorage.config.totalCostLimit") + open var maxMemoryCost: Int { + get { return memoryStorage.config.totalCostLimit } + set { memoryStorage.config.totalCostLimit = newValue } + } + + /// The default DiskCachePathClosure + @available(*, deprecated, message: "Not needed anymore.") + public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String { + let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + return (dstPath as NSString).appendingPathComponent(cacheName) + } + + /// The default file extension appended to cached files. + @available(*, deprecated, message: "Use `diskStorage.config.pathExtension` instead.", + renamed: "diskStorage.config.pathExtension") + open var pathExtension: String? { + get { return diskStorage.config.pathExtension } + set { diskStorage.config.pathExtension = newValue } + } + + ///The disk cache location. + @available(*, deprecated, message: "Use `diskStorage.directoryURL.absoluteString` instead.", + renamed: "diskStorage.directoryURL.absoluteString") + public var diskCachePath: String { + return diskStorage.directoryURL.absoluteString + } + + /// The largest disk size can be taken for the cache. It is the total + /// allocated size of cached files in bytes. + /// Default is no limit. + @available(*, deprecated, message: "Use `diskStorage.config.sizeLimit` instead.", + renamed: "diskStorage.config.sizeLimit") + open var maxDiskCacheSize: UInt { + get { return UInt(diskStorage.config.sizeLimit) } + set { diskStorage.config.sizeLimit = newValue } + } + + @available(*, deprecated, message: "Use `diskStorage.cacheFileURL(forKey:).path` instead.", + renamed: "diskStorage.cacheFileURL(forKey:)") + open func cachePath(forComputedKey key: String) -> String { + return diskStorage.cacheFileURL(forKey: key).path + } + + /** + Get an image for a key from disk. + + - parameter key: Key for the image. + - parameter options: Options of retrieving image. If you need to retrieve an image which was + stored with a specified `ImageProcessor`, pass the processor in the option too. + + - returns: The image object if it is cached, or `nil` if there is no such key in the cache. + */ + @available(*, deprecated, + message: "Use `Result` based `retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)` instead.", + renamed: "retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)") + open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage? { + let options = KingfisherParsedOptionsInfo(options ?? .empty) + let computedKey = key.computedKey(with: options.processor.identifier) + do { + if let data = try diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) { + return options.cacheSerializer.image(with: data, options: options) + } + } catch {} + return nil + } + + @available(*, deprecated, + message: "Use `Result` based `retrieveImage(forKey:options:callbackQueue:completionHandler:)` instead.", + renamed: "retrieveImage(forKey:options:callbackQueue:completionHandler:)") + open func retrieveImage(forKey key: String, + options: KingfisherOptionsInfo?, + completionHandler: ((KFCrossPlatformImage?, CacheType) -> Void)?) + { + retrieveImage( + forKey: key, + options: options, + callbackQueue: .dispatch((options ?? .empty).callbackDispatchQueue)) + { + result in + do { + let value = try result.get() + completionHandler?(value.image, value.cacheType) + } catch { + completionHandler?(nil, .none) + } + } + } + + /// The longest time duration in second of the cache being stored in disk. + /// Default is 1 week (60 * 60 * 24 * 7 seconds). + /// Setting this to a negative value will make the disk cache never expiring. + @available(*, deprecated, message: "Deprecated. Use `diskStorage.config.expiration` instead") + open var maxCachePeriodInSecond: TimeInterval { + get { return diskStorage.config.expiration.timeInterval } + set { diskStorage.config.expiration = newValue < 0 ? .never : .seconds(newValue) } + } + + @available(*, deprecated, message: "Use `Result` based callback instead.") + open func store(_ image: KFCrossPlatformImage, + original: Data? = nil, + forKey key: String, + processorIdentifier identifier: String = "", + cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, + toDisk: Bool = true, + completionHandler: (() -> Void)?) + { + store( + image, + original: original, + forKey: key, + processorIdentifier: identifier, + cacheSerializer: serializer, + toDisk: toDisk) + { + _ in + completionHandler?() + } + } + + @available(*, deprecated, message: "Use the `Result`-based `calculateDiskStorageSize` instead.") + open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> Void)) { + calculateDiskStorageSize { result in + let size: UInt? = try? result.get() + handler(size ?? 0) + } + } +} + +// MARK: - Deprecated +extension Collection where Iterator.Element == KingfisherOptionsInfoItem { + /// The queue of callbacks should happen from Kingfisher. + @available(*, deprecated, message: "Use `callbackQueue` instead.", renamed: "callbackQueue") + public var callbackDispatchQueue: DispatchQueue { + return KingfisherParsedOptionsInfo(Array(self)).callbackQueue.queue + } +} + +/// Error domain of Kingfisher +@available(*, deprecated, message: "Use `KingfisherError.domain` instead.", renamed: "KingfisherError.domain") +public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error" + +/// Key will be used in the `userInfo` of `.invalidStatusCode` +@available(*, unavailable, +message: "Use `.invalidHTTPStatusCode` or `isInvalidResponseStatusCode` of `KingfisherError` instead for the status code.") +public let KingfisherErrorStatusCodeKey = "statusCode" + +// MARK: - Deprecated +extension Collection where Iterator.Element == KingfisherOptionsInfoItem { + /// The target `ImageCache` which is used. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `targetCache` instead.") + public var targetCache: ImageCache? { + return KingfisherParsedOptionsInfo(Array(self)).targetCache + } + + /// The original `ImageCache` which is used. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `originalCache` instead.") + public var originalCache: ImageCache? { + return KingfisherParsedOptionsInfo(Array(self)).originalCache + } + + /// The `ImageDownloader` which is specified. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloader` instead.") + public var downloader: ImageDownloader? { + return KingfisherParsedOptionsInfo(Array(self)).downloader + } + + /// Member for animation transition when using UIImageView. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `transition` instead.") + public var transition: ImageTransition { + return KingfisherParsedOptionsInfo(Array(self)).transition + } + + /// A `Float` value set as the priority of image download task. The value for it should be + /// between 0.0~1.0. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloadPriority` instead.") + public var downloadPriority: Float { + return KingfisherParsedOptionsInfo(Array(self)).downloadPriority + } + + /// Whether an image will be always downloaded again or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceRefresh` instead.") + public var forceRefresh: Bool { + return KingfisherParsedOptionsInfo(Array(self)).forceRefresh + } + + /// Whether an image should be got only from memory cache or download. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `fromMemoryCacheOrRefresh` instead.") + public var fromMemoryCacheOrRefresh: Bool { + return KingfisherParsedOptionsInfo(Array(self)).fromMemoryCacheOrRefresh + } + + /// Whether the transition should always happen or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceTransition` instead.") + public var forceTransition: Bool { + return KingfisherParsedOptionsInfo(Array(self)).forceTransition + } + + /// Whether cache the image only in memory or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheMemoryOnly` instead.") + public var cacheMemoryOnly: Bool { + return KingfisherParsedOptionsInfo(Array(self)).cacheMemoryOnly + } + + /// Whether the caching operation will be waited or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `waitForCache` instead.") + public var waitForCache: Bool { + return KingfisherParsedOptionsInfo(Array(self)).waitForCache + } + + /// Whether only load the images from cache or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyFromCache` instead.") + public var onlyFromCache: Bool { + return KingfisherParsedOptionsInfo(Array(self)).onlyFromCache + } + + /// Whether the image should be decoded in background or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `backgroundDecode` instead.") + public var backgroundDecode: Bool { + return KingfisherParsedOptionsInfo(Array(self)).backgroundDecode + } + + /// Whether the image data should be all loaded at once if it is an animated image. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `preloadAllAnimationData` instead.") + public var preloadAllAnimationData: Bool { + return KingfisherParsedOptionsInfo(Array(self)).preloadAllAnimationData + } + + /// The `CallbackQueue` on which completion handler should be invoked. + /// If not set in the options, `.mainCurrentOrAsync` will be used. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `callbackQueue` instead.") + public var callbackQueue: CallbackQueue { + return KingfisherParsedOptionsInfo(Array(self)).callbackQueue + } + + /// The scale factor which should be used for the image. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `scaleFactor` instead.") + public var scaleFactor: CGFloat { + return KingfisherParsedOptionsInfo(Array(self)).scaleFactor + } + + /// The `ImageDownloadRequestModifier` will be used before sending a download request. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `requestModifier` instead.") + public var modifier: ImageDownloadRequestModifier? { + return KingfisherParsedOptionsInfo(Array(self)).requestModifier + } + + /// `ImageProcessor` for processing when the downloading finishes. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `processor` instead.") + public var processor: ImageProcessor { + return KingfisherParsedOptionsInfo(Array(self)).processor + } + + /// `ImageModifier` for modifying right before the image is displayed. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `imageModifier` instead.") + public var imageModifier: ImageModifier? { + return KingfisherParsedOptionsInfo(Array(self)).imageModifier + } + + /// `CacheSerializer` to convert image to data for storing in cache. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheSerializer` instead.") + public var cacheSerializer: CacheSerializer { + return KingfisherParsedOptionsInfo(Array(self)).cacheSerializer + } + + /// Keep the existing image while setting another image to an image view. + /// Or the placeholder will be used while downloading. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `keepCurrentImageWhileLoading` instead.") + public var keepCurrentImageWhileLoading: Bool { + return KingfisherParsedOptionsInfo(Array(self)).keepCurrentImageWhileLoading + } + + /// Whether the options contains `.onlyLoadFirstFrame`. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyLoadFirstFrame` instead.") + public var onlyLoadFirstFrame: Bool { + return KingfisherParsedOptionsInfo(Array(self)).onlyLoadFirstFrame + } + + /// Whether the options contains `.cacheOriginalImage`. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheOriginalImage` instead.") + public var cacheOriginalImage: Bool { + return KingfisherParsedOptionsInfo(Array(self)).cacheOriginalImage + } + + /// The image which should be used when download image request fails. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onFailureImage` instead.") + public var onFailureImage: Optional { + return KingfisherParsedOptionsInfo(Array(self)).onFailureImage + } + + /// Whether the `ImagePrefetcher` should load images to memory in an aggressive way or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `alsoPrefetchToMemory` instead.") + public var alsoPrefetchToMemory: Bool { + return KingfisherParsedOptionsInfo(Array(self)).alsoPrefetchToMemory + } + + /// Whether the disk storage file loading should happen in a synchronous behavior or not. + @available(*, deprecated, + message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `loadDiskFileSynchronously` instead.") + public var loadDiskFileSynchronously: Bool { + return KingfisherParsedOptionsInfo(Array(self)).loadDiskFileSynchronously + } +} + +/// The default modifier. +/// It does nothing and returns the image as is. +@available(*, deprecated, message: "Use `nil` in KingfisherOptionsInfo to indicate no modifier.") +public struct DefaultImageModifier: ImageModifier { + + /// A default `DefaultImageModifier` which can be used everywhere. + public static let `default` = DefaultImageModifier() + private init() {} + + /// Modifies an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { return image } +} + + +#if os(macOS) +@available(*, deprecated, message: "Use `KFCrossPlatformImage` instead.") +public typealias Image = KFCrossPlatformImage +@available(*, deprecated, message: "Use `KFCrossPlatformView` instead.") +public typealias View = KFCrossPlatformView +@available(*, deprecated, message: "Use `KFCrossPlatformColor` instead.") +public typealias Color = KFCrossPlatformColor +@available(*, deprecated, message: "Use `KFCrossPlatformImageView` instead.") +public typealias ImageView = KFCrossPlatformImageView +@available(*, deprecated, message: "Use `KFCrossPlatformButton` instead.") +public typealias Button = KFCrossPlatformButton +#else +@available(*, deprecated, message: "Use `KFCrossPlatformImage` instead.") +public typealias Image = KFCrossPlatformImage +@available(*, deprecated, message: "Use `KFCrossPlatformColor` instead.") +public typealias Color = KFCrossPlatformColor + #if !os(watchOS) + @available(*, deprecated, message: "Use `KFCrossPlatformImageView` instead.") + public typealias ImageView = KFCrossPlatformImageView + @available(*, deprecated, message: "Use `KFCrossPlatformView` instead.") + public typealias View = KFCrossPlatformView + @available(*, deprecated, message: "Use `KFCrossPlatformButton` instead.") + public typealias Button = KFCrossPlatformButton + #endif +#endif diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift new file mode 100644 index 0000000..db5e2b4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift @@ -0,0 +1,137 @@ +// +// 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 { + return (assetImageGenerator.asset as? AVURLAsset)?.url.absoluteString ?? UUID().uuidString + } + + /// 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) + 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), + let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) + else { + return nil + } + CGImageDestinationAddImage(destination, self, nil) + guard CGImageDestinationFinalize(destination) else { return nil } + return mutableData as Data + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift new file mode 100644 index 0000000..f303107 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift @@ -0,0 +1,157 @@ +// +// 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 } +} + +/// 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 + + // 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. + public init(fileURL: URL, cacheKey: String? = nil) { + self.fileURL = fileURL + self.cacheKey = cacheKey ?? fileURL.absoluteString + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public var cacheKey: String + + public func data(handler: (Result) -> Void) { + handler(Result(catching: { try Data(contentsOf: fileURL) })) + } + + /// 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift new file mode 100644 index 0000000..8514384 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift @@ -0,0 +1,86 @@ +// +// 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() -> Source { + return downloadURL.isFileURL ? + .provider(LocalFileImageDataProvider(fileURL: downloadURL, cacheKey: cacheKey)) : + .network(self) + } +} + +/// 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.absoluteString + } + + // 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 absoluteString } + public var downloadURL: URL { return self } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/Source.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/Source.swift new file mode 100644 index 0000000..79680ab --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/ImageSource/Source.swift @@ -0,0 +1,97 @@ +// +// 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 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 { + var asResource: Resource? { + guard case .network(let resource) = self else { + return nil + } + return resource + } + + var asProvider: ImageDataProvider? { + guard case .provider(let provider) = self else { + return nil + } + return provider + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/Kingfisher.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/Kingfisher.swift new file mode 100644 index 0000000..946fee8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/Kingfisher.swift @@ -0,0 +1,90 @@ +// +// 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 +#else +import WatchKit +#endif +#endif + +/// Wrapper for Kingfisher compatible types. This type provides an extension point for +/// connivence 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 diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherError.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherError.swift new file mode 100644 index 0000000..a3262f4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherError.swift @@ -0,0 +1,437 @@ +// +// 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 + +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) + } + + /// 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) + } + + + /// 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 + } +} + +// 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)," + } + } + + 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 + } + } +} + +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)." + } + } + + 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 + } + } +} + +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/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherManager.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherManager.swift new file mode 100644 index 0000000..dff8ab9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherManager.swift @@ -0,0 +1,741 @@ +// +// 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 + +/// 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 +} + +/// 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`. + /// + public func retrieveImage( + with source: Source, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + let options = currentDefaultOptions + (options ?? .empty) + var info = KingfisherParsedOptionsInfo(options) + if let block = progressBlock { + info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + return retrieveImage( + with: source, + options: info, + downloadTaskUpdated: downloadTaskUpdated, + completionHandler: completionHandler) + } + + func retrieveImage( + with source: Source, + options: KingfisherParsedOptionsInfo, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + 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 + } + if let nextSource = retrievingContext.popAlternativeSource() { + 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 { + + // Skip alternative sources if the user cancelled it. + guard !error.isTaskCancelled else { + completionHandler?(.failure(error)) + return + } + if let nextSource = retrievingContext.popAlternativeSource() { + retrievingContext.appendError(error, to: currentSource) + 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: currentSource) + let finalError = KingfisherError.imageSettingError( + reason: .alternativeSourcesExhausted(retrievingContext.propagationErrors) + ) + completionHandler?(.failure(finalError)) + } + } + } + } + } + + 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 + } + + let finalImage = options.imageModifier?.modify(image) ?? image + options.callbackQueue.execute { + let result = ImageLoadingResult(image: finalImage, 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) + // 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) { + let result = RetrieveImageResult( + image: value.image, + cacheType: .none, + source: source, + originalSource: context.originalSource + ) + 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) { + let result = RetrieveImageResult( + image: value.image, + cacheType: .none, + source: source, + originalSource: context.originalSource + ) + completionHandler?(.success(result)) + } + } + } + + coordinator.apply(.cacheInitiated) { + let result = RetrieveImageResult( + image: value.image, + cacheType: .none, + source: source, + originalSource: context.originalSource + ) + 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 } + options.callbackQueue.execute { + result.match( + onSuccess: { cacheResult in + let value: Result + if let image = cacheResult.image { + value = result.map { + RetrieveImageResult( + image: image, + cacheType: $0.cacheType, + source: source, + originalSource: context.originalSource + ) + } + } else { + value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))) + } + completionHandler(value) + }, + onFailure: { _ in + 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) + + targetCache.store( + processedImage, + forKey: key, + options: cacheOptions, + toDisk: !options.cacheMemoryOnly) + { + _ in + coordinator.apply(.cachingImage) { + let value = RetrieveImageResult( + image: processedImage, + cacheType: .none, + source: source, + originalSource: context.originalSource + ) + options.callbackQueue.execute { completionHandler?(.success(value)) } + } + } + + coordinator.apply(.cacheInitiated) { + let value = RetrieveImageResult( + image: processedImage, + cacheType: .none, + source: source, + originalSource: context.originalSource + ) + options.callbackQueue.execute { completionHandler?(.success(value)) } + } + } + }, + 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift new file mode 100644 index 0000000..629cd67 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift @@ -0,0 +1,386 @@ +// +// 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 fire a download task for the resource. + 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 an error. + 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 of this member will be used as the target queue of dispatch callbacks when + /// retrieving images from cache. If not set, Kingfisher will use main queue for callbacks. + @available(*, deprecated, message: "Use `.callbackQueue(CallbackQueue)` instead.") + case callbackDispatchQueue(DispatchQueue?) + + /// 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(ImageDownloadRequestModifier) + + /// 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) + + /// Supplies 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 a 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 a downloading 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 + + /// 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 `ImageProgressive` of + 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) +} + +// 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: ImageDownloadRequestModifier? = 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 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 + + 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 .callbackDispatchQueue(let value): callbackQueue = value.map { .dispatch($0) } ?? .mainCurrentOrAsync + 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 + } + } + + 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) { + DispatchQueue.main.async { + guard self.onShouldApply() else { return } + guard let expectedContentLength = task.task.response?.expectedContentLength, + expectedContentLength != -1 else + { + return + } + + let dataLength = Int64(task.mutableData.count) + self.block(dataLength, expectedContentLength) + } + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Filter.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Filter.swift new file mode 100644 index 0000000..6e4b386 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Filter.swift @@ -0,0 +1,146 @@ +// +// 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) + +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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift new file mode 100644 index 0000000..4685583 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift @@ -0,0 +1,121 @@ +// +// 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. +class GIFAnimatedImage { + let images: [KFCrossPlatformImage] + let duration: TimeInterval + + init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) { + let frameCount = CGImageSourceGetCount(imageSource) + var images = [KFCrossPlatformImage]() + var gifDuration = 0.0 + + for i in 0 ..< frameCount { + guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else { + return nil + } + + if frameCount == 1 { + gifDuration = .infinity + } else { + // Get current animated GIF frame duration + gifDuration += GIFAnimatedImage.getFrameDuration(from: imageSource, at: i) + } + images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil)) + if options.onlyFirstFrame { break } + } + self.images = images + self.duration = gifDuration + } + + // Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary. + 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`. + 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) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Image.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Image.swift new file mode 100644 index 0000000..da757ca --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Image.swift @@ -0,0 +1,377 @@ +// +// 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 + +private var animatedImageDataKey: Void? + +// MARK: - Image Properties +extension KingfisherWrapper where Base: KFCrossPlatformImage { + private(set) var animatedImageData: Data? { + get { return getAssociatedObject(base, &animatedImageDataKey) } + set { setRetainedAssociatedObject(base, &animatedImageDataKey, 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 } + + private(set) var imageSource: CGImageSource? { + 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 + } + return pixel * cgImage.bitsPerPixel / 8 + } +} + +// 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 + #if swift(>=4.2) + return base.pngData() + #else + return UIImagePNGRepresentation(base) + #endif + #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 + #if swift(>=4.2) + return base.jpegData(compressionQuality: compressionQuality) + #else + return UIImageJPEGRepresentation(base, compressionQuality) + #endif + #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. + /// + /// - Parameter format: The format in which the output data should be. If `unknown`, the `base` image will be + /// converted in the PNG representation. + /// + /// - Returns: The output data representing. + + /// 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. + 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? { + let info: [String: Any] = [ + kCGImageSourceShouldCache as String: true, + kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF + ] + + guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else { + return nil + } + + #if os(macOS) + guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else { + return nil + } + var image: KFCrossPlatformImage? + if options.onlyFirstFrame { + image = animatedImage.images.first + } else { + image = KFCrossPlatformImage(data: data) + var kf = image?.kf + kf?.images = animatedImage.images + kf?.duration = animatedImage.duration + } + image?.kf.animatedImageData = data + 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: imageSource, for: info, 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 = data + } else { + image = KFCrossPlatformImage(data: data, scale: options.scale) + var kf = image?.kf + kf?.imageSource = imageSource + kf?.animatedImageData = data + } + + 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 input size 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 = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary + guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { + return nil + } + return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageDrawing.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageDrawing.swift new file mode 100644 index 0000000..6449431 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageDrawing.swift @@ -0,0 +1,543 @@ +// +// 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) { _ 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) { _ 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(withRoundRadius radius: CGFloat, + 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) { _ in + #if os(macOS) + if let backgroundColor = backgroundColor { + let rectPath = NSBezierPath(rect: rect) + backgroundColor.setFill() + rectPath.fill() + } + + let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius) + #if swift(>=4.2) + path.windingRule = .evenOdd + #else + path.windingRule = .evenOddWindingRule + #endif + 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 = UIBezierPath( + roundedRect: rect, + byRoundingCorners: corners.uiRectCorner, + cornerRadii: CGSize(width: radius, height: radius) + ) + context.addPath(path.cgPath) + context.clip() + base.draw(in: rect) + #endif + return false + } + } + + #if os(iOS) || os(tvOS) + 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) { _ 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) + } + + guard let context = beginContext(size: size, scale: scale, inverting: true) 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)) + endContext() + + var inBuffer = createEffectBuffer(context) + + guard let outContext = beginContext(size: size, scale: scale, inverting: true) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + defer { endContext() } + 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 + } + + // 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) { 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) + if imageSource != 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 + } + } +} + +extension KingfisherWrapper where Base: KFCrossPlatformImage { + + func beginContext(size: CGSize, scale: CGFloat, inverting: Bool = false) -> 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 + NSGraphicsContext.saveGraphicsState() + guard let context = NSGraphicsContext(bitmapImageRep: rep) else { + assertionFailure("[Kingfisher] Image context cannot be created.") + return nil + } + + NSGraphicsContext.current = context + return context.cgContext + #else + UIGraphicsBeginImageContextWithOptions(size, false, scale) + 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 + } + + func endContext() { + #if os(macOS) + NSGraphicsContext.restoreGraphicsState() + #else + UIGraphicsEndImageContext() + #endif + } + + func draw( + to size: CGSize, + inverting: Bool = false, + scale: CGFloat? = nil, + refImage: KFCrossPlatformImage? = nil, + draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`) + ) -> KFCrossPlatformImage + { + let targetScale = scale ?? self.scale + guard let context = beginContext(size: size, scale: targetScale, inverting: inverting) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + defer { endContext() } + 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) + } + + #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) { context in + image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0) + return false + } + } + #endif +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageFormat.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageFormat.swift new file mode 100644 index 0000000..14e3c7d --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageFormat.swift @@ -0,0 +1,131 @@ +// +// 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 + } + + var buffer = [UInt8](repeating: 0, count: base.count) + base.copyBytes(to: &buffer, count: base.count) + for (index, item) in buffer.enumerated() { + guard + item == marker.bytes.first, + buffer.count > index + 1, + buffer[index + 1] == marker.bytes[1] else { + continue + } + return true + } + return false + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageProcessor.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageProcessor.swift new file mode 100644 index 0000000..8cdabe8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageProcessor.swift @@ -0,0 +1,923 @@ +// +// 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 +#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 `image` 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 `image` 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: 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. + /// - Note: + /// This method is deprecated. Please implement the version with + /// `KingfisherParsedOptionsInfo` as parameter instead. + @available(*, deprecated, + message: "Deprecated. Implement the method with same name but with `KingfisherParsedOptionsInfo` instead.") + func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> KFCrossPlatformImage? + + /// 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 { + public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> KFCrossPlatformImage? { + return process(item: item, options: KingfisherParsedOptionsInfo(options)) + } +} + +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.hex)") + } + 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.hex)") + } + 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 + +/// 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 { + + /// 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 + } + } + } + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Corner radius will be applied in processing. To provide backward compatibility, this property returns `0` unless + /// `Radius.point` is specified. + @available(*, deprecated, message: "Use `radius` property instead.") + public var cornerRadius: CGFloat { + switch radius { + case .widthFraction, .heightFraction: + return 0.0 + case .point(let value): + return value + } + } + + /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the + /// target image with `.fraction`. `.fraction(0.5)` means use half of the + 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 + + let cornerRadius: CGFloat + switch radius { + case .point(let point): + cornerRadius = point + case .widthFraction(let widthFraction): + cornerRadius = size.width * widthFraction + case .heightFraction(let heightFraction): + cornerRadius = size.height * heightFraction + } + + return image.kf.scaled(to: options.scaleFactor) + .kf.image( + withRoundRadius: cornerRadius, + fit: size, + roundingCorners: roundingCorners, + backgroundColor: backgroundColor) + 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 takes 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.hex)_\(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.hex))" + } + + /// 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 downsample the input data directly to an +/// image. It is a more efficient than `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) + } + } +} + +/// Concatenates two `ImageProcessor`s. `ImageProcessor.append(another:)` is used internally. +/// +/// - Parameters: +/// - left: The first processor. +/// - right: The second processor. +/// - Returns: The concatenated processor. +@available(*, deprecated, +message: "Will be removed soon. Use `|>` instead.", +renamed: "|>") +public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { + return left.append(another: right) +} + +infix operator |>: AdditionPrecedence +public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { + return left.append(another: right) +} + +extension KFCrossPlatformColor { + var hex: String { + var r: CGFloat = 0 + var g: CGFloat = 0 + var b: CGFloat = 0 + var a: CGFloat = 0 + + #if os(macOS) + (usingColorSpace(.sRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a) + #else + getRed(&r, green: &g, blue: &b, alpha: &a) + #endif + + let rInt = Int(r * 255) << 24 + let gInt = Int(g * 255) << 16 + let bInt = Int(b * 255) << 8 + let aInt = Int(a * 255) + + let rgba = rInt | gInt | bInt | aInt + + return String(format:"#%08x", rgba) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageProgressive.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageProgressive.swift new file mode 100644 index 0000000..218bafc --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageProgressive.swift @@ -0,0 +1,325 @@ +// +// 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 + +private let sharedProcessingQueue: CallbackQueue = + .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) + +public struct ImageProgressive { + + /// A default `ImageProgressive` could be used across. + 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 + + public init(isBlur: Bool, + isFastestScan: Bool, + scanInterval: TimeInterval) { + self.isBlur = isBlur + self.isFastestScan = isFastestScan + self.scanInterval = scanInterval + } +} + +protocol ImageSettable: AnyObject { + var image: KFCrossPlatformImage? { get set } +} + +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? + var count: Int { return items.count } + + 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 notify(_ closure: @escaping () -> Void) { + self.notify = closure + } + + func clean() { + queue.async { [weak self] in + guard let self = self else { return } + self.items.forEach { $0.cancel() } + self.items.removeAll() + } + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageTransition.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageTransition.swift new file mode 100644 index 0000000..c13a9d2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/ImageTransition.swift @@ -0,0 +1,115 @@ +// +// 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. + +#if os(iOS) || os(tvOS) +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 +} +#endif diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Placeholder.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Placeholder.swift new file mode 100644 index 0000000..1179815 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Image/Placeholder.swift @@ -0,0 +1,80 @@ +// +// 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 os(macOS) +import AppKit +#else +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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Kingfisher.h b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Kingfisher.h new file mode 100644 index 0000000..356adde --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Kingfisher.h @@ -0,0 +1,37 @@ +// +// Kingfisher.h +// 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 + +//! Project version number for Kingfisher. +FOUNDATION_EXPORT double KingfisherVersionNumber; + +//! Project version string for Kingfisher. +FOUNDATION_EXPORT const unsigned char KingfisherVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift new file mode 100644 index 0000000..5f6fc57 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift @@ -0,0 +1,91 @@ +// +// 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 + +/// Protocol indicates that an authentication challenge could be handled. +public protocol AuthenticationChallengeResponsable: 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 AuthenticationChallengeResponsable { + + 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift new file mode 100644 index 0000000..51e9705 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift @@ -0,0 +1,80 @@ +// +// 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 { + var finalImage = image + if let imageModifier = callback.options.imageModifier { + finalImage = imageModifier.modify(image) + } + if callback.options.backgroundDecode { + finalImage = finalImage.kf.decoded + } + 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift new file mode 100644 index 0000000..1fc443f --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift @@ -0,0 +1,377 @@ +// +// 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 + +/// 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 +} + +/// 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) + } + } + + /// 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: AuthenticationChallengeResponsable? + + private let name: String + private let sessionDelegate: SessionDelegate + 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.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 + guard let url = task.originalURL else { + return task.mutableData + } + return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, for: url) + } + } + + // MARK: Dowloading 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? + { + // Creates default request. + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout) + request.httpShouldUsePipelining = requestsUsePipelining + + if let requestModifier = options.requestModifier { + // Modifies request before sending. + guard let r = requestModifier.modified(for: request) else { + options.callbackQueue.execute { + completionHandler?(.failure(KingfisherError.requestError(reason: .emptyRequest))) + } + return nil + } + request = r + } + + // There is a possibility that request modifier changed the url to `nil` or empty. + // In this case, throw an error. + guard let url = request.url, !url.absoluteString.isEmpty else { + options.callbackQueue.execute { + completionHandler?(.failure(KingfisherError.requestError(reason: .invalidURL(request: request)))) + } + return nil + } + + // Wraps `completionHandler` to `onCompleted` respectively. + + let onCompleted = completionHandler.map { + block -> Delegate, Void> in + let delegate = Delegate, Void>() + delegate.delegate(on: self) { (_, callback) in + block(callback) + } + return delegate + } + + // SessionDataTask.TaskCallback is a wrapper for `onCompleted` and `options` (for processor info) + let callback = SessionDataTask.TaskCallback( + onCompleted: onCompleted, + options: options + ) + + // Ready to start download. Add it to session task manager (`sessionHandler`) + + let downloadTask: DownloadTask + if let existingTask = sessionDelegate.task(for: url) { + downloadTask = sessionDelegate.append(existingTask, url: url, callback: callback) + } else { + let sessionDataTask = session.dataTask(with: request) + sessionDataTask.priority = options.downloadPriority + downloadTask = sessionDelegate.add(sessionDataTask, url: url, callback: callback) + } + + let sessionTask = downloadTask.sessionTask + + // Start the session task if not started yet. + if !sessionTask.started { + 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. + do { + let value = try result.get() + self.delegate?.imageDownloader( + self, + didFinishDownloadingImageForURL: url, + with: value.1, + error: nil + ) + } catch { + self.delegate?.imageDownloader( + self, + didFinishDownloadingImageForURL: url, + with: nil, + error: error + ) + } + + switch result { + // Download finished. Now process the data to an image. + case .success(let (data, response)): + let processor = ImageDataProcessor( + data: data, callbacks: callbacks, processingQueue: options.processingQueue) + processor.onImageProcessed.delegate(on: self) { (self, result) 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) = result + + if let image = try? result.get() { + self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response) + } + + let imageResult = result.map { ImageLoadingResult(image: $0, url: 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)) } + } + } + } + delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) + sessionTask.resume() + } + 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) + } +} + +// 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 `AuthenticationChallengeResponsable`. +extension ImageDownloader: AuthenticationChallengeResponsable {} + +// Use the default implementation from extension of `ImageDownloaderDelegate`. +extension ImageDownloader: ImageDownloaderDelegate {} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift new file mode 100644 index 0000000..2cc9102 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift @@ -0,0 +1,127 @@ +// +// 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 + +/// 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. + /// - 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. + 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 +} + +// 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, for url: URL) -> Data? { + return data + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageModifier.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageModifier.swift new file mode 100644 index 0000000..5ef0722 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImageModifier.swift @@ -0,0 +1,116 @@ +// +// 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. + +import Foundation + +/// An `ImageModifier` can be used to change properties on an image in between +/// cache serialization and use of the image. The modified returned image will be +/// only used for current rendering purpose, the serialization data will not contain +/// the changes applied by the `ImageModifier`. +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) +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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift new file mode 100644 index 0000000..c2d5ff1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift @@ -0,0 +1,372 @@ +// +// 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 pretchQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.pretchQueue") + 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 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 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 + } + + 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(pretchQueue) + 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() { + pretchQueue.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() { + pretchQueue.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. + pretchQueue.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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift new file mode 100644 index 0000000..aaf0f7f --- /dev/null +++ b/sopt_29th_Assignment/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, (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, (URLRequest?) -> Void) -> Void) { + block = handle + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/RequestModifier.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/RequestModifier.swift new file mode 100644 index 0000000..06b062a --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/RequestModifier.swift @@ -0,0 +1,69 @@ +// +// 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. +public protocol ImageDownloadRequestModifier { + + /// A 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? +} + +/// 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift new file mode 100644 index 0000000..1ab5a2e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift new file mode 100644 index 0000000..6330918 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift @@ -0,0 +1,121 @@ +// +// 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 + 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 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift new file mode 100644 index 0000000..6b40c75 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift @@ -0,0 +1,262 @@ +// +// 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 +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 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, + url: URL, + 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 + } + 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 { + + 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 + } + completionHandler(.allow) + } + + 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) + } + } + } + + 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), let finalData = data { + result = .success((finalData, task.response)) + } else { + result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask))) + } + } + onCompleted(task: task, result: result) + } + + func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + onReceiveSessionChallenge.call((session, challenge, completionHandler)) + } + + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler)) + } + + 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 + } + remove(sessionTask) + sessionTask.onTaskDone.call((result, sessionTask.callbacks)) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Box.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Box.swift new file mode 100644 index 0000000..0303a6e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift new file mode 100644 index 0000000..fa67f14 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift @@ -0,0 +1,81 @@ +// +// 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 + +/// 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 ()->()) { + if self === DispatchQueue.main && Thread.isMainThread { + block() + } else { + async { block() } + } + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Delegate.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Delegate.swift new file mode 100644 index 0000000..15915c9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Delegate.swift @@ -0,0 +1,53 @@ +// +// 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 delegate helper type to "shadow" weak `self`, to prevent creating an unexpected retain cycle. +class Delegate { + init() {} + + private var block: ((Input) -> Output?)? + + func delegate(on target: T, block: ((T, Input) -> Output)?) { + // The `target` is weak inside block, so you do not need to worry about it in the caller side. + self.block = { [weak target] input in + guard let target = target else { return nil } + return block?(target, input) + } + } + + func call(_ input: Input) -> Output? { + return block?(input) + } +} + +extension Delegate where Input == Void { + // To make syntax better for `Void` input. + func call() -> Output? { + return call(()) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift new file mode 100644 index 0000000..f1e1e8b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift @@ -0,0 +1,125 @@ +// +// 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()) + } + + var isFuture: Bool { + return !isPast + } + + func isPast(referenceDate: Date) -> Bool { + return timeIntervalSince(referenceDate) <= 0 + } + + func isFuture(referenceDate: Date) -> Bool { + return !isPast(referenceDate: referenceDate) + } + + // `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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Result.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Result.swift new file mode 100644 index 0000000..8b9c5fd --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Result.swift @@ -0,0 +1,239 @@ +// +// 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 + +#if swift(>=4.3) +/// Result type already built-in +#else +/// A value that represents either a success or failure, capturing associated +/// values in both cases. +public enum Result { + /// A success, storing a `Value`. + case success(Success) + + /// A failure, storing an `Error`. + case failure(Failure) + + /// Evaluates the given transform closure when this `Result` instance is + /// `.success`, passing the value as a parameter. + /// + /// Use the `map` method with a closure that returns a non-`Result` value. + /// + /// - Parameter transform: A closure that takes the successful value of the + /// instance. + /// - Returns: A new `Result` instance with the result of the transform, if + /// it was applied. + public func map( + _ transform: (Success) -> NewSuccess + ) -> Result { + switch self { + case let .success(success): + return .success(transform(success)) + case let .failure(failure): + return .failure(failure) + } + } + + /// Evaluates the given transform closure when this `Result` instance is + /// `.failure`, passing the error as a parameter. + /// + /// Use the `mapError` method with a closure that returns a non-`Result` + /// value. + /// + /// - Parameter transform: A closure that takes the failure value of the + /// instance. + /// - Returns: A new `Result` instance with the result of the transform, if + /// it was applied. + public func mapError( + _ transform: (Failure) -> NewFailure + ) -> Result { + switch self { + case let .success(success): + return .success(success) + case let .failure(failure): + return .failure(transform(failure)) + } + } + + /// Evaluates the given transform closure when this `Result` instance is + /// `.success`, passing the value as a parameter and flattening the result. + /// + /// - Parameter transform: A closure that takes the successful value of the + /// instance. + /// - Returns: A new `Result` instance, either from the transform or from + /// the previous error value. + public func flatMap( + _ transform: (Success) -> Result + ) -> Result { + switch self { + case let .success(success): + return transform(success) + case let .failure(failure): + return .failure(failure) + } + } + + /// Evaluates the given transform closure when this `Result` instance is + /// `.failure`, passing the error as a parameter and flattening the result. + /// + /// - Parameter transform: A closure that takes the error value of the + /// instance. + /// - Returns: A new `Result` instance, either from the transform or from + /// the previous success value. + public func flatMapError( + _ transform: (Failure) -> Result + ) -> Result { + switch self { + case let .success(success): + return .success(success) + case let .failure(failure): + return transform(failure) + } + } +} + +extension Result where Failure: Error { + /// Returns the success value as a throwing expression. + /// + /// Use this method to retrieve the value of this result if it represents a + /// success, or to catch the value if it represents a failure. + /// + /// let integerResult: Result = .success(5) + /// do { + /// let value = try integerResult.get() + /// print("The value is \(value).") + /// } catch error { + /// print("Error retrieving the value: \(error)") + /// } + /// // Prints "The value is 5." + /// + /// - Returns: The success value, if the instance represents a success. + /// - Throws: The failure value, if the instance represents a failure. + public func get() throws -> Success { + switch self { + case let .success(success): + return success + case let .failure(failure): + throw failure + } + } + + /// Unwraps the `Result` into a throwing expression. + /// + /// - Returns: The success value, if the instance is a success. + /// - Throws: The error value, if the instance is a failure. + @available(*, deprecated, message: "This method will be removed soon. Use `get() throws -> Success` instead.") + public func unwrapped() throws -> Success { + switch self { + case let .success(value): + return value + case let .failure(error): + throw error + } + } +} + +extension Result where Failure == Swift.Error { + /// Creates a new result by evaluating a throwing closure, capturing the + /// returned value as a success, or any thrown error as a failure. + /// + /// - Parameter body: A throwing closure to evaluate. + @_transparent + public init(catching body: () throws -> Success) { + do { + self = .success(try body()) + } catch { + self = .failure(error) + } + } +} + +extension Result : Equatable where Success : Equatable, Failure: Equatable { } + +extension Result : Hashable where Success : Hashable, Failure : Hashable { } + +extension Result : CustomDebugStringConvertible { + public var debugDescription: String { + var output = "Result." + switch self { + case let .success(value): + output += "success(" + debugPrint(value, terminator: "", to: &output) + case let .failure(error): + output += "failure(" + debugPrint(error, terminator: "", to: &output) + } + output += ")" + + return output + } +} +#endif + +// 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) + } + } + + func matchSuccess(with folder: (Success?) -> Output) -> Output { + return match( + onSuccess: { value in return folder(value) }, + onFailure: { _ in return folder(nil) } + ) + } + + func matchFailure(with folder: (Error?) -> Output) -> Output { + return match( + onSuccess: { _ in return folder(nil) }, + onFailure: { error in return folder(error) } + ) + } + + func match(with folder: (Success?, Error?) -> Output) -> Output { + return match( + onSuccess: { return folder($0, nil) }, + onFailure: { return folder(nil, $0) } + ) + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Runtime.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Runtime.swift new file mode 100644 index 0000000..d5818e2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/Runtime.swift @@ -0,0 +1,35 @@ +// +// 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? { + return objc_getAssociatedObject(object, key) as? T +} + +func setRetainedAssociatedObject(_ object: Any, _ key: UnsafeRawPointer, _ value: T) { + objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift new file mode 100644 index 0000000..19d05d6 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/String+MD5.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/String+MD5.swift new file mode 100644 index 0000000..07eaaf2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Utility/String+MD5.swift @@ -0,0 +1,291 @@ +// +// 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 + } + + #if swift(>=5.0) + let message = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in + return [UInt8](bytes) + } + #else + let message = data.withUnsafeBytes { bytes in + return [UInt8](UnsafeBufferPointer(start: bytes, count: data.count)) + } + #endif + + let MD5Calculator = MD5(message) + let MD5Data = MD5Calculator.calculate() + + var MD5String = String() + for c in MD5Data { + MD5String += String(format: "%02x", c) + } + return MD5String + } +} + +// 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 + } + + #if swift(>=4.1) + valuePointer.deinitialize(count: 1) + valuePointer.deallocate() + #else + valuePointer.deinitialize() + valuePointer.deallocate(capacity: 1) + #endif + + return bytes +} + +extension Int { + // Array of bytes with optional padding (little-endian) + func bytes(_ totalBytes: Int = MemoryLayout.size) -> [UInt8] { + return arrayOfBytes(self, length: totalBytes) + } + +} + +extension NSMutableData { + + // Convenient way to append bytes + func appendBytes(_ arrayOfBytes: [UInt8]) { + append(arrayOfBytes, length: arrayOfBytes.count) + } + +} + +protocol HashProtocol { + var message: [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 { + + static let size = 16 // 128 / 8 + let message: [UInt8] + + init (_ message: [UInt8]) { + self.message = message + } + + // specifies the per-round shift amounts + private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] + + // binary integer part of the sines of integers (Radians) + private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] + + private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] + + func calculate() -> [UInt8] { + var tmpMessage = prepare(64) + tmpMessage.reserveCapacity(tmpMessage.count + 4) + + // hash values + var hh = hashes + + // Step 2. Append Length a 64-bit representation of lengthInBits + let lengthInBits = (message.count * 8) + let lengthBytes = lengthInBits.bytes(64 / 8) + tmpMessage += lengthBytes.reversed() + + // Process the message in successive 512-bit chunks: + let chunkSizeBytes = 512 / 8 // 64 + + for chunk in 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 + break + case 16...31: + F = (D & B) | (~D & C) + g = (5 * j + 1) % 16 + break + case 32...47: + F = B ^ C ^ D + g = (3 * j + 5) % 16 + break + case 48...63: + F = C ^ (B | (~D)) + g = (7 * j) % 16 + break + default: + break + } + dTemp = D + D = C + C = B + B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) + A = dTemp + } + + hh[0] = hh[0] &+ A + hh[1] = hh[1] &+ B + hh[2] = hh[2] &+ C + hh[3] = hh[3] &+ D + } + var result = [UInt8]() + result.reserveCapacity(hh.count / 4) + + hh.forEach { + let itemLE = $0.littleEndian + let r1 = UInt8(itemLE & 0xff) + let r2 = UInt8((itemLE >> 8) & 0xff) + let r3 = UInt8((itemLE >> 16) & 0xff) + let r4 = UInt8((itemLE >> 24) & 0xff) + result += [r1, r2, r3, r4] + } + return result + } +} diff --git a/sopt_29th_Assignment/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift new file mode 100644 index 0000000..3843eeb --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift @@ -0,0 +1,614 @@ +// +// 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) {} +} + +#if swift(>=4.2) +let KFRunLoopModeCommon = RunLoop.Mode.common +#else +let KFRunLoopModeCommon = RunLoopMode.commonModes +#endif + +/// 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? + + // MARK: - Private property + /// `Animator` instance that holds the frames of a specific image in memory. + private var animator: Animator? + + // 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() + } + } + + 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) { + if let currentFrame = animator?.currentFrameImage { + layer.contents = currentFrame.cgImage + } else { + layer.contents = image?.cgImage + } + } + + override open func didMoveToWindow() { + super.didMoveToWindow() + didMove() + } + + override open func didMoveToSuperview() { + super.didMoveToSuperview() + didMove() + } + + // This is for back compatibility that using regular `UIImageView` to show animated image. + override func shouldPreloadAllAnimation() -> Bool { + return false + } + + // Reset the animator. + private func reset() { + animator = nil + if let imageSource = image?.kf.imageSource { + let targetSize = bounds.scaled(UIScreen.main.scale).size + let animator = Animator( + imageSource: imageSource, + contentMode: contentMode, + size: targetSize, + 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 + class Animator { + private let size: CGSize + private let maxFrameCount: Int + private let imageSource: CGImageSource + 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 + + // Current active frame image + var currentFrameImage: UIImage? { + return frame(at: currentFrameIndex) + } + + // Current active frame duration + var currentFrameDuration: TimeInterval { + return duration(at: currentFrameIndex) + } + + // The index of the current GIF frame. + 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 + } + } + + 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`. + /// - count: Count of frames needed to be preloaded. + /// - repeatCount: The repeat count should this animator uses. + init(imageSource source: CGImageSource, + contentMode mode: UIView.ContentMode, + size: CGSize, + framePreloadCount count: Int, + repeatCount: RepeatCount, + preloadQueue: DispatchQueue) { + self.imageSource = source + self.contentMode = mode + self.size = size + self.maxFrameCount = count + self.maxRepeatCount = repeatCount + self.preloadQueue = preloadQueue + } + + func frame(at index: Int) -> KFCrossPlatformImage? { + return animatedFrames[index]?.image + } + + func duration(at index: Int) -> TimeInterval { + return animatedFrames[index]?.duration ?? .infinity + } + + func prepareFramesAsynchronously() { + frameCount = Int(CGImageSourceGetCount(imageSource)) + 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 options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageIfAbsent: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height) + ] + + let resize = needsPrescaling && size != .zero + guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, + index, + resize ? options as CFDictionary : nil) else { + return nil + } + + let image = KFCrossPlatformImage(cgImage: cgImage) + return backgroundDecode ? image.kf.decoded : image + } + + private func updatePreloadedFrames() { + guard preloadingIsNeeded else { + return + } + + animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame + + 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() { + currentFrameIndex = increment(frameIndex: currentFrameIndex) + if isLastFrame { + currentRepeatCount += 1 + if isReachMaxRepeatCount { + isFinished = true + } + 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/sopt_29th_Assignment/Pods/Kingfisher/Sources/Views/Indicator.swift b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Views/Indicator.swift new file mode 100644 index 0000000..9ec9547 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Kingfisher/Sources/Views/Indicator.swift @@ -0,0 +1,236 @@ +// +// 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 + } + #else + if #available(iOS 13.0, * ) { + indicatorStyle = UIActivityIndicatorView.Style.medium + } else { + indicatorStyle = UIActivityIndicatorView.Style.gray + } + #endif + + #if swift(>=4.2) + activityIndicatorView = UIActivityIndicatorView(style: indicatorStyle) + #else + activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle) + #endif + #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/sopt_29th_Assignment/Pods/ListPlaceholder/LICENSE b/sopt_29th_Assignment/Pods/ListPlaceholder/LICENSE new file mode 100644 index 0000000..c1bcaa4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/ListPlaceholder/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 Moayad Al kouz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/sopt_29th_Assignment/Pods/ListPlaceholder/ListPlaceholder/Classes/ListLoader.swift b/sopt_29th_Assignment/Pods/ListPlaceholder/ListPlaceholder/Classes/ListLoader.swift new file mode 100644 index 0000000..cfc60bb --- /dev/null +++ b/sopt_29th_Assignment/Pods/ListPlaceholder/ListPlaceholder/Classes/ListLoader.swift @@ -0,0 +1,280 @@ +// +// Copyright (c) 2017 malkouz +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + + +import UIKit + +@objc public protocol ListLoadable +{ + func ld_visibleContentViews()->[UIView] +} + +@objc extension UITableView : ListLoadable +{ + public func ld_visibleContentViews()->[UIView] + { + return (self.visibleCells as NSArray).value(forKey: "contentView") as! [UIView] + } +} + +@objc extension UIView +{ + public func showLoader(){ + self.isUserInteractionEnabled = false + if self is UITableView{ + ListLoader.addLoaderTo(self as! UITableView) + }else if self is UICollectionView{ + ListLoader.addLoaderTo(self as! UICollectionView) + }else{ + ListLoader.addLoaderToViews([self]) + } + } + + public func hideLoader(){ + self.isUserInteractionEnabled = true + if self is UITableView{ + ListLoader.removeLoaderFrom(self as! UITableView) + }else if self is UICollectionView{ + ListLoader.removeLoaderFrom(self as! UICollectionView) + }else{ + ListLoader.removeLoaderFromViews([self]) + } + } +} + +@objc extension UICollectionView : ListLoadable +{ + public func ld_visibleContentViews()->[UIView] + { + return (self.visibleCells as NSArray).value(forKey: "contentView") as! [UIView] + } +} + + + +@objc extension UIColor { + static func backgroundFadedGrey()->UIColor + { + return UIColor(red: (246.0/255.0), green: (247.0/255.0), blue: (248.0/255.0), alpha: 1) + } + + static func gradientFirstStop()->UIColor + { + return UIColor(red: (238.0/255.0), green: (238.0/255.0), blue: (238.0/255.0), alpha: 1.0) + } + + static func gradientSecondStop()->UIColor + { + return UIColor(red: (221.0/255.0), green: (221.0/255.0), blue:(221.0/255.0) , alpha: 1.0); + } +} + +@objc extension UIView{ + func boundInside(_ superView: UIView){ + + self.translatesAutoresizingMaskIntoConstraints = false + superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics:nil, views:["subview":self])) + superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics:nil, views:["subview":self])) + } +} + +extension CGFloat +{ + func doubleValue()->Double + { + return Double(self) + } +} + + + +@objc open class ListLoader: NSObject +{ + static func addLoaderToViews(_ views : [UIView]) + { + CATransaction.begin() + views.forEach { $0.ld_addLoader() } + CATransaction.commit() + } + + static func removeLoaderFromViews(_ views: [UIView]) + { + CATransaction.begin() + views.forEach { $0.ld_removeLoader() } + CATransaction.commit() + } + + public static func addLoaderTo(_ list : ListLoadable ) + { + self.addLoaderToViews(list.ld_visibleContentViews()) + } + + + public static func removeLoaderFrom(_ list : ListLoadable ) + { + self.removeLoaderFromViews(list.ld_visibleContentViews()) + } +} + +@objc class CutoutView : UIView +{ + override func draw(_ rect: CGRect) { + super.draw(rect) + let context = UIGraphicsGetCurrentContext() + context?.setFillColor(UIColor.white.cgColor) + context?.fill(self.bounds) + + for view in (self.superview?.subviews)! { + if view != self { + if #available(iOS 9.0, *), let stackView = view as? UIStackView { + recursivelyDrawCutOutInStackView(stackView, fromParentView: view.superview!, context: context) + } else { + drawPath(context: context, view: view) + } + } + } + } + + @available(iOS 9.0, *) + private func recursivelyDrawCutOutInStackView(_ stackView: UIStackView, fromParentView parentView: UIView, context: CGContext?) { + stackView.arrangedSubviews.forEach { arrangedSubview in + if let arrangedSubviewStackView = arrangedSubview as? UIStackView { + recursivelyDrawCutOutInStackView(arrangedSubviewStackView, fromParentView: parentView, context: context) + return + } + let frame = stackView.convert(arrangedSubview.frame, to: parentView) + drawPath(context: context, view: arrangedSubview, fixedFrame: frame) + } + } + + private func drawPath(context: CGContext?, view: UIView, fixedFrame: CGRect? = nil) { + let frame = fixedFrame ?? view.frame + context?.setBlendMode(.clear); + let rect = frame + let clipPath: CGPath = UIBezierPath(roundedRect: rect, cornerRadius: view.layer.cornerRadius).cgPath + context?.addPath(clipPath) + context?.setFillColor(UIColor.clear.cgColor) + context?.closePath() + context?.fillPath() + } + + override func layoutSubviews() { + self.setNeedsDisplay() + self.superview?.ld_getGradient()?.frame = (self.superview?.bounds)! + } +} + +// TODO :- Allow caller to tweak these + +var cutoutHandle: UInt8 = 0 +var gradientHandle: UInt8 = 0 +var loaderDuration = 0.85 +var gradientWidth = 0.17 +var gradientFirstStop = 0.1 + + + +@objc extension UIView +{ + fileprivate func ld_getCutoutView()->UIView? + { + return objc_getAssociatedObject(self, &cutoutHandle) as! UIView? + } + + fileprivate func ld_setCutoutView(_ aView : UIView) + { + return objc_setAssociatedObject(self, &cutoutHandle, aView, .OBJC_ASSOCIATION_RETAIN) + } + + fileprivate func ld_getGradient()->CAGradientLayer? + { + return objc_getAssociatedObject(self, &gradientHandle) as! CAGradientLayer? + } + + fileprivate func ld_setGradient(_ aLayer : CAGradientLayer) + { + return objc_setAssociatedObject(self, &gradientHandle, aLayer, .OBJC_ASSOCIATION_RETAIN) + } + + fileprivate func ld_addLoader() + { + let gradient: CAGradientLayer = CAGradientLayer() + gradient.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width , height: self.bounds.size.height) + self.layer.insertSublayer(gradient, at:0) + + self.configureAndAddAnimationToGradient(gradient) + self.addCutoutView() + } + + fileprivate func ld_removeLoader() + { + self.ld_getCutoutView()?.removeFromSuperview() + self.ld_getGradient()?.removeAllAnimations() + self.ld_getGradient()?.removeFromSuperlayer() + + for view in self.subviews { + view.alpha = 1 + } + } + + + func configureAndAddAnimationToGradient(_ gradient : CAGradientLayer) + { + gradient.startPoint = CGPoint(x: -1.0 + CGFloat(gradientWidth), y: 0) + gradient.endPoint = CGPoint(x: 1.0 + CGFloat(gradientWidth), y: 0) + + gradient.colors = [ + UIColor.backgroundFadedGrey().cgColor, + UIColor.gradientFirstStop().cgColor, + UIColor.gradientSecondStop().cgColor, + UIColor.gradientFirstStop().cgColor, + UIColor.backgroundFadedGrey().cgColor + ] + + let startLocations = [NSNumber(value: gradient.startPoint.x.doubleValue() as Double),NSNumber(value: gradient.startPoint.x.doubleValue() as Double),NSNumber(value: 0 as Double),NSNumber(value: gradientWidth as Double),NSNumber(value: 1 + gradientWidth as Double)] + + + gradient.locations = startLocations + let gradientAnimation = CABasicAnimation(keyPath: "locations") + gradientAnimation.fromValue = startLocations + gradientAnimation.toValue = [NSNumber(value: 0 as Double),NSNumber(value: 1 as Double),NSNumber(value: 1 as Double),NSNumber(value: 1 + (gradientWidth - gradientFirstStop) as Double),NSNumber(value: 1 + gradientWidth as Double)] + + gradientAnimation.repeatCount = Float.infinity + gradientAnimation.fillMode = .forwards + gradientAnimation.isRemovedOnCompletion = false + gradientAnimation.duration = loaderDuration + gradient.add(gradientAnimation ,forKey:"locations") + + + self.ld_setGradient(gradient) + + } + + fileprivate func addCutoutView() + { + let cutout = CutoutView() + cutout.frame = self.bounds + cutout.backgroundColor = UIColor.clear + + self.addSubview(cutout) + cutout.setNeedsDisplay() + cutout.boundInside(self) + + for view in self.subviews { + if view != cutout { + view.alpha = 0 + } + } + + + self.ld_setCutoutView(cutout) + } +} + diff --git a/sopt_29th_Assignment/Pods/ListPlaceholder/README.md b/sopt_29th_Assignment/Pods/ListPlaceholder/README.md new file mode 100644 index 0000000..c6b86b1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/ListPlaceholder/README.md @@ -0,0 +1,103 @@ +# ListPlaceholder + +[![Version](https://img.shields.io/cocoapods/v/ListPlaceholder.svg?style=flat)](http://cocoapods.org/pods/ListPlaceholder) +[![License](https://img.shields.io/cocoapods/l/ListPlaceholder.svg?style=flat)](http://cocoapods.org/pods/ListPlaceholder) +[![Platform](https://img.shields.io/cocoapods/p/ListPlaceholder.svg?style=flat)](http://cocoapods.org/pods/ListPlaceholder) + +

ListPlaceholder

+

Facebook news feed style animation

+ +

+ +

+ + +## Features +ListPlaceholder is a swift library allows you to easily add facebook style animated loading placeholder to your tableviews, collection views or custom views. + +## Installation + +### CocoaPods (Recommended) + +1. Install [CocoaPods](https://cocoapods.org) +2. Add this repo to your `Podfile` + +```ruby +target 'Example' do +# IMPORTANT: Make sure use_frameworks! is included at the top of the file +use_frameworks! +platform :ios, '8.0' +pod 'ListPlaceholder' +end +``` +3. Run `pod install` +4. Open up the `.xcworkspace` that CocoaPods created +5. Done! + +### Manually + +Simply download the `ListLoader.swift` file from [here](https://github.com/malkouz/ListPlaceholder/blob/master/ListPlaceholder/Classes/ListLoader.swift) into your project, make sure you point to your projects target + +### Usage + +```swift +import ListPlaceholder +``` +UITableView usage +```swift +//to show the loader +tableView.reloadData() +tableView.showLoader() + +//to hide the loader +tableView.hideLoader() +``` + +UICollectionView usage +```swift +//to show the loader +collectionView.reloadData() +collectionView.layoutIfNeeded() +collectionView.showLoader() + +//to hide the loader +collectionView.hideLoader() +``` + +UIView usage +```swift +//to show the loader + +customView.showLoader() + +//to hide the loader +customView.hideLoader() +``` + +Also the placeholder is now supporting in Objective-C language +```Objective-C + +@import ListPlaceholder; + +//to show the loader +[_customView showLoader]; +//to hide the loader +[_customView hideLoader]; +``` + + +## Example project + +Take a look at the example project over here + +1. Download it +2. Open the `Example.xcworkspace` in Xcode +3. Enjoy! + +## Author + +Moayad Al kouz, moayad_kouz9@hotmail.com + +## License + +ListPlaceholder is available under the MIT license. See the LICENSE file for more info. diff --git a/sopt_29th_Assignment/Pods/Manifest.lock b/sopt_29th_Assignment/Pods/Manifest.lock new file mode 100644 index 0000000..3a0bb64 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Manifest.lock @@ -0,0 +1,67 @@ +PODS: + - Alamofire (5.4.4) + - Kingfisher (5.15.8): + - Kingfisher/Core (= 5.15.8) + - Kingfisher/Core (5.15.8) + - ListPlaceholder (1.5) + - lottie-ios (3.2.3) + - Moya (14.0.0): + - Moya/Core (= 14.0.0) + - Moya/Core (14.0.0): + - Alamofire (~> 5.0) + - RxCocoa (6.2.0): + - RxRelay (= 6.2.0) + - RxSwift (= 6.2.0) + - RxRelay (6.2.0): + - RxSwift (= 6.2.0) + - RxSwift (6.2.0) + - SkeletonView (1.25.1) + - SnapKit (5.0.1) + - SwiftyJSON (4.3.0) + - Then (2.7.0) + +DEPENDENCIES: + - Alamofire (~> 5.1) + - Kingfisher (~> 5.0) + - ListPlaceholder + - lottie-ios + - Moya (~> 14.0) + - RxCocoa (= 6.2.0) + - RxSwift (= 6.2.0) + - SkeletonView + - SnapKit (~> 5.0.0) + - SwiftyJSON (~> 4.0) + - Then + +SPEC REPOS: + trunk: + - Alamofire + - Kingfisher + - ListPlaceholder + - lottie-ios + - Moya + - RxCocoa + - RxRelay + - RxSwift + - SkeletonView + - SnapKit + - SwiftyJSON + - Then + +SPEC CHECKSUMS: + Alamofire: f3b09a368f1582ab751b3fff5460276e0d2cf5c9 + Kingfisher: a3c03d702433fa6cfedabb2bddbe076fb8f2e902 + ListPlaceholder: 2d7950014852ee5613d636cf14fd1bb93419e330 + lottie-ios: c058aeafa76daa4cf64d773554bccc8385d0150e + Moya: 5b45dacb75adb009f97fde91c204c1e565d31916 + RxCocoa: 4baf94bb35f2c0ab31bc0cb9f1900155f646ba42 + RxRelay: e72dbfd157807478401ef1982e1c61c945c94b2f + RxSwift: d356ab7bee873611322f134c5f9ef379fa183d8f + SkeletonView: 77079530e1348a72f48b79ae30dcb966c1b18b6a + SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb + SwiftyJSON: 6faa0040f8b59dead0ee07436cbf76b73c08fd08 + Then: acfe0be7e98221c6204e12f8161459606d5d822d + +PODFILE CHECKSUM: ac49fa414015d8736c33eef0212216c73de9a897 + +COCOAPODS: 1.11.2 diff --git a/sopt_29th_Assignment/Pods/Moya/License.md b/sopt_29th_Assignment/Pods/Moya/License.md new file mode 100644 index 0000000..58ef14f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Readme.md b/sopt_29th_Assignment/Pods/Moya/Readme.md new file mode 100644 index 0000000..863e96a --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Readme.md @@ -0,0 +1,328 @@ +

+ +

+ +# Moya 14.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 + +To integrate using Apple's Swift package manager, add the following as a dependency to your `Package.swift`: + +```swift +.package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "14.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"` or `"RxMoya"` as your Target dependency respectively. +Here's an example `PackageDescription`: + +```swift +// swift-tools-version:5.0 +import PackageDescription + +let package = Package( + name: "MyPackage", + products: [ + .library( + name: "MyPackage", + targets: ["MyPackage"]), + ], + dependencies: [ + .package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "14.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. + +### 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', '~> 14.0' + +# or + +pod 'Moya/RxSwift', '~> 14.0' + +# or + +pod 'Moya/ReactiveSwift', '~> 14.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`, or `ReactiveMoya`. + +Make the following entry in your Cartfile: + +``` +github "Moya/Moya" ~> 14.0 +``` + +Then run `carthage update`. + +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`, then `RxMoya`, `RxTest`, `RxCocoa`, 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, Result & 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/antitypical/Result.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 `Result.xcodeproj` in the `Result` folder and `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 build target you need for `Result`. +- Click on the `+` button 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) and +[RxSwift](https://github.com/ReactiveX/RxSwift). + +### 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. + +## 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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/AnyEncodable.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/AnyEncodable.swift new file mode 100644 index 0000000..15c7128 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Cancellable.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Cancellable.swift new file mode 100644 index 0000000..9a9c783 --- /dev/null +++ b/sopt_29th_Assignment/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 { return innerCancellable.isCancelled } + + internal func cancel() { + innerCancellable.cancel() + } +} + +internal class SimpleCancellable: Cancellable { + var isCancelled = false + func cancel() { + isCancelled = true + } +} diff --git a/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Endpoint.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Endpoint.swift new file mode 100755 index 0000000..dae0504 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Endpoint.swift @@ -0,0 +1,140 @@ +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 { + return 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 { + return 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) { + guard let request = try? urlRequest() else { + hasher.combine(url) + return + } + hasher.combine(request) + } + + /// 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 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 } + return (lhsRequest == rhsRequest) + } +} diff --git a/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Image.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Image.swift new file mode 100644 index 0000000..b57b472 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Moya+Alamofire.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Moya+Alamofire.swift new file mode 100644 index 0000000..93f0bd9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Moya+Alamofire.swift @@ -0,0 +1,137 @@ +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] { + return 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 { + private let lock: NSRecursiveLock = NSRecursiveLock() + + var prepare: ((URLRequest) -> URLRequest)? + private var internalWillSend: ((URLRequest) -> Void)? + + var willSend: ((URLRequest) -> Void)? { + get { + lock.lock(); defer { lock.unlock() } + return internalWillSend + } + + set { + lock.lock(); defer { lock.unlock() } + internalWillSend = newValue + } + } + + 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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaError.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaError.swift new file mode 100644 index 0000000..4b16bd2 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider+Defaults.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider+Defaults.swift new file mode 100644 index 0000000..0f97f69 --- /dev/null +++ b/sopt_29th_Assignment/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 { + return 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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider+Internal.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider+Internal.swift new file mode 100644 index 0000000..212c9a0 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider+Internal.swift @@ -0,0 +1,287 @@ +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 { + lock.lock() + var inflightCompletionBlocks = self.inflightRequests[endpoint] + inflightCompletionBlocks?.append(pluginsWithCompletion) + self.inflightRequests[endpoint] = inflightCompletionBlocks + lock.unlock() + + if inflightCompletionBlocks != nil { + return cancellableToken + } else { + lock.lock() + self.inflightRequests[endpoint] = [pluginsWithCompletion] + lock.unlock() + } + } + + 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.lock.lock() + self.inflightRequests.removeValue(forKey: endpoint) + self.lock.unlock() + } 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 request = session.upload(multipartFormData: formData, with: request, interceptor: interceptor) + setup(interceptor: interceptor, with: target, and: request) + + let validationCodes = target.validationType.statusCodes + let validatedRequest = validationCodes.isEmpty ? request : request.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 = session.upload(file, with: request, interceptor: interceptor) + setup(interceptor: interceptor, with: target, and: 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 = session.download(request, interceptor: interceptor, to: destination) + setup(interceptor: interceptor, with: target, and: 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 = session.request(request, interceptor: interceptor) + setup(interceptor: interceptor, with: target, and: 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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider.swift new file mode 100755 index 0000000..0c6381f --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MoyaProvider.swift @@ -0,0 +1,215 @@ +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 { + return 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 internal(set) var inflightRequests: [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 { + return 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 { + return .never + } + + /// Return a response immediately. + final class func immediatelyStub(_: Target) -> Moya.StubBehavior { + return .immediate + } + + /// Return a response after a delay. + final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { + return { _ in return .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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MultiTarget.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MultiTarget.swift new file mode 100644 index 0000000..19cb701 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MultiTarget.swift @@ -0,0 +1,61 @@ +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 { + return target.path + } + + /// The baseURL of the embedded target. + public var baseURL: URL { + return target.baseURL + } + + /// The HTTP method of the embedded target. + public var method: Moya.Method { + return target.method + } + + /// The sampleData of the embedded target. + public var sampleData: Data { + return target.sampleData + } + + /// The `Task` of the embedded target. + public var task: Task { + return target.task + } + + /// The `ValidationType` of the embedded target. + public var validationType: ValidationType { + return target.validationType + } + + /// The headers of the embedded target. + public var headers: [String: String]? { + return 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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MultipartFormData.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MultipartFormData.swift new file mode 100644 index 0000000..28f86ae --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/MultipartFormData.swift @@ -0,0 +1,65 @@ +import Foundation +import Alamofire + +/// Represents "multipart/form-data" for an upload. +public struct MultipartFormData { + + /// Method to provide the form data. + public enum FormDataProvider { + 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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugin.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugin.swift new file mode 100644 index 0000000..e0705c6 --- /dev/null +++ b/sopt_29th_Assignment/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 { return request } + func willSend(_ request: RequestType, target: TargetType) { } + func didReceive(_ result: Result, target: TargetType) { } + func process(_ result: Result, target: TargetType) -> Result { return 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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/AccessTokenPlugin.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/AccessTokenPlugin.swift new file mode 100644 index 0000000..88fca37 --- /dev/null +++ b/sopt_29th_Assignment/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 = (AuthorizationType) -> 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 authValue = authorizationType.value + " " + tokenClosure(authorizationType) + request.addValue(authValue, forHTTPHeaderField: "Authorization") + + return request + } +} diff --git a/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/CredentialsPlugin.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/CredentialsPlugin.swift new file mode 100644 index 0000000..88e1015 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/NetworkActivityPlugin.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/NetworkActivityPlugin.swift new file mode 100644 index 0000000..988e90f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift new file mode 100644 index 0000000..06099c9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift @@ -0,0 +1,237 @@ +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 instanciate 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 instanciate 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 + }() + } +} diff --git a/sopt_29th_Assignment/Pods/Moya/Sources/Moya/RequestTypeWrapper.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/RequestTypeWrapper.swift new file mode 100644 index 0000000..192310b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/RequestTypeWrapper.swift @@ -0,0 +1,36 @@ +import Foundation + +// Workaround for new asynchronous handling of Alamofire's request creation. +struct RequestTypeWrapper: RequestType { + + var request: URLRequest? { + return _urlRequest + } + + var sessionHeaders: [String: String] { + return _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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Response.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Response.swift new file mode 100644 index 0000000..df338cc --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Response.swift @@ -0,0 +1,192 @@ +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 { + return "Status Code: \(statusCode), Data Length: \(data.count)" + } + + /// A text description of the `Response`. Suitable for debugging. + public var debugDescription: String { + return description + } + + public static func == (lhs: Response, rhs: Response) -> Bool { + return 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 { + return 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 { + return 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 { + return 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.count < 1 && !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.count < 1 && !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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/TargetType.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/TargetType.swift new file mode 100644 index 0000000..d247491 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/TargetType.swift @@ -0,0 +1,34 @@ +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. + 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 { + return .none + } +} diff --git a/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Task.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/Task.swift new file mode 100644 index 0000000..191e259 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/URL+Moya.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/URL+Moya.swift new file mode 100644 index 0000000..0c1303c --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/URLRequest+Encoding.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/URLRequest+Encoding.swift new file mode 100644 index 0000000..232d86d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Moya/Sources/Moya/ValidationType.swift b/sopt_29th_Assignment/Pods/Moya/Sources/Moya/ValidationType.swift new file mode 100644 index 0000000..ffc8d8f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/Pods.xcodeproj/project.pbxproj b/sopt_29th_Assignment/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..a5ef7ef --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,5107 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 55; + objects = { + +/* Begin PBXBuildFile section */ + 000702A76DD1A018D9B45DEB79FB505D /* UITextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D92F82B9D0455965CA33B58CD326D06 /* UITextView+Rx.swift */; }; + 016D4D3888A5AC8A1D3B85B3B84F5630 /* ObservableType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C97506E3F057F8206D153A604935B805 /* ObservableType+Extensions.swift */; }; + 01D943FA6C3498798643565DB390A395 /* GIFAnimatedImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE694AAA0AB777F54457592C110B14EE /* GIFAnimatedImage.swift */; }; + 0216178994AB68CF35038568D738DE92 /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 952BA62F6689CB4B398C16DBE3471008 /* Merge.swift */; }; + 022DFEBF3DD3B5B1627278F189254A25 /* RxCocoa.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9FB3F0C1C99CBB4ABF104F8AC950FE0 /* RxCocoa.swift */; }; + 024E8F7B20ADD67F41221E857D45CB4B /* PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E7ACE526EED15B718B4B164D40F7834 /* PrimitiveSequence.swift */; }; + 02621C4B82398D0657F474E21493A3A2 /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4701D61B9E8B58C7B8DE650388D62501 /* HTTPMethod.swift */; }; + 02DB462B121245593CE653B9B377F970 /* Protected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 246879F9E04EAD3592150755424A7EFC /* Protected.swift */; }; + 03C184B386BC437000BA957FAB24DE26 /* KeyframeInterpolator.swift in Sources */ = {isa = PBXBuildFile; fileRef = F75A90C2F8242F9556979A6FA039CA1D /* KeyframeInterpolator.swift */; }; + 03D894819ECA3CA8F42C578E42D08960 /* DelegateProxyType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59479749C35D07AD73D552FEF1A3F790 /* DelegateProxyType.swift */; }; + 03DD607FF2E024C83F3CA482FC681E52 /* KeypathSearchable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BDB661C93B87F00D167E4709AD2A86C /* KeypathSearchable.swift */; }; + 0422FC5745E406CB752E9497A2F56EA9 /* _RXKVOObserver.h in Headers */ = {isa = PBXBuildFile; fileRef = 301AFE63C3AB09BD6D7E866765FB708D /* _RXKVOObserver.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 043F83AC76D2FB2268B91C06651F1A8C /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4C19766D6627B764323CAA1F56C4BE8 /* AnonymousObserver.swift */; }; + 047028E10E1DFF0233C919FB1148AE03 /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD3D6EEF925607AD0B298BEE42319A52 /* Buffer.swift */; }; + 047BE588B6EEEFD95C74C64CA1C0BD81 /* Animation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B640A6E4F170CB420AEF0F40319B8A78 /* Animation.swift */; }; + 04B2DDDF8C3C5DAE8952E85BD4ECF6CE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 04B641288248D3ACC28E7F707058073B /* ObservableConvertibleType+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FD6FB7BB4200891D8DB64A315EFC273 /* ObservableConvertibleType+Signal.swift */; }; + 05BC0D78A16CBD4355700DE7E7ABC1BD /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4304FC34470876F5AE58F762218D8E27 /* DisposeBase.swift */; }; + 05D207C109285670CC665E49B55AD485 /* PathElement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DF448AB4ED97D9C8A49D8B950451DEF /* PathElement.swift */; }; + 05E90BD45B7BBD7DC82A14074FDB0751 /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D2CE551669C63D2247F730227904BC1 /* CombineLatest.swift */; }; + 0618111154400B212A90E0755CE2346E /* Asset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C12F9EE80F91F13B4B83C977CD01AE8 /* Asset.swift */; }; + 06AE486D6684BB4675A6FAE0EF7BDD10 /* PrimitiveSequence+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28C41248617CC832243457A5AE5A72FD /* PrimitiveSequence+Zip+arity.swift */; }; + 06F4F2CD428BB536AA64F1830DDF41D9 /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11DE39107577F3D7973D85C19DC2DC4F /* Zip.swift */; }; + 074F2C0B76CB8E6B2469BC38CBF3AD72 /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CD09121D5921CA90BF4362D690AF12A /* Amb.swift */; }; + 0757D2C17526F2CAEBD6D7BC0D399EA8 /* PathOutputNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 444F5668DB1CCE1EEE4C56A44681A9A1 /* PathOutputNode.swift */; }; + 078FBD69F399F3B3CBF722F3D10379A4 /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = F82ADDF5EFB61F235D5A96300B18D0D3 /* Range.swift */; }; + 08155F3F6D55A38A07F00F85763290E7 /* UITabBarController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA2D17E3F21BC2BBF052D1EC33D995DF /* UITabBarController+Rx.swift */; }; + 08764DA4C847E1FB033E9EA07DB1EDCA /* Kingfisher.h in Headers */ = {isa = PBXBuildFile; fileRef = 8FC7A302AF558DC2FFCCDA0282CD0E63 /* Kingfisher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 08B5EF23E86D67EECADDE2D39B03C557 /* LayerTextProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8086AFD18868DE3546DA9099D9320BF /* LayerTextProvider.swift */; }; + 08CF585A5947964954E7ACB70910985F /* AnyValueContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22C6807ACC5407C39AE3CFE3BEF30D50 /* AnyValueContainer.swift */; }; + 090D7FB5904E0FC4C50F8536764D6D3B /* SkeletonExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45A00219A0362BFAB2AF1BE55BFACA9F /* SkeletonExtended.swift */; }; + 092AFD0D15EA0C5A23AC8E37E65239FE /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37E494D03710E8D813D8044D134F16C7 /* Timer.swift */; }; + 093181D89BFA8C8FBE5FADCE51AC4E85 /* Runtime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED733DB06AC8A291976B4A6AEED7AE0 /* Runtime.swift */; }; + 09672BF940608C6A8A93C25441AABA14 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 09997FDBE8364411FFB6F495729608D2 /* Driver+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D72B0197B86C4795FDBC92B632740 /* Driver+Subscription.swift */; }; + 09A29DDA49E800244859F5DDC4307C13 /* LayerDebugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B9B5E120B5F7D089128B46F55F1BCAB /* LayerDebugging.swift */; }; + 09E4A424C9A4B6AF425B42861E50E5F0 /* UIBarButtonItem+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE73DD65AC9269C15438EB353DFE71B1 /* UIBarButtonItem+Rx.swift */; }; + 09F2ED0DDE23A30CABF4B9C36C722096 /* UITableView+CollectionSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D13749C1361D3E0309897785A6F01FE /* UITableView+CollectionSkeleton.swift */; }; + 0B2165491D9E7087D8C78C7A8128A9F0 /* UISegmentedControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3582E176B7730B8D517496A78618266 /* UISegmentedControl+Rx.swift */; }; + 0B399DCF32F8FE4F09B03B6E7B65E0D1 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7C55FC5EF514FB4258BC99DB4703D221 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0C80F358772C9985C89D6F323EE7D8DB /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD7AF050C7F66F9596DB3250B26EF760 /* CFNetwork.framework */; }; + 0CA04306449F28C86466A60DB7E7E973 /* VectorsExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 699C754CB7A4A4F2D0BBB08B976D0EFC /* VectorsExtensions.swift */; }; + 0D7B6FF8C492D77C003609B68CFABA1E /* UISearchController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71D272C276387B42DE9C3FF7D1711F7D /* UISearchController+Rx.swift */; }; + 0DB08820C29F9A3AD174E05C1159C78C /* GradientFillRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C052ECF294DA36289A931FCE885FCCE2 /* GradientFillRenderer.swift */; }; + 0DF5F8B4A94FA40A38EF4765E918BA42 /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AEAC5C3F987A9644AD6C9C04B25B1A2 /* AnyObserver.swift */; }; + 0F75B8C82523266A3DF606A5974073AA /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2605E5A47D5C358C87DE3D160E420E4A /* Platform.Linux.swift */; }; + 11C61D1C07842BA31AC919BBE8C945C2 /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D758A0D185CC311BCFAF0FF0CD32C44 /* Sink.swift */; }; + 12EC6D92F5D1612E2293F1B808D0A27E /* ColorValueProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72FA3260F540C02E616019AF7AF70861 /* ColorValueProvider.swift */; }; + 1383568E0420C3831A67240BFDC73BE1 /* GroupedObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9967B03CCF1284AA798AE8C3724EAEA /* GroupedObservable.swift */; }; + 13E62623092B680C6A5C349D48B8A4FD /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E635C61C9A23D4E53936282C66E79876 /* CachedResponseHandler.swift */; }; + 144DA93A55A598F5197F10C729FBDD69 /* UILayoutSupport+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACBF41845B42A62975644A4A871D0276 /* UILayoutSupport+Extensions.swift */; }; + 14B051AB5008329CAD63246CCBD78F5B /* TextLayerModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A07764B25F14323CC34D8697ECD39487 /* TextLayerModel.swift */; }; + 14D2C2DC6532CC4AAD73F205B9211DB8 /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A435B7B2440EB29B92A6E97E5F426E4 /* RecursiveLock.swift */; }; + 15038A10A82131B5D91E94668F3043E0 /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC943D97ED350208583B6BA939BB98D2 /* RetryWhen.swift */; }; + 155D953401DF644E75F2ACE729D00DF2 /* Infallible+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51BCE2958D21169BE85CC73B5D398D2C /* Infallible+Bind.swift */; }; + 15D5D77E68C8B6AF20B7056602F7AEBF /* RxPickerViewAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6A7F9A69B7D9163B17A60B7AA14A78C /* RxPickerViewAdapter.swift */; }; + 15F220C3618C1E3F720475FEAF78661F /* SkeletonLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 220131E8E36EBD40284FAF5AF8CE03D8 /* SkeletonLayer.swift */; }; + 15FBDAE3DDDEBF1E36298091A8896B04 /* lottie-ios-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 50535740A752839EFCC7E5D87EEDC917 /* lottie-ios-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 161856AC63FAA2C3D8164A7500E14CB8 /* UITableView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CA7DDF91B9AB1CDDBF143E802DACD59 /* UITableView+Rx.swift */; }; + 16625D9331228E7A690819C60A2991A3 /* PrecompAsset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43CFF9BDD3A181526EF302B0229AAECC /* PrecompAsset.swift */; }; + 16C8FC256C4CE275407038E626C430B1 /* TextDocument.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B5C178ABA8010A0DEC30E331EB4DF64 /* TextDocument.swift */; }; + 16EB1EAEF9D5FF0D6E4B221ECB397D63 /* RxCollectionViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7486E5C476617A9E62DF0845B3133A84 /* RxCollectionViewDataSourceProxy.swift */; }; + 170ACEF678D7B6AABA4CD5A396E25C70 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 171A21B0155EA10267C1DE165A6E1500 /* NSButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAD21644D07C588A6BB916B9CE6FADD7 /* NSButton+Rx.swift */; }; + 1765A958437BF3E2C1A15B6DB68B975B /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C993FA1C50C448867D6FA9026008D4B0 /* Storage.swift */; }; + 1773084DECF68CADD45567FBEC56036D /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = EBFD7FB4845277FFA9666FDEF11DF965 /* Alamofire-dummy.m */; }; + 17BE0F4E51B0FB968125F1A520607FD8 /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F126DE82378F3C5075DC5D1E4F2C04B /* ConstraintMultiplierTarget.swift */; }; + 17E19EA54D755CE77F1583420314128D /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = B04EFFB7E4883C11B13334C7E9B5D414 /* PublishSubject.swift */; }; + 1844F9B8011F32E1455386DC5E870E80 /* ValidationType.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC4A56E2A6E5F31A3C5F7289B79FD61B /* ValidationType.swift */; }; + 190810DE6417E143E4FCFC4835706638 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D30BF91E8A5992C22B85D971C167223 /* MultipartFormData.swift */; }; + 19249139AD95AE769B08AEF313AB6F69 /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ECE50328AD6B4F70001FD7342D1AC24 /* ScheduledItemType.swift */; }; + 19BFB80D74F610E326B28161F07CE38A /* Mask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E963FDB21BEC3F2CBFF40253B0B1671 /* Mask.swift */; }; + 1A0BFCD16FAD69F17736551A5D27262C /* UIView+AssociatedObjects.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D8FD318337131921162F3040DA3E2DE /* UIView+AssociatedObjects.swift */; }; + 1AD93376D403A851F152D1B804F7BFC0 /* Signal+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCB00308A3486A03F452853D6A4B9076 /* Signal+Subscription.swift */; }; + 1AF3BF0EDE10F429386594F787838C1B /* _RX.h in Headers */ = {isa = PBXBuildFile; fileRef = 16AFD5E477C7973D1144A718B6373568 /* _RX.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1B402AACD54B2064A7BC86857F2769DD /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62A531319033D427E8405BE7B48DFB62 /* InfiniteSequence.swift */; }; + 1C4EC804E8F498F823B68DB526FF3D36 /* Recoverable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5609126CF5995535E9EA2DC866B0E36 /* Recoverable.swift */; }; + 1D17B83410DC98911D539F2BD5254C05 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC4858AAE41174640ADC6C4F4EBB738A /* RequestTaskMap.swift */; }; + 1D75EBE5A8334EA0052EB286BD51AE32 /* AuthenticationChallengeResponsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BEEE5E708E847867300037A0C0D8F16 /* AuthenticationChallengeResponsable.swift */; }; + 1D91FD32BEADDD9796BF802700FEE968 /* NullCompositionLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36AB4A0D570C8199050F230FC5DD3C34 /* NullCompositionLayer.swift */; }; + 1E9033562EACB851BBAB74F033194B48 /* RxPickerViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9166244941FB647F587BB858C1470031 /* RxPickerViewDataSourceType.swift */; }; + 1E9EEA756F2774D73347F1660EEFE3E9 /* ConstraintView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D3B3A052D7F825E2B4B74BC66DE801 /* ConstraintView+Extensions.swift */; }; + 1EBEC0DBDAC11B78976FDA5BA5188FC5 /* ShapeCompositionLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA353CE7AE8D250EFA8C4A3247EB25C1 /* ShapeCompositionLayer.swift */; }; + 1F6A7438F6FDF9A30AA037DADD767814 /* Notification+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FDDD0C23DABA7732501CD8AF1CCE6D /* Notification+Extensions.swift */; }; + 210E6BE763C894C38888F5B166A2EA64 /* PublishRelay+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 557A68D20A14109ADEC30EE3A1D38C45 /* PublishRelay+Signal.swift */; }; + 21F7BA5FF2769F5E50BFEA68348A939E /* CollectionSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAC87840CE67D59C51D0B26BA74041A /* CollectionSkeleton.swift */; }; + 22546F34DC8AFFD4787B3C3770C21F01 /* AnimatedSwitch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E19FA12109EA2B1D8E939B3434B1332 /* AnimatedSwitch.swift */; }; + 2356D3F4002DA73FFF29532A6E46B81C /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10C11E72EAF8B195DDB1928BD42D7ABF /* SingleAsync.swift */; }; + 238C4A1EC8BA1D3A575ADA67F68CD09C /* ControlTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48C7604CA62FB6215DFBB6A7C45EDB5F /* ControlTarget.swift */; }; + 23A5EB716BC87C36228E9E9CEF96F1DB /* Infallible+CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED682ADC810B7280D3DCA0D01A11CA3E /* Infallible+CombineLatest+arity.swift */; }; + 247D0F213507F51B66F9EEFDEC262250 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DDF961CC34E9D9CEC76F2A52AEA6708 /* Map.swift */; }; + 24C44D889CCC3570C277EB1C3CE505F4 /* UIButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB3646BC16DDD6CC7E44EABA6B58C12F /* UIButton+Rx.swift */; }; + 24F623776AD8527B08372983A2A71778 /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EFC2A7CCEE7FD68946B41699013C20C /* Lock.swift */; }; + 2550F0D474DE846FEC5C76CBE85F927E /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD8BC706C48603A873CD59F14C5EF00B /* OperationQueue+Alamofire.swift */; }; + 2592D36AAC2594BE8E75A8F5141040A2 /* ImageModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EA592B787975BD740DF85A0C27FD2A8 /* ImageModifier.swift */; }; + 25DAE084C22F018D4FD26A0CDC1EB3D5 /* SwiftSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79CCD96014790B1C04490CC18D92C41A /* SwiftSupport.swift */; }; + 26319EDD7F4262FDFE348EDB3888DF72 /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = B58CBA3AA57CA05996897232EC752A91 /* Sample.swift */; }; + 2657F78072FBBC8525C416CBB9D4FB14 /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94144BB3737DFCA50D6CBDA921B288CB /* RecursiveLock.swift */; }; + 26C1F54FCAFA5BD581D973CD73E7B70C /* Accelerate.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7DCF16C57C75BF50B3F5CCB76DD8EFB5 /* Accelerate.framework */; }; + 26CA566E8D825C806717F2877A152D92 /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 788E707B4401762A4BA111312D0317F9 /* Rx.swift */; }; + 26EF0B340EFE29CD9278F2237085A86C /* PreCompLayerModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0676D52867ED3A86854134835E52F0A0 /* PreCompLayerModel.swift */; }; + 2722C9B25CF57D3AE89825729DEA9BED /* DelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71933B6884EC0E04F1FB08D3D531237A /* DelegateProxy.swift */; }; + 274DF0E2BF04F6F4F9F1E70CF513A4F2 /* ConstraintLayoutSupportDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08FBD5ED8C8FFF6DF290DCE8F8399024 /* ConstraintLayoutSupportDSL.swift */; }; + 283651FE159A0D98ECE27527A434469F /* LayerTransformNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33520700E00C9FBBBB89B24FBA4EDA44 /* LayerTransformNode.swift */; }; + 2845BA44FED1A376014962A6C193A66B /* ListLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5874F841747FFE1D064649C299B37A77 /* ListLoader.swift */; }; + 287CC3349411453BC71DFD4DEDA52BC9 /* UIView+AppLifecycleNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6337BB2269CC5F2DB6B494F7F76148F4 /* UIView+AppLifecycleNotifications.swift */; }; + 28C6F8CA00102B3388800AEE0FEC9B36 /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5BEB05D94BDF212CDD826BE2A283F2E /* SubscribeOn.swift */; }; + 28D5D9EEAE845C76C8079BD1C77BFE82 /* RxCollectionViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3FE18E0C1AB2C67F76AA021FEEBEE28 /* RxCollectionViewDelegateProxy.swift */; }; + 28DDBE36EE067086F4925C830D668FBA /* KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F31EAC752A1F003ACD8F94AE101F1A58 /* KVORepresentable.swift */; }; + 2C25912842315A22E31DA59BFEADE101 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD902B8A405D4C1EB6494D97EC73FFE9 /* Platform.Darwin.swift */; }; + 2C540DCFDC6F8E190FA83880DE7BBFF7 /* SkeletonConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EB10D17D9BEBBA990AEF87BA0F42A6A /* SkeletonConfig.swift */; }; + 2C64E385669A619F264F7556914DF205 /* UISlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DCE96AB9E9FA3053AC8B0DF7E2C066F /* UISlider+Rx.swift */; }; + 2D038D93CEE0C88E51E744FB034F76BB /* CompoundBezierPath.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9569A95E5B6C6404B3DE7ADAC9DB01A /* CompoundBezierPath.swift */; }; + 2D4559869409A3351874F5370868033C /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3485652A97F1EAFC84E390F4CDAF13B3 /* SynchronizedUnsubscribeType.swift */; }; + 2D54A6F4D7229B917C6BF41E6C5DCB58 /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E5F0AEB88A75A924160B8991DC64A4D /* AsyncSubject.swift */; }; + 2DD8AF8A98A4072A1F5447E0FFD55B09 /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CB3E26C685C33AAD94DDAC2A13DD470 /* Never.swift */; }; + 2E134F2B82EF1A0A8E98A461DC9BA631 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9015A681DA4DF2A9AF382E9A5D3BCA4 /* AnonymousDisposable.swift */; }; + 2E6550EDA354A83B07382CE344AEABE7 /* PrepareViewForSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CC5E86D7D71B850C7D72A19A6FCD417 /* PrepareViewForSkeleton.swift */; }; + 2E69464EBC0B563DF853D07B17E561EB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 2E6B9D42DCB19234F4D78BD2414DA3CB /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87587A4BCD25F7ABE2B906B50D52E516 /* ElementAt.swift */; }; + 2EDB25C9CD31B9B025ABD2E1D693A15F /* Recursive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75207E1DC5C483BB5DE0C5B790629BB4 /* Recursive.swift */; }; + 2F0C9F44FD3AD47DDFC47E0D447EDD81 /* UILabel+IBInspectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 020972B007C5F08B995E8C1C1955D9A4 /* UILabel+IBInspectable.swift */; }; + 2F66150D2FD47CA8479EDC4B3FE14BF4 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68424BAC950DB41E65054A2379D3970E /* PriorityQueue.swift */; }; + 3038C2E2B7542B3AB8131B81424CDCDC /* Binder.swift in Sources */ = {isa = PBXBuildFile; fileRef = B833736B901BD30A23F443B52BCDE473 /* Binder.swift */; }; + 3091F1A82E0FD6ABA766EBC91D4E5DE6 /* Then.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAF26B7796406D469664118D70F8B582 /* Then.swift */; }; + 30A331CD9286145E92DB11D671664C63 /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C0EC79BB2684684092112E66097E51C /* MultipartUpload.swift */; }; + 31F0D187BC76DAB3C2DEE8B2CABB0535 /* RxTableViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = B77639677D7E536F13ADA0C3B0E12156 /* RxTableViewDelegateProxy.swift */; }; + 325CCDB295FFA016638075B5D2CEDD5C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 327AAE190E95AA55FCC8BE533639DD56 /* ObservableConvertibleType+Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = D73F4F7EAF190B3B0E9D75100191A449 /* ObservableConvertibleType+Infallible.swift */; }; + 33F86FAB918B148A63A1575667F9B570 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD7AF050C7F66F9596DB3250B26EF760 /* CFNetwork.framework */; }; + 34019564C5C98A565672FFC27018BDF9 /* SkeletonAnimationBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C1283162259A2F47FC79EB025ED886A /* SkeletonAnimationBuilder.swift */; }; + 34570F3C31C86DEFE70F58BD94BEF595 /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C3783A8A3F5F65A635AF839F252AA0F /* Repeat.swift */; }; + 34737FCF80EB891F68EF7449985DE544 /* Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25E58D99D7B2769C8099EB0C018414F4 /* Create.swift */; }; + 3532586AA98F718BB4D475E26B8279F5 /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 853087100942AF514143837601F12DCC /* CombineLatest+arity.swift */; }; + 3578D665C9C31F719E06D9D9DAF96C48 /* Task.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE387A021380A1F97903F86356357253 /* Task.swift */; }; + 3610F2C29CECD76224B45F870A20BD42 /* AnimatedControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93D42DBBE4B2B3C7F405C325CE7ED02D /* AnimatedControl.swift */; }; + 36C83ECB5C07B2A6F9432D78CA5EDA28 /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B692AA196B6AFE8904EB2BCD1F07359 /* Concat.swift */; }; + 37268A5E666EAD38A8E412B2626DEFAF /* Zip+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64592E246FA7D5B9EF0A591746D1F2EC /* Zip+Collection.swift */; }; + 381A02F6ED67B17114AD8E6508EF9EF3 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBE2CB20E4A11173FDEFBFD41F42F39D /* Utils.swift */; }; + 38A40573B5727C618A65FA918FED55A2 /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = B93578502709168269517790C6A933EA /* Reduce.swift */; }; + 38CBD5B47484781EBD8CCE722F8D89AF /* Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AD24F3A7AC53743B10C3F63B5866547 /* Deprecated.swift */; }; + 38D0534EDDC37793282AD797DF3CF4B0 /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC4D9306A4093C2303CE6A5013C8F4A /* Observable+Bind.swift */; }; + 38D1F9945A20E48EE0E501720A888CDB /* SkeletonCollectionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA1D48C657C7350A77938B94F6F71C48 /* SkeletonCollectionDelegate.swift */; }; + 3927997BB85A4DD42717797E025E8826 /* SkeletonView-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CD14B52B0A8703B45487AEE16E0D0AFE /* SkeletonView-dummy.m */; }; + 39C14E278AD856E7549BD6FE3B4A0557 /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93AF1A70F61D237BFA37E52EC09B3345 /* InvocableType.swift */; }; + 3A07899E85E6FB676A43189205C325DF /* Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = 964824591CA2DE2B4FB7B566519B80FE /* Single.swift */; }; + 3AF28B4E2467590CC9C9AC65BBCD71E2 /* AnimatorNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCF4EDC3F12B4511CA85D4FC7A5911E1 /* AnimatorNode.swift */; }; + 3AFEA39C21C700AAB86C4ACD9436D357 /* RxCocoa.h in Headers */ = {isa = PBXBuildFile; fileRef = 3F4EEAAD35116C85CB0C374EFE4E28DA /* RxCocoa.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3B074EF87B82EC659717ED824DAB6A41 /* URL+Moya.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7918CA582A9312F6A2A6C43295B7F80 /* URL+Moya.swift */; }; + 3B3D152A81491E1C8377FDAD7D37E720 /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CFEF22F3B4602DC87F04B456C1EE28D2 /* RxSwift-dummy.m */; }; + 3B60C02F6E42FD06B128473E00A94224 /* ConstraintLayoutSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 299F2DCA91D09BC1CD72BF3DCF3D0637 /* ConstraintLayoutSupport.swift */; }; + 3B82FB00AD02652E1801233E5684DB1D /* NSControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7928AE6F54492F85775B5EEDC096789C /* NSControl+Rx.swift */; }; + 3BB830496EA62C8CF3D95D868A0C9D5D /* ImageAsset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61CAA5048FAA6F86DBCA93B8B7B6FB05 /* ImageAsset.swift */; }; + 3CD5FAFC746A76D73C3F501734199DFF /* Typealiases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79C9F7290555E8206ECC8A5A27A6FB84 /* Typealiases.swift */; }; + 3CE45B10C39699F9A3F92F64B599215C /* Maybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F5AE1F6568B946172123A13DD26E4AC /* Maybe.swift */; }; + 3CEEDAD8F50DB77D1BDBBD2ADA78CF17 /* SkeletonTransitionStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = E46E04ECE7C5DC3EDC3C423924255D42 /* SkeletonTransitionStyle.swift */; }; + 3D42C9D3EEBE1EAD7E365276753FE99E /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 637A7B8E0568D3EF7B0A2556D5DE4A06 /* Queue.swift */; }; + 3D445FD9D8FFBDD79E0D04BDFE96B0BB /* Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E360D14592776CF6F8A12605C00C389 /* Signal.swift */; }; + 3D54F55B562E67C4AB35ED725E04108D /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61BCD1938C7E8E565B52A5E0BE04084C /* Timeout.swift */; }; + 3D674DAEAD9EEEAF023B6EE96C984C5B /* Font.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ED739459C8BBA3A49BDF0C535E3D6C3 /* Font.swift */; }; + 3D94CFF2A5A7C85B6A85B662327B67C0 /* CredentialsPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99257C69694C651E2522624CF9C224FD /* CredentialsPlugin.swift */; }; + 3DD9694A6D1F5035C6C400C6912B9E36 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED7660BAC6E4C3F93494EBA47017B0A4 /* RxCollectionViewReactiveArrayDataSource.swift */; }; + 3DEDFA52B3A196F6D3E1F0937617628A /* ConstraintLayoutGuide+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5988D1FB2FF114A5F12FAEA50CC10BE2 /* ConstraintLayoutGuide+Extensions.swift */; }; + 3DF3AD9CC46A68BC88BDA42594F73911 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 683A06F221EAF470EDECF217893A1459 /* Errors.swift */; }; + 3FC5414EC9FC6F6CBFCFDAE20563BAB0 /* CALayer+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 668793E6F8B1D1C36659901F3D212F86 /* CALayer+Extensions.swift */; }; + 400964555B766D5EBA2E15AD96CB17C7 /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 13AE6E53A98B27F06918950C3CE6FAFB /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40E76B8F9326C19C56089EA163D25949 /* NSTextAttachment+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 506581462DCF2AD73F7FFB993DE007D8 /* NSTextAttachment+Kingfisher.swift */; }; + 4127F4FF9046879314D9DA3CB7D8C439 /* StringExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 958990AC25E732E67FE51103C087723C /* StringExtensions.swift */; }; + 4147793AD077CAF6648567B479AB387A /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8155266263D676CBE1AA5434A651904 /* Error.swift */; }; + 4153B903876D19347BAB9596EB94707C /* UITableView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2516CD94F1705F41F9E9975E40EA932 /* UITableView+Extensions.swift */; }; + 415C5905FFE8D629B9A11EAEBBF780A6 /* UIView+Transitions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51057370900323FCEB104A0AFA33850C /* UIView+Transitions.swift */; }; + 41AEBE3D7FA634427F4C61A01A9B5B3B /* FloatValueProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64B2FD33538D38B86472940515F0DCC5 /* FloatValueProvider.swift */; }; + 42CD03543D2E6551D6BFAA58199AEB63 /* Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35497D877BD0C0976B31A79849E5852B /* Deprecated.swift */; }; + 43863B6D6A0E47B6648BB7B469736EDD /* LayoutConstraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1429C1A73E6127C81B743C89411AF246 /* LayoutConstraint.swift */; }; + 4475AC7E1DABCB3149A11BDA941FC30B /* Infallible+Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB73A1C3B4A7F9EE2A1685D474B50FA1 /* Infallible+Create.swift */; }; + 447744AABA6D0172810EC3B34236824B /* ImageProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51C9D42FAF78B6A8609A0BB2C9215532 /* ImageProcessor.swift */; }; + 44AEBB2D29B9FB87530556A0CEC170F7 /* RxNavigationControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51AFF4C368AA3CBD436E0DC6CC0942AC /* RxNavigationControllerDelegateProxy.swift */; }; + 44FA570548F4A7ECA029A49106D0D959 /* GroupOutputNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DD295E670FAB94E394EA854B93616CF /* GroupOutputNode.swift */; }; + 4512E08421FABF56C88254012381979B /* Delegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40833CDFE3A86FC1485A6A8F67ABD5E6 /* Delegate.swift */; }; + 459F2B9F92966946BA75A00EF1903803 /* AnyNodeProperty.swift in Sources */ = {isa = PBXBuildFile; fileRef = A178A97BCE6505C2B3FD32FCFA25A45F /* AnyNodeProperty.swift */; }; + 45E4B0E2D63AB3C1763DEA7393891463 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A8C9E61C5B107DF52BFA41FF3621A6B /* NopDisposable.swift */; }; + 4634BA717BFCE522E5B42304C6A78B5D /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5E0E1270F1DC7CA9ACC0415782C2011 /* ParameterEncoding.swift */; }; + 4680B52D35120A71C11ECBA5314E2187 /* ImageCompositionLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC9C172FF95F6BCF1D316CE2E1F746C9 /* ImageCompositionLayer.swift */; }; + 4700CB6BDC06861FB8675B3E9481F6CB /* DashPattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EBADBDD2F7B15C127B92289C76915E4 /* DashPattern.swift */; }; + 471611F482CDC15BF464E3BA9CB83968 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 944DA138D0F8B5754B4374EDCE6E9B0D /* Notifications.swift */; }; + 47188F85260A6C84881F9E5C01496DC6 /* ImageFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF9ECF5DC98A260F6CDB707618BA0859 /* ImageFormat.swift */; }; + 476B533C5822CF0D778A6BB5EA1E7916 /* Shape.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1833C016AFDFA598B3C7CE1DB8E431C5 /* Shape.swift */; }; + 478E6877D343FB3036F1ACB05BC9715A /* MathKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = D03B4C2B16C9EF8A9E6B858BBCE8BF5A /* MathKit.swift */; }; + 47B48B7531CE161773DEF0B851D08037 /* ControlProperty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C4579507D0921EBF1E697F281041418 /* ControlProperty.swift */; }; + 4805CB07760ACB4F6CD9AD2DDA6A3198 /* AccessTokenPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7E83FBCF31EBBE7B947981E091EE7D6 /* AccessTokenPlugin.swift */; }; + 4810CB587998CA2D2813FED0F8F3DFF6 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D168476D52EFA1C2C2052BBFC538ED3 /* VirtualTimeConverterType.swift */; }; + 482527EC3E623021997866C1ACCA1343 /* Completable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504F6A77D82470D4C99C670B2C9F0049 /* Completable.swift */; }; + 4838B3C8759DACF738F61BF91100379A /* RxTabBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2460FB307D49DA24619E67C6AC7D77D4 /* RxTabBarDelegateProxy.swift */; }; + 4878A6C8BDEF6FCC155719CA93BA9586 /* _RXDelegateProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = EF25D6E0F21F2010AED7C8FFBB456444 /* _RXDelegateProxy.m */; }; + 4994F1CABB9926703D82BA0D9D66321C /* RxCocoaRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = 1DDF1003EE8B21290AD02B9110DBCFAE /* RxCocoaRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 49BF03182077B22857C2855EEC0798C2 /* AnimationCacheProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49B32A5355B9E0D5930A79C4C83652C2 /* AnimationCacheProvider.swift */; }; + 4A18A6CB333D9CB3A52BF554B77A570B /* Transform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A201CE6C47D308F8A0460BF3C410204 /* Transform.swift */; }; + 4A2672188800EA69DF8496907162697E /* GradientStrokeRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07717BA267486AC9402D252D4961A068 /* GradientStrokeRenderer.swift */; }; + 4ABE13EFC755B386D82CE75AB8BB9BDA /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1090A2E25CADE447F0E441B7F86C09C4 /* Empty.swift */; }; + 4B745396FD1223BA8532DFE2216E043C /* NSTextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE2F81EE0A1DEAFA1442491D488A81D9 /* NSTextField+Rx.swift */; }; + 4B7F8E0C244B08EDCAAD9AF99193CBFA /* AnimatorNodeDebugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0F310186ED318969FC8006B3056F8C7 /* AnimatorNodeDebugging.swift */; }; + 4BCB6E64B090ECA7E41B5C26E6E05D9C /* AnyValueProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB4D150E2481BC5A0BF7A81282C2DBD6 /* AnyValueProvider.swift */; }; + 4C1D2F33A32937F016D0C68D5EE1AE0B /* TextCompositionLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60DAF39780BEBA99153B7A449B8B5A5A /* TextCompositionLayer.swift */; }; + 4C4807533D9C80FA1A41206498B712C2 /* Int+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC6E4149138E959D0E81F99FB12B5708 /* Int+Extensions.swift */; }; + 4C6F321163D29CD3DABAEB08A178601D /* AnimationFontProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AB11D015902E3E50194C7855580589E /* AnimationFontProvider.swift */; }; + 4CA13A0527BC57DE2C54A0F3B5ED8652 /* LayoutConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = E45508CEF09B7205462B0A96CBD68DEE /* LayoutConstraintItem.swift */; }; + 4EB4328C78B36211BF7D50529327FD7C /* UINavigationController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EAF4EDBA81B4579F87F6B03975305E7 /* UINavigationController+Rx.swift */; }; + 4EB8DC557500857899B36623C09000D5 /* UIColorExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECAA3D71D0B3875B94B4A632D9A2654D /* UIColorExtension.swift */; }; + 4EE0F2D2112CE993AEA24549F5DB19BF /* UIControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 948610301CCEBB19AAA757417190F369 /* UIControl+Rx.swift */; }; + 4EE1F030245C299E2BB2375CB14B0241 /* SkeletonTextNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE117BBAB45229F7D3240A99FD8D2275 /* SkeletonTextNode.swift */; }; + 4EE7583081DD2A762FA35A2A7C54FC56 /* PathNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8368A92C8EA09600C9E2C855F83C8C01 /* PathNode.swift */; }; + 4EEDB45F2DDBCD0D0D213A801A7B09EE /* UIColor+Skeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 375F61A82A5F40C5FD6C91FCCA9DACE9 /* UIColor+Skeleton.swift */; }; + 4EFD31D7DB8D26D9D031A2225A0C6AEC /* UIApplication+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D95787CC4368F63D40C76E31152FB436 /* UIApplication+Rx.swift */; }; + 4F744303AF9B5E7CEF8C3A9327E852B9 /* ControlEvent+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A39BB18953213AFF2BE09075C24C3A2 /* ControlEvent+Signal.swift */; }; + 4FC27FF6DF0328A134393A57E735977B /* RxTextStorageDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98A27FB74C2C193735A702F70EEAFC2D /* RxTextStorageDelegateProxy.swift */; }; + 500F5B102872362C647C424D690CDCC4 /* ListPlaceholder-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A6D1220EF0F905357EBF2ABB4C0F553D /* ListPlaceholder-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 505A0698D846ABF6E2A2413789B89D3A /* AnimationTextProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0B8965EB066B4207C18FA0BB86BB3F5 /* AnimationTextProvider.swift */; }; + 50681D70D26BA315A5DDC1365B4CF0BB /* KVORepresentable+CoreGraphics.swift in Sources */ = {isa = PBXBuildFile; fileRef = E64F20DBFC58C1AB19FAAA4D16B19738 /* KVORepresentable+CoreGraphics.swift */; }; + 507044595704E8B86462582ABB193472 /* RequestModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56944244C79D6B7A8CD6B1AA50E54632 /* RequestModifier.swift */; }; + 508783CD55FA16BDB4019BEE545BE0D3 /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2FD251C9AE8976588211B879701AFB3 /* ObserverType.swift */; }; + 50F7404C67D49C3F124905E263893947 /* SolidLayerModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FBFC9C2376164147EDEEB37CE43CF48 /* SolidLayerModel.swift */; }; + 512FAFBD71830F126224C033B6C45F4E /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 446E3EB3F699A644D3549F0D2657CB69 /* RetryPolicy.swift */; }; + 5162C4A6F96947FBF255F7130CE28A6D /* Moya-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F23704FF9C44B7431AE73A27EEDDA236 /* Moya-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 51A4A1046676D304410544EB56732A49 /* Constraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = E298B1AD2B044011B7A989681F2936AF /* Constraint.swift */; }; + 51C984425C777CF8B613C230DCE2DB65 /* UIGestureRecognizer+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84B58261A8D6FC70BD19808D6EF5D68D /* UIGestureRecognizer+Rx.swift */; }; + 528FC1CA236EFA61CA43894D0A2C5B96 /* SubviewsSkeletonables.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60E8F31B3DA3B9958C36DA86B0A97F0E /* SubviewsSkeletonables.swift */; }; + 5291A92FB6C7E3FB265DC22EDD908884 /* Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C201370A855FCF81DC8E1D8DA720491 /* Driver.swift */; }; + 529BDA5E8CE104C4B384017447D0DC60 /* _RXObjCRuntime.m in Sources */ = {isa = PBXBuildFile; fileRef = 44F6BDD6C63042363FABEB4018BD511F /* _RXObjCRuntime.m */; }; + 52BE6F747C26DF2A24532458E55DC10F /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 354FB31B9128687D8F619B708088196A /* HTTPHeaders.swift */; }; + 53A5C4AC5D469408BA8EBB350596C5F4 /* CompositionLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FC173610BDE1E63571E4D11392019E3 /* CompositionLayer.swift */; }; + 548B9145185925F281D9B1951379E6D1 /* RxTabBarControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92D160F41A5F10649E32F3FD52D41D21 /* RxTabBarControllerDelegateProxy.swift */; }; + 55100F4BEC29276C7C6BCCF1C73F213A /* Glyph.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78B5248C51B733A30C1C2CEFBD955431 /* Glyph.swift */; }; + 5615FDB610CE9BA1D0BFF89B9A5257A3 /* AnimatedImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 433B80DE9E0F4B1F42A3E818AE8B40DC /* AnimatedImageView.swift */; }; + 5880747D56EA9504CFCB91A27102570A /* CacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 438454217A3C55CD48E9CBD2755D3F22 /* CacheSerializer.swift */; }; + 591FC15E43DF0201FD978AAED60812E8 /* UIView+SKExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D9607F168FFEFCF17906EDB2A22DFF3 /* UIView+SKExtensions.swift */; }; + 595B1FB5D2B65054035261346DC105AF /* DefaultIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB3D0AD0E7F8C7B3D7C26CABDA7846D4 /* DefaultIfEmpty.swift */; }; + 59691189B7A014BB0230561AC0A489A6 /* RxCocoa-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6CDDF1EB0C34D6D1DFAC3CB89513B98E /* RxCocoa-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 59B555B51F6C00939F675E74B00EA92F /* CompatibleAnimationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A274191F06572D07458949D5AD6657 /* CompatibleAnimationView.swift */; }; + 59B56C56C55B8AE7FF142CAD2B59FD51 /* MoyaError.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3E6345266B4A99F5832756CE9B23BCC /* MoyaError.swift */; }; + 5A3D602684104FE1F41A6BF7ABAB641C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 5B56F1C7F0598A78E720E4D0F888851B /* Source.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66FBAC3E0E191ED981538DBCFFBFBD83 /* Source.swift */; }; + 5BA4B59005579BF090EB06953A0DEFEF /* RequestTypeWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = E05745650ABE7B996F364774222E1168 /* RequestTypeWrapper.swift */; }; + 5D4CC81D40F9408E73C5E4BAA5514270 /* Placeholder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CD3719C675D6F03542CD7EFCE7B46EB /* Placeholder.swift */; }; + 5DEA5E130127037F3F7BD7D2B12E1E7C /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA03E550D12601C16729AAADF5DD65F0 /* SessionDelegate.swift */; }; + 5E3BF2B719B3A034C173D16B3ABF682E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 5E443AA3466CCBDA19C7B16C421269E5 /* TakeWithPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4AA012F0B4AD6EDD134E7938E204847 /* TakeWithPredicate.swift */; }; + 5E594FA3290D3D70F500572D0AC100DB /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A75C74B3699B0CDC64C7C23892A9BA1 /* URLConvertible+URLRequestConvertible.swift */; }; + 5E8BA529DFB4529006967624044FEC1C /* ConstraintViewDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44B994A40E780755A43AB36546BE247B /* ConstraintViewDSL.swift */; }; + 5EAB4643D7EE612FF0DD0F7D11288863 /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = F908E30565F6F797BDAC18B70C873EC0 /* Window.swift */; }; + 5FA526557719FDBE81B1974B113CF600 /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A04CAB33A23F87A51DD2CD941A6895F9 /* SwiftyJSON-dummy.m */; }; + 610E8FA6DBC3690E8DB7616E0389CF4B /* UILabel+SKExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E84906E7CC87F8BCFAE71AF108F1777E /* UILabel+SKExtensions.swift */; }; + 61BBED7470DC5C4419884780188079EC /* Marker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E0E9B03955AD5C69E96676AC5F31FD5 /* Marker.swift */; }; + 61F68C272EDB42E7B8AFB512A11E819C /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72D98974480C49492DA09E6CDDE9A7FE /* SkipUntil.swift */; }; + 628059AB7BA3EF69BEDD42689D4CCE23 /* SkeletonFlowHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1079D87BD115E4351902A4B9A6A98EA3 /* SkeletonFlowHandler.swift */; }; + 62815773AA8209068D20C2BDB0879223 /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5466629AEF3C4F485F46A299FE40ADA /* ObservableConvertibleType.swift */; }; + 62F299B4704A7C95FB5866C6CDE2E2FD /* ConstraintOffsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FF59D35D100AB4908E8C05EA0DDBBBA /* ConstraintOffsetTarget.swift */; }; + 6329167CA0A6D5885EA63ECDF0D29FF9 /* SkeletonLayerBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A097698ED559F253065E3FE68B41B5AE /* SkeletonLayerBuilder.swift */; }; + 6440487903AE496B5B0CE78022D7C4E2 /* NSButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4264469B6581B43C3A3379E6C8927360 /* NSButton+Kingfisher.swift */; }; + 65029D089337A48EC4D0055E29E30A97 /* Moya+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65805841B5A618A05FAAF656AE93E772 /* Moya+Alamofire.swift */; }; + 653B61D0B8A3004974DBE0AFC9B37AF2 /* Date+Dispatch.swift in Sources */ = {isa = PBXBuildFile; fileRef = D94A28A6B8ADE4854BB40514512CBD9E /* Date+Dispatch.swift */; }; + 6587B749518669C9950777734423A245 /* ShapeLayerModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D873E925CE42958A7B41F3F37920F0D /* ShapeLayerModel.swift */; }; + 660E283AF231972CD7165B566CAA487F /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBE5754AAA9F6ACD8F57F8DD39D05E07 /* Switch.swift */; }; + 661778AC0812FF0081A94E899B339F77 /* LayerImageProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11A089E572305D54324465FF35B215E3 /* LayerImageProvider.swift */; }; + 669420900229BD5DE7A7B7EEACB2C5CA /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4764E8A7D0A60A2B1959E62D5EE630A8 /* SkipWhile.swift */; }; + 670BD4A21A32FB96FA076DC9BB475A33 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E0771F18B5F0586F32DDA90BCC27E7A /* Queue.swift */; }; + 674AEC9F05744B4C977CDA7A8967CABE /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8ABB4DA8734B11EC34DA694E8CADCB8 /* Cancelable.swift */; }; + 67975D9D65BC7E2F5C007BA1E086DC06 /* SkeletonTableViewProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = C97468661B020B68BD7AC08EAAA90D1E /* SkeletonTableViewProtocols.swift */; }; + 67C58CFFF7E94C6235B1A857EA921F3C /* Keyframe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FA4E4F7F53DBC89CE7DD14EC091577B /* Keyframe.swift */; }; + 68623BC382EACE93D53213D1D5AAAD3C /* NSTextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A13C79480FE01C9508D13C16018BEADA /* NSTextView+Rx.swift */; }; + 688337B18659C4BF722F87AFC4FEEF81 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14F87B9368AD2DD04C9404B2B7C3D990 /* SessionDelegate.swift */; }; + 69537EEBAEE542798C9630CB8F96DF8D /* NotificationCenter+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFB4AB361BD8533DC4A1F3D99015F9DD /* NotificationCenter+Rx.swift */; }; + 6ACA51DA70224B785DA1F9C9071CAA76 /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B46F7D182E6FCA5635A2BEA65BCF483 /* HistoricalSchedulerTimeConverter.swift */; }; + 6AEDF3D1798888D99C3C7C6BD2F3779F /* Color.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA79228103DCF330C6CF010CF0F509B5 /* Color.swift */; }; + 6C1352E8D74AC09B9A62E498BEB521B6 /* ExtensionHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23AA520C599D9905EA822AD7D599635F /* ExtensionHelpers.swift */; }; + 6C5BC6342C03A7D2F1BFDBB5D087CB08 /* ImageDownloaderDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53827C32DF6393C2BD736C97B9831F75 /* ImageDownloaderDelegate.swift */; }; + 6D8CDC66C950346874056F3F45FAB0FC /* NSView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B221BB5199889A8401D51EAAC1E618E /* NSView+Rx.swift */; }; + 6DB650B92A505AC2F62BD77615A1D2FD /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E378619273CDCD4DFAF4A5E807226744 /* BooleanDisposable.swift */; }; + 6DCB85FA3A3AAB40FE841711B901EAA6 /* ImageDataProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBA5958B85EB0C407E6F8EF90D38FD5F /* ImageDataProcessor.swift */; }; + 6E702FE34E6DD5A6B6C57C50C8F0783B /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79CCBA90D8565C6D22EFAC3E476BAD52 /* Catch.swift */; }; + 6EB45229225932A7BE48AB1B9A54D569 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0A389573E7C58DCFE123C674C78E89D /* Result.swift */; }; + 6F45F1B2F2A1654AC02DECC42FA02A58 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E303F3D83643F01CB24EE4934852916F /* BinaryDisposable.swift */; }; + 70527867C4C4C965053E4283F3778986 /* RxCocoa-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4366C669579E73C3ADCF0EFABC667C90 /* RxCocoa-dummy.m */; }; + 70917925E9105D38F63D920C592E5240 /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42C2D48C54A7871FC049E1A1E12314BB /* Bag.swift */; }; + 70A41125865DDF878FC4CBD646349805 /* UIScrollView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DD434842DAF29DF870CB0898C2BECDD /* UIScrollView+Rx.swift */; }; + 7121DEA57978B70F6973FE651AB88561 /* MultiTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BB013FF0D1B8DC50E478E8D80AED779 /* MultiTarget.swift */; }; + 71390993914649DEE98167EE490F4AEE /* ProcessInfo+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA50B9E5875D7540898597072A675557 /* ProcessInfo+Extensions.swift */; }; + 71D5BDF4D210C1DC54AB197B1D2E9D13 /* ControlEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 822AD736BB3D75AC5047E27811EC926F /* ControlEvent.swift */; }; + 7260A7AF7CAC80E1C485936F08BD5D75 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69B2B19CD8426F161013829AABAA4A64 /* UIKit.framework */; }; + 7347C527A87F0CDC12F50B3855B5F48D /* Indicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0A8B19E1BC4E88AA8159FDE0A173A3 /* Indicator.swift */; }; + 73BA2DACFAECAD7153E206434CCA1CAF /* Bag+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AED798F345A7AB54BF82C5FD690CEEC /* Bag+Rx.swift */; }; + 73D036F6EAE83FED494970377AE0C12D /* String+MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40FD9C80907D086CB5E915BB58C9CFFD /* String+MD5.swift */; }; + 73FDC454634CE5926EAAB69DE8944A32 /* Enumerated.swift in Sources */ = {isa = PBXBuildFile; fileRef = F066C45D5BADC84EDB0EE2E961787719 /* Enumerated.swift */; }; + 7425A145B15B33A92BB41EAE2CC019CE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 743B669698434D7300922601465DCE62 /* Cancellable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00CA608937E7087A2803C3E379738798 /* Cancellable.swift */; }; + 743E4C01D4872CA7723D9BF9F6A5D59C /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = 353F2BD4A9347C8D3533715105EC244C /* Disposables.swift */; }; + 74C08C8EA83869938C7A25C9A88D22F8 /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECF872CAA95230C7E18A18B762F9204A /* ConnectableObservableType.swift */; }; + 753C2663E1979F0B2F76CE467FA19F59 /* Trim.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE21E076DA1CB81D248C4EC102DE5C52 /* Trim.swift */; }; + 7580FAAB1BDA52F5A969E5571D1A5973 /* ConstraintAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D32CA634B512FB58E0DFC658CA4C36 /* ConstraintAttributes.swift */; }; + 75D86DA3C2D36884965F757171B628E3 /* PointValueProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 287C08308C6C979AD2AE20875F806582 /* PointValueProvider.swift */; }; + 7618FCC1078531135C1CDFEE2611F91D /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31FD46ECE4E238AEABFE3EA76B9F6F66 /* TakeLast.swift */; }; + 76C6317D31C85D988550BB479703A02E /* StrokeRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2399A067CF54CE64CA10F9123F63F19 /* StrokeRenderer.swift */; }; + 7764AA5F6BBFC6ECE43959923DD007D3 /* ConstraintDirectionalInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85328C52C4A45C6C830C8F5D72D13AEE /* ConstraintDirectionalInsetTarget.swift */; }; + 77F9AE6FF8AA6303492F6E37D57218ED /* UIView+SkeletonView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B44E8DFF310AA7060F227B091F7A87C0 /* UIView+SkeletonView.swift */; }; + 787514B3319DAFFBAEAF87B259006805 /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 391AC99DE47C2D48F06B251895B9C015 /* ObserveOn.swift */; }; + 787BA6BBC90B8F6A78707BF992CD8B7D /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 779509B5AC8A026D6CCF04664FE67F0C /* Box.swift */; }; + 79A3FB163FD740818AF7C0FCB1772DF4 /* NodeProperty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36162C76DB6AF3C2B51AF1A95E380696 /* NodeProperty.swift */; }; + 7A0553AB2F1A53F7B21579734AA6EB87 /* SkeletonTreeNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EA480CD3DBE3432276B6BC5B8469E3E /* SkeletonTreeNode.swift */; }; + 7AA2D1AFEF137A1CDE9014885BF7E7EA /* UIView+CollectionSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7B6034196E136373C741FBCDB769798 /* UIView+CollectionSkeleton.swift */; }; + 7B2C37E4FDCA29C551A6C9DCE0505137 /* AnimationPublic.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21345028EFC317FB2DBC1A4C9ECA08FA /* AnimationPublic.swift */; }; + 7B36C7B7BAAC6A742AE38C98484D9AE6 /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE837EB01476AC48BAA57CE0FE92E4BA /* Debug.swift */; }; + 7B98805FF1F385B8B4387D57BA0A9090 /* PolygonNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8A5986178C2D57C6A6D36F0FBDA1536 /* PolygonNode.swift */; }; + 7BEF420E8F9099C5079845A9BE4DCA63 /* RxWKNavigationDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 514A2A555C799CAE4A62B986735C1A78 /* RxWKNavigationDelegateProxy.swift */; }; + 7C0DC741562A17F09F60EB9329DDA7CD /* ControlEvent+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97F8A41D5BE85EF128CB8F2401A2E9DB /* ControlEvent+Driver.swift */; }; + 7CA1733A94C18DB9B7B68FDF965C1DC3 /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23AD8F2A2CD08E671C3FD51565E63057 /* ToArray.swift */; }; + 7CC6F389A6BAA882FD6D138EA0552095 /* TextAnimator.swift in Sources */ = {isa = PBXBuildFile; fileRef = F422053BDBB0BDDDDD82DFAE5FDF6CFE /* TextAnimator.swift */; }; + 7D277A69B12123C0120607B1EF392E87 /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9DA97D80CD7B83E04907CD379D46AD0 /* ObservableType.swift */; }; + 7D63A41230675587C871B7DC59D0CAC5 /* EllipseNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CC11B921788E101765C74857D6473EA /* EllipseNode.swift */; }; + 7D7E665800950F8B498A956A385639BB /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE3A4F198D553449CE8B70E24399F16C /* Do.swift */; }; + 7E027CD0A35229E2E0333ACE3BFF3B20 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 7E3402342205B2DC03468A7FD95F61A9 /* NSTextStorage+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BEF0FAAC7C86B3C907BF5962D972DC3 /* NSTextStorage+Rx.swift */; }; + 7E4ACDCC3CC0F6A1B7EC8ECD64B83D62 /* KingfisherError.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4E560FCC7FB3037CD48F0A911A4B06D /* KingfisherError.swift */; }; + 7EDF4A4786BF27B10D07275427BBA4CD /* UIView+IBInspectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2AD080F3651EBED22DAC46B01E5DAD7 /* UIView+IBInspectable.swift */; }; + 7EEED39CE5F3611AB4D7205FD038021E /* NSObject+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4828B93FADCCFD4794B2484CAACCC552 /* NSObject+Rx.swift */; }; + 7F101E76AA506DB15D2D392E9FFBE11F /* CompositionLayersInitializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EC82515D323F64C29E236D7341AE7AE /* CompositionLayersInitializer.swift */; }; + 7F19ABB4D0B4EA343EE7C8266A80A92F /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25EEA2EDD084B84C71D534C5172BA41F /* SchedulerServices+Emulation.swift */; }; + 7F60B371FE78073E7DFDD621FFC482CE /* URLSession+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7067BB1DCEE4AEFF65144415F41FD9B9 /* URLSession+Rx.swift */; }; + 7FFF6A07CE06086379767B9A4462B223 /* UITextView+IBInspectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3BFC79BAF981C0610BE473F2FC97028 /* UITextView+IBInspectable.swift */; }; + 802604F6837A93FE6722E5C5AEF91A41 /* SkeletonAppearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8ECFAE0BD799A0E0CF48BA1E63F906A /* SkeletonAppearance.swift */; }; + 81A394201D240F032A6108ED479B427A /* UITextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B8A4D3E4C2891D850DE42B3402AC27 /* UITextField+Rx.swift */; }; + 81D31A9220A1D5D0800757FD461F0CE1 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0879FB18BD6A133DD98B8EF43021FF20 /* CoreGraphics.framework */; }; + 825062025906CE93C5D124E1FD9A811E /* ConstraintMakerExtendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC30D3FB284CDC3251E256458BAD5B33 /* ConstraintMakerExtendable.swift */; }; + 82FBD2B7C1EF83494D5AE1C328212488 /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C03C324DCEC33D1BCDC0F49FEA3BF5A /* LockOwnerType.swift */; }; + 83B47C9B322E517D85EFFBDB6A9C536A /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 349681955FF4E7F5E8E163E05F167288 /* VirtualTimeScheduler.swift */; }; + 841FBD1EB10F9112D309BB28BD10CF1D /* SharedSequence+Operators+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03E82BB2AAE6AB5C51DB74536D697019 /* SharedSequence+Operators+arity.swift */; }; + 843588510847505E149784E74D2CB687 /* AnimationSubview.swift in Sources */ = {isa = PBXBuildFile; fileRef = D483C06CDB9E8C25AF3499A532E7326C /* AnimationSubview.swift */; }; + 8449EB1DFD43E222D687D5A8D2088D2D /* ConstraintLayoutGuideDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5D4436D14D000A1E81E60708A232A60 /* ConstraintLayoutGuideDSL.swift */; }; + 84648F04C89B3344A503049AE2344D36 /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2A62ACB1FA99BED968D941C78B678FE /* SingleAssignmentDisposable.swift */; }; + 84CD1A3D6E57178F901C732FE0B61C95 /* BundleImageProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E56681B529C28A6E689C753AFB5C5A9 /* BundleImageProvider.swift */; }; + 84D5EFC338A8F4982B55D6B06BA03F48 /* SkeletonReusableCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4153857072584D894C8031B00E5FE798 /* SkeletonReusableCell.swift */; }; + 855C1CF730DC09A4545491BFF611B823 /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC6E0F0D4A9AB5A9CF292BA58D1C9B2E /* RefCountDisposable.swift */; }; + 8588448262230A0643BE8EB3BBD8FE36 /* UIView+Swizzling.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D9520E93F1C6E181AB64C6705EEDEC9 /* UIView+Swizzling.swift */; }; + 85B4ED0D6B1B81D8100C84E4C559DA14 /* URLRequest+Encoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13D91F6A2C0E62BC0F8D907BFDFC83EE /* URLRequest+Encoding.swift */; }; + 861C9EB0C760A8D446C3A4F1320E2C06 /* AnimationViewInitializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9896557140AD1D536F8409779DBAEFF /* AnimationViewInitializers.swift */; }; + 8670DF35FF314F88247A38208C5A376A /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78EE67455BC257C012D56E3CF4289753 /* Multicast.swift */; }; + 876BEAC75F36A8BE7DC6FFE1CCED3136 /* CurveVertex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69E2C711E5C8B7DB42DDBBD92A6845D1 /* CurveVertex.swift */; }; + 87F5E9DA1ECD4A4BBCF2A509BCA14947 /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CA31AE5F7ECFABC6C659814E6834818 /* Image.swift */; }; + 88B2B239168C5027BC6852A05C0F02D1 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 40D34EBDA2B1EA531EE140BE3FA0AAD9 /* QuartzCore.framework */; }; + 88B8AC6029632517A72F63AFC12C5B3E /* Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67AEAD300238A4E2EB710FE822BB3A5A /* Kingfisher.swift */; }; + 890CC10F66302B68299B534848CB8B85 /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0C51C8150CA22332D6DAC6B496EDF75 /* ObserverBase.swift */; }; + 894BF76C4272C38C9E17385110BF4A41 /* _RXKVOObserver.m in Sources */ = {isa = PBXBuildFile; fileRef = CAC7D9C80495BBF05241A594E6C87603 /* _RXKVOObserver.m */; }; + 89559315BEB73C84E776677C8EBF01EB /* Pods-sopt_29th_Assignment-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6353C2C95453DCBB87CC569B4A188FCC /* Pods-sopt_29th_Assignment-dummy.m */; }; + 8A41383549AED0DE41709306C7D63DFC /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 968326A729170F8CF833DC5AE0E14E9D /* MainScheduler.swift */; }; + 8AB17FA6B8EB58971DF433547FC6E923 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = F43F0A34089FF64327D57D242A57BF6C /* Filter.swift */; }; + 8AEF0775CDF920AC2DBE0C725B59EC96 /* UIStepper+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A8B74BEBC874E98F39F2E95F0E5A2E /* UIStepper+Rx.swift */; }; + 8B25121213F37B3FD5A37ADB0A780CB6 /* TextLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27F720B3CAA847C7E9C1D8382F05D5A6 /* TextLayer.swift */; }; + 8B649F531E6ABDDB4008CFA8F6F670DD /* Endpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75AE3E15F1F864EB067AB303139E6202 /* Endpoint.swift */; }; + 8B7686A732E13434E997809196B15955 /* UIRefreshControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A4FD77D127220741C07ECC1A4DB34FB /* UIRefreshControl+Rx.swift */; }; + 8B9CDBE3FFD712120CD66DD8B06C44E4 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 456259D8BA3A3A1A953B73B998EC12B9 /* ParameterEncoder.swift */; }; + 8C6546C1EF4F153DF3795CC6FE189E5B /* ConstraintInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C2A0E95B0BA6D0627206971E21E650C /* ConstraintInsets.swift */; }; + 8C93569C689ACD00E456B23E73D80BFE /* ObservableType+PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = B63B29F6B0F59E6DE8F568AEB205CBF1 /* ObservableType+PrimitiveSequence.swift */; }; + 8D3213017B92C533EB9E127BA5563BBD /* PassThroughOutputNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFD49E72672C87106DCAACF65BA77F61 /* PassThroughOutputNode.swift */; }; + 8DAB16DE913A7BE02FA4F6E98731044F /* PublishRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32C25D90E00FED9797258D70F1F617DE /* PublishRelay.swift */; }; + 8EA5CC7EF28B004A8A813925E4F17F93 /* WKWebView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6ADB32B034C4EC108D132E1D1886EB47 /* WKWebView+Rx.swift */; }; + 8F9E1EEF2FE52E3231A769722D5C4148 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5CE0BDCFF01EB2384FC3A771ACD4E43 /* ServerTrustEvaluation.swift */; }; + 8FD03CB2DC0FDA1E9636D373909DDDE6 /* MoyaProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44FEACAACB5FD6154FE9B04A8A54FEE1 /* MoyaProvider.swift */; }; + 8FD9CD608C4EAAFDE6AC7B8B9EF0FF5E /* ConstraintDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18E8574D9A7619ED4C44F466CEB9B55D /* ConstraintDescription.swift */; }; + 8FE0BD68EA39B931E49D9C038BE80B65 /* UIDatePicker+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB0164FE6305B6D92B73DFD76AB7F27E /* UIDatePicker+Rx.swift */; }; + 9067F373822D84F800203D89278E08E0 /* ShapeNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C156DEDEE5322CEF2B1F759D8B69489 /* ShapeNode.swift */; }; + 90FD5AE525E138A473723FD79AF73273 /* ConstraintDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB872120E955C14C936A66F79C63056E /* ConstraintDSL.swift */; }; + 91C2A156C0264EEFBB1C83787451AFE7 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92ABA31BDF9745B8D40F3B5E55502350 /* RedirectHandler.swift */; }; + 9208290CA7980F567B71D2D74DC0DEFE /* InvertedMatteLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE884D500D9139650D8E47EB891A17F2 /* InvertedMatteLayer.swift */; }; + 923B375805761A521F28D04DDD84B504 /* UIButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 881461D11DAD4B0D0627B6EFE37D1926 /* UIButton+Kingfisher.swift */; }; + 926B261B45D4C5FD5ED5733C313838F1 /* Moya-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 527FA930D9A852867C15A579A4F01D92 /* Moya-dummy.m */; }; + 938B46EF411204D0BEE0A56A7D584D51 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E4D3CDCE6607CA1788A973945B813DB /* RxCollectionViewDataSourcePrefetchingProxy.swift */; }; + 938E3D465A86F41C64F2E1774A2D14CA /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5571BC824BE85B8DEDD7C5FB972803F1 /* ScheduledDisposable.swift */; }; + 941822CDF68EB8F4D49F150457A82616 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F68B9B5FD094181660E4555CCE82A897 /* ResponseSerialization.swift */; }; + 944C78C2EABCD498AB74F5CCBB17D2AE /* Rectangle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20C21FA8C4DD01B44A00ACDCC06C137E /* Rectangle.swift */; }; + 945C6DC7FEF1B06D689E3FECB099F652 /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08DCD01DA45EC603BA3469CB31065493 /* CompositeDisposable.swift */; }; + 945DBBCB62542CD24B29F83FAFEF13B1 /* NSObject+Rx+KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12437FDC5507B09A5086FBF896237734 /* NSObject+Rx+KVORepresentable.swift */; }; + 95181366D610146E29AD34636DB9EFB7 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 207831A8AE3036D49F36C140A5487C63 /* Platform.Darwin.swift */; }; + 967C1562F78380A677F3539A185DCEDA /* AnimationTime.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB156F61588D89617814BA094C4E1C24 /* AnimationTime.swift */; }; + 968B4874A9F12D67C8B901136C9C8157 /* SnapKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A210044777925BBC8576B70CCA87AEB0 /* SnapKit-dummy.m */; }; + 96CFE0501DE851C5C7E1E23BEB5BE259 /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99430E20314FA52AE89A8E413268C90D /* SubscriptionDisposable.swift */; }; + 97584BC08D2B494417BDEE268CFF38C9 /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AD41A4730360AF228ACA97E7BCE4212 /* Combine.swift */; }; + 98241E64DA05272FA80194F03AF3199C /* RetryStrategy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 029298EC9C3BCB1FAAA6B0BF3F6B2A46 /* RetryStrategy.swift */; }; + 9850A80051F5259DF4BD9060DEFE783F /* BehaviorRelay+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3067BD7A13A4D8688FD0E78BBA46A35 /* BehaviorRelay+Driver.swift */; }; + 98A6AF2289B5C85BEFC492099F4AAB2C /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0B7F04DEBC34B16DE6AF03596E35556 /* Merge.swift */; }; + 98CAEDFDBFAC617AFDCA5452B790C283 /* SkeletonTreeNode+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C242DB41AE52F6AFD5C52D96966223A /* SkeletonTreeNode+Extensions.swift */; }; + 98CB55A8029728CCCE26047A5036E4CE /* AssociationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87735C0487D6CA4F171CF8DA7CD1278B /* AssociationPolicy.swift */; }; + 98F985B972592091D033FB84ADC7CAC1 /* Debounce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39D7CBE018675DF98D1EEFB4F7070327 /* Debounce.swift */; }; + 995F464575B20E78B0C124B9459E702E /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45FEFE36956CF674FB10839C7EC507D3 /* Producer.swift */; }; + 998C56F6835B30FF5071B39480B5C8F5 /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A6BDC77EAEBCA14DA677FCC3FE310A9 /* WithLatestFrom.swift */; }; + 9A12C0A11CC604DDD9ABD6C279E6CE9B /* SolidCompositionLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D54C98DE7CEBB2D8F1131C7B50E7FD04 /* SolidCompositionLayer.swift */; }; + 9B0C4E404F30F1AEAEE1FBE3A027FA5D /* Kingfisher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 5B294D750DF2AE93BF7C04FF7C1D8B7B /* Kingfisher-dummy.m */; }; + 9B692301E1D52EE349613955FA014E68 /* RecoverableViewState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25EAC37D7B8734F5F6B503F33A1C8349 /* RecoverableViewState.swift */; }; + 9B6D684A7CCF9470B92E10267E3987CA /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08ACDB5C9A8DBE46151E7C196E1A8991 /* DispatchQueue+Extensions.swift */; }; + 9C0BE8FA0030B2BC1DF7C159FA059389 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + 9CC401020A54F5F9E9C3D91D7B4AE77B /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5FAB1F918FD5B82BD0664038EE47057 /* RecursiveScheduler.swift */; }; + 9CC74656D849D327FB463AE05CDBCFBC /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 949BBB5ECE7B5436603B7FC04CF44AE3 /* DistinctUntilChanged.swift */; }; + 9CF94CAFCC98DE4F72B77E40AA760370 /* LottieView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B6946CBE7861917F027FE6008918B0C /* LottieView.swift */; }; + 9CFDA7C92E0EEA31F709663B0E727ABA /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3284940F014301795A4E512B8488B45C /* EventMonitor.swift */; }; + 9D18851445B1EFD750837CB21592295F /* SessionDataTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA353B32D4E255B5032D0EB172EC1338 /* SessionDataTask.swift */; }; + 9DB4A288E7875E7346EAB537875222D8 /* SharedSequence+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DF70B89B4E437BE1FEE3E1384564301 /* SharedSequence+Operators.swift */; }; + 9E7129BF4046FAF7D85245489EE29B5C /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 243F6A556BC9324243FAC2BEF43E5154 /* Response.swift */; }; + 9E9547A1D2F5A629C392D6EB55B2CE7C /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09693AC1A1B3A18F9FA52A7D51DD3971 /* Scan.swift */; }; + 9EDE0E2AC392A11A8048310C760DB0F3 /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D0751A1FB0F9C0431EFE99C2219FA91 /* Skip.swift */; }; + 9F20B18821E54566E6D16F393240B096 /* Star.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43DA4FB5DBD9F9E7FA2D72E5116CE1AD /* Star.swift */; }; + A0F754C88A64972A40A9008B0AD52109 /* ConstraintDirectionalInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21376495DF6F8B0050143D1E33B305A3 /* ConstraintDirectionalInsets.swift */; }; + A115142039C23F91827E6961CC479F05 /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D6D6B51E110B6440442F78F8CA9BADC9 /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A1194BE78FCE2929CDA65C95CA310EAF /* RxPickerViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37FDD05AFD5CE6C2AA7CC7C13A0686E9 /* RxPickerViewDataSourceProxy.swift */; }; + A1985C2CC5030AB984FFA33B94E1E39D /* ControlProperty+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89D812681CA39BEB09D4C419C19E684E /* ControlProperty+Driver.swift */; }; + A1B89609AB49417FB424FAF9B2310F72 /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66FBA686CFD090AA2B166227E4ECF81E /* DisposeBag.swift */; }; + A1CF368CE7252F8B8961C47586C178F2 /* GradientValueProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCB9B7980E4C45EF00EDD72D1DAA9B70 /* GradientValueProvider.swift */; }; + A2F7FF2AEFF21D78671543FA8CB6A8B3 /* NSObject+Rx+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FF3A9A33C900F71DA5EF5C29BE949A4 /* NSObject+Rx+RawRepresentable.swift */; }; + A3153333FC136836B0028E6AB2A56BEE /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A293AC4105C62BC723877D10AE638D4 /* AlamofireExtended.swift */; }; + A3423ADEDFB20D72E2C608221A26D3C6 /* UICollectionView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D36F1A384BC0E8912C9656D9E9FC32E1 /* UICollectionView+Rx.swift */; }; + A37D3661369446F3AA978C8FD342A83A /* UIActivityIndicatorView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0284DCEBF435B8B9683A5409873BEA7 /* UIActivityIndicatorView+Rx.swift */; }; + A3868E3FB80103D4EC40A361B74B92B4 /* Infallible+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5801960901D0BADB1E4BD40CA6C67C66 /* Infallible+Operators.swift */; }; + A392A4AB1CDBE4F4BF1E6451074E1EDE /* AsMaybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08EFB0508FB59B5A9CC9C10BFBB5D669 /* AsMaybe.swift */; }; + A3A65AC84DB2B13043BF9BB828C98F94 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + A3CE32243E84303A2D146EEE78044EB9 /* DispatchQueueConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10E0EBA8A23A9FD3551DCF70CE32FB5A /* DispatchQueueConfiguration.swift */; }; + A3CEE8324948497036C4E123B21CBC59 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 393CFBCF0BDEE619F1453EC0C3FE00F2 /* SwiftyJSON.swift */; }; + A3D8A9114B5767604A49DA50827F19E1 /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6994931C5C5549C924814ED0DECA00A0 /* Zip+arity.swift */; }; + A435E4B3FF0B326E880502C6FD3FC987 /* KVORepresentable+Swift.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA3E1896A379203483554C6A1C48253B /* KVORepresentable+Swift.swift */; }; + A4467357581E8345DD348683CC4111AF /* SnapKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = EF01F6EF733E1CA24A3DB61B34B8D1F4 /* SnapKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A4F1202CE5BBE79F3BBCAE3D2B16BC03 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B4EAA7FDBF8CFE95F3696938910D562 /* Result+Alamofire.swift */; }; + A515A3A3B2CF6958FAA17D86A579DDFB /* KeyframeGroup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19C735D18D612892EEDC5F487CB5ABA7 /* KeyframeGroup.swift */; }; + A53D3AF15CE8D348306EF11619C5D166 /* ConstraintMakerEditable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05BD8CE141801C12386DB9E517293094 /* ConstraintMakerEditable.swift */; }; + A550954F1A2F8855F1CBB0C518AE8C0E /* SkeletonGradient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7733913F39955FAD01EB941C89BD73FB /* SkeletonGradient.swift */; }; + A5AE75455F58AFA8091A87C1539A0E37 /* Repeater.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD54988AAEF3476D7CDFD2076F4F7D35 /* Repeater.swift */; }; + A612AD876F2009B32288E53A9C3EF222 /* SkeletonCollectionDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = E86E84B8E69882F455368E223F2A0927 /* SkeletonCollectionDataSource.swift */; }; + A664924D6CCE2922A3F81EC932F4D476 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0E8F0EF266C9F823732B3056F3ED8ED /* AFError.swift */; }; + A673B8FA85DAAA5F0E1E6C111479D0AE /* Plugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8741F7E10B36E8F94F04D711CAAEFFE9 /* Plugin.swift */; }; + A69EC4C58ACCC0039D025DD4E3BBAC58 /* Stroke.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E353EDBF4268085799BBFFF27229504 /* Stroke.swift */; }; + A748A04163F32EA3AF9B2E4516D78DDD /* RectNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFB0D21E5795488A0BB324C98CB416AD /* RectNode.swift */; }; + A7D4105D2351D2F90AB88CBFB147E170 /* UILabel+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3973EEB64C9D326DF952735E56A35608 /* UILabel+Extensions.swift */; }; + A892A3F92A4B151AD508CFCD080082A4 /* Then-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = CC950DA283FF7D67AD9F5BB2852CEC51 /* Then-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A960856B5EF2892D980158CCEC24A512 /* StarNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AB5A54E0682D80EBE2BBB6A2BCA2965 /* StarNode.swift */; }; + A9A47BC5110048309D88B3A183994EC5 /* FillI.swift in Sources */ = {isa = PBXBuildFile; fileRef = C47E28487EDD76C42BA8438285F90A17 /* FillI.swift */; }; + A9D6ED2A2795D2257153EDA170AEE556 /* CompatibleAnimationKeypath.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E471D37BD70D017261F532771D3652B /* CompatibleAnimationKeypath.swift */; }; + AA49099C1F3D0549158D3A9B2DD3D6E6 /* LayerFontProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = F91DBDE07A61124CA56D3DF66AC9DE34 /* LayerFontProvider.swift */; }; + AA5188D20EF55F511E77DC2BEF9E7F37 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + AA7BBD3390AF2ECAFA1AD576BB69CE15 /* RxScrollViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E0F121593C5A360AD45CB450EF3EF36 /* RxScrollViewDelegateProxy.swift */; }; + AAF660F2B3CE8E2BF423D0F97B20B16C /* ShareReplayScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBC804AD1464BA2566282D04FC227C34 /* ShareReplayScope.swift */; }; + AB4875CA5028C3C32274EC2CCDFE9066 /* NSSlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF0D1DC6BF577BEA4933CC9E9904D5E7 /* NSSlider+Rx.swift */; }; + AB7A0A676C7772470D72188B526C5160 /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F50F7590F13C2FEC54F3A2AF039F1DD /* GroupBy.swift */; }; + AB83BB2166917FF3675B1F3B8A08C919 /* ValueContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 045B675D9753FDDDB0BFE1C846868669 /* ValueContainer.swift */; }; + ABB41236912FC1C6E7330BB3568E917C /* Pods-sopt_29th_Assignment-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A351B9E7F7C039CD709E1333C4329FC3 /* Pods-sopt_29th_Assignment-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AC5EB10C38F324E227F38EBDC929F864 /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8E66D8E800FF87FB95483E022E5BFE3 /* OperationQueueScheduler.swift */; }; + AC9AE764EAB1C65078F0D3926C4C9FD9 /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = 060D5947DF2A206EBACAC4D9141BA5C2 /* Just.swift */; }; + ACA8DA6F28979DD495524BE7B918F18C /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = C63608A86051287DCC19717603B2BF81 /* Take.swift */; }; + AD1B944836523F2827AC7F43A79D0FEB /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8F0BE0C794A61C7EB4634CDF63FCEA4 /* Image.swift */; }; + ADC248F460EF445A0D5B67450A01839B /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3409FC3583B82BE7AE393910A5C75F5E /* DispatchQueue+Extensions.swift */; }; + ADDC43CFB0D46CACFE765C2A708F8D28 /* Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 778BBEE465580922EF19056B1FB95575 /* Delay.swift */; }; + ADF8DFE7C4E5E25FF75A84C3756577B2 /* ImageDrawing.swift in Sources */ = {isa = PBXBuildFile; fileRef = F55A505B6DD9C82DC3280E5B748463C9 /* ImageDrawing.swift */; }; + AE2FEB2F12262748259016973292183D /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A5C88CC7FE36F1A405C15CDFC255FCF /* Event.swift */; }; + AEFFE0F8CC99EAFD362E53DC63970243 /* InterpolatableExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 601A2832945FACAC50820FDBB3B05BCF /* InterpolatableExtensions.swift */; }; + AF62255D606B96D175C1896E131EA3AC /* SwitchIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A31C9A5DE11AFE106E3B36938178387 /* SwitchIfEmpty.swift */; }; + B06B474BA6F82DC1EBFF2B199724522E /* Ellipse.swift in Sources */ = {isa = PBXBuildFile; fileRef = C70255F45E310C14D25E974842ACE0C9 /* Ellipse.swift */; }; + B1BE54560B0DE6A294086544880A8D4C /* ImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD8F63AEB8F29A078DB6D1994472EA53 /* ImageCache.swift */; }; + B283E0B7BB5A5910188B1B4C7B15FF53 /* ObservableConvertibleType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 208E0A59F6812B839FEACDFDF42F6B01 /* ObservableConvertibleType+SharedSequence.swift */; }; + B2D2DF2EC4B3DD3FDC5A81B1BF0E5F66 /* NodePropertyMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = B744D0CCE9CE83FFF1F579AE0B296541 /* NodePropertyMap.swift */; }; + B305BB4271B22CAD1C31181780A36754 /* ImageProgressive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4648526110FA513D5C2B2E4598FE0416 /* ImageProgressive.swift */; }; + B543FD108C1C6AF6129CB4991553218B /* ConstraintConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12D7DDD5B9E3C6B66125EB05399AA92C /* ConstraintConfig.swift */; }; + B547F42465BDC15F134837E6B555F924 /* AnimationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 544395BC5A4545A205B84129662C3839 /* AnimationContext.swift */; }; + B5A92E0243CBB6CD7BABCAB2E2C4D256 /* Resource.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF5F0433C5B5A2FDCD09A81C569C081F /* Resource.swift */; }; + B6473B8E8353317F75D6800D4F7054CB /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E21A1D9ABB6E3BF10CF6276800D7EAF /* NetworkReachabilityManager.swift */; }; + B6C30F158F113B17E8D8156D78540A95 /* KeyedDecodingContainerExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 346EFDE086B13ABF6504CE67C670CE68 /* KeyedDecodingContainerExtensions.swift */; }; + B73DE72E42CF89C320EAC875E47D61BA /* TargetType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 474C1BE238A9FD53D68B97640CA2FE74 /* TargetType.swift */; }; + B7892F7510C7BAE53B1FB1504850740D /* DiskStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 513FD6E24419295D861763CE18D52C4D /* DiskStorage.swift */; }; + B87486D885CFEFFD0C365B4742BB013C /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFD786257ABB39B40D70F3165D42C01F /* Sequence.swift */; }; + B89D1C69742F61878115334A1D2DFFE7 /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEE5B6721BB2351DE21380FD23EFD7C6 /* URLRequest+Alamofire.swift */; }; + B8BB86CD7B7CB7E27FFF043629798EA8 /* ImageView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C8C603268BD296934CEC35FB0BC8923 /* ImageView+Kingfisher.swift */; }; + B8C99CF3DE63D713A71F79B20D42C7DD /* Materialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC5618864BECF00765464BFADD6D457E /* Materialize.swift */; }; + B8E27E8D24CBE6DB22F38E06FFBDB710 /* _RX.m in Sources */ = {isa = PBXBuildFile; fileRef = B958D6DAA7CC8E707A980E42F41B9E7B /* _RX.m */; }; + B95F86F591566A619E54D0CCAFBF9AF0 /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = B484FCBAC5748316D28EE3BB31442683 /* Using.swift */; }; + B9A197B0BAB8CA9F17A46D4440AC712E /* FillRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D220985C78D75C384CDF8B81DB6B3D91 /* FillRenderer.swift */; }; + BA1B763BE8CAE9799D6C650C0B07F7DA /* ImageDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = E86354E64FA98EDE3E66839D9D8C9689 /* ImageDownloader.swift */; }; + BA4DB50479A93EAD2BD1381CAB7D926E /* Decode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 808B587D23A5746A071DBE671C0B134F /* Decode.swift */; }; + BAABF3FC2F7E7E34A91A2D2274163E98 /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F6F84E9FDFB7A1AD3349F7E93194D7C /* RxMutableBox.swift */; }; + BACBE6C091D4012095FB22981B3C2616 /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13F92A11E3FCF33BA60FE05727A0BEDA /* AsyncLock.swift */; }; + BAE6F428F0027E5AC5115E2AF060E0E7 /* NetworkActivityPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A03336AD1E639C291FCB24745455335 /* NetworkActivityPlugin.swift */; }; + BB75BCF76F22254E3302085A5A6A4B48 /* SchedulerType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE492532FB512F9B783CFB73C24D696C /* SchedulerType+SharedSequence.swift */; }; + BBB7A1F02BE6A68A27F610816B89D62E /* NetworkLoggerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13CD233600EAFB966BBE0690A5CAD59C /* NetworkLoggerPlugin.swift */; }; + BC458D8EEF99A5C7FB5BBCC345FF5BB5 /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F69100E0147D6C4D38EDDD7A1E58A5E /* Disposable.swift */; }; + BC9A4262101924828199108EA8965486 /* LayerModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFF0769755F5BA666BB460EFCB21376E /* LayerModel.swift */; }; + BC9B08914E282476538AF6506ECE6A2E /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DDD5C32EEB0C67A01C78D27F8800267 /* InfiniteSequence.swift */; }; + BD333CDBCF5D2FD55920336FC271DF33 /* ConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39ED72107466232296E60B188AAD4A74 /* ConstraintItem.swift */; }; + BD6E20E0209D4B01ABF7642506F583F5 /* AnimatedButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 011A48617CAE79014E42ED17A15ABF48 /* AnimatedButton.swift */; }; + BDA7A156A12164C755BB71EF2118CB66 /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3FD5F1676F6BE15B29D02BACF63E175 /* Generate.swift */; }; + BDA9D77308041B5E3BE5AE89565B37F4 /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD891281D4AE67F534654AC87653323E /* SubjectType.swift */; }; + BEACA23AAFFCDF4B7D9F82C9A04FA345 /* KeyframeExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E98C006640C2FDCDAD55CA9CA1801605 /* KeyframeExtensions.swift */; }; + BEBF920FEB959B46A76BAADF22E5CD15 /* ConstraintInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E2F62EDA4ABF8D09B58CCF5D39C40B0 /* ConstraintInsetTarget.swift */; }; + BEC47341045E090EAA1817BC4E7B190D /* CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB6402E753D04F905BC4852F64AF7029 /* CombineLatest+Collection.swift */; }; + BEFE617EABAE8B434A580CCD4179C04E /* TextInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 876658971488280401D29AE699396A1C /* TextInput.swift */; }; + BFA1536E972A7E8266BD74C2771FBFAF /* AnyEncodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C1EF8E89F3F9C75C30DE4DFE7934AE9 /* AnyEncodable.swift */; }; + C051416713CFE621121265BD3553C9D2 /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EE72C751257B211AA10C4EBA38EA378 /* SynchronizedOnType.swift */; }; + C0A070E7EE584BEFC55190BB1B978697 /* SkeletonMultilineLayerBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 500EA97058AF35437C7881D78F36791E /* SkeletonMultilineLayerBuilder.swift */; }; + C109CE5E629F211619D0AA184E406122 /* UIView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DE7E81B55F89A333B743EB3C1FB84E4 /* UIView+Extensions.swift */; }; + C16A047C4E8D856309A486182A490993 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 681C7085B058D412CDBAE81D6CC3590F /* MultipartFormData.swift */; }; + C174156410407591E73348E291BAC330 /* Swizzling.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEC45818B7595FAE44DBD16AA13C3096 /* Swizzling.swift */; }; + C1C0E2AB487C2D515DAFD58B382293BB /* AsSingle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7520D72882C54D369DC3AB4761527968 /* AsSingle.swift */; }; + C1CF4AC823B7E034DB6CB5DB0EA08CA3 /* AnimationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 015CD2874ABEA0E08CA67E1EBB1F7404 /* AnimationView.swift */; }; + C2DB5CB595C2BE3D8C5E24758F8F1ACF /* CGFloatExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 328D4B3B5F0D35672A572ED5EC36DF34 /* CGFloatExtensions.swift */; }; + C3F495518D47871CA7BACD476A4D426A /* AnimationKeypathExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088A593EA49F6CD6A9EB9B1445C3A5AD /* AnimationKeypathExtension.swift */; }; + C403D56540C5E9371AD79B1C07976DE3 /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B13E7ED22E76C5EF80A1F86662E19D /* DelaySubscription.swift */; }; + C4D350D569A2B6567E087ED515A93EE2 /* RxTableViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16CECFC90862F1ADBFB95E1D0F77C3F3 /* RxTableViewDataSourceType.swift */; }; + C56A14C84CF05A1A96D8B92E16E0CBFB /* SectionedViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = D62EA072C6C22D3A5C278C866B397AD2 /* SectionedViewDataSourceType.swift */; }; + C5805A0100B5CA98C19A7D02813D01B8 /* SkeletonType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2975BFFB1283CF80FB0ECC05E969690 /* SkeletonType.swift */; }; + C5F4366AF47030DD66F19914E67B5FAB /* ReplayRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF430063AF43D273608BD10FF1719F05 /* ReplayRelay.swift */; }; + C61D3BC32A28A405C934C00039AD2583 /* ConstraintConstantTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CBA8D2D8781420D04B92B32FADC98A1 /* ConstraintConstantTarget.swift */; }; + C66C4E3E67C26B960FABBC8F1B0C056A /* RxTextViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE55C5E6AA523AFA73EC2D83A4E177D5 /* RxTextViewDelegateProxy.swift */; }; + C7F66519CE6148F21D7DB11423F1D34D /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0D608D68469ACC4C3385FD091BBF95D /* Response.swift */; }; + C8413231EA7E3A9AF268C845AA0FC32A /* ShapeTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93E79E4061F7310825626A571136E52C /* ShapeTransform.swift */; }; + C89FF9E911A1F953A96A9542C6AAAA1A /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4826213952103BBABC0B948C3A1540D7 /* ScheduledItem.swift */; }; + C92946ADA88B4CAD47524ACA731441BF /* AnimationContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67A269CCEF3E54285735630AE7BB7253 /* AnimationContainer.swift */; }; + CA21B1B110FD066CC661B98E85D96729 /* MemoryStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99D2BEA76FA15F487ADF926CB89CF093 /* MemoryStorage.swift */; }; + CB194156C900B767B0160AF72EDF354D /* ConstraintMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = D50E0E8195DD834A2F4829C5EAEBA725 /* ConstraintMaker.swift */; }; + CB8E4BF0D710970BE2CB4C87ED1043E4 /* ConstraintMakerRelatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17D3F5FECAC38602378868EA27A72126 /* ConstraintMakerRelatable.swift */; }; + CCA22C9F421C9E8C13009947816D8C82 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */; }; + CD8F79531679DC41E33E8FC3CB487EED /* RxRelay-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ADD9BE3E7CF0D7114194C3E5B4E20CF /* RxRelay-dummy.m */; }; + CEDCE669E51F7B8B8EBAF1583B8D4CD0 /* AnimationKeypath.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE7F07175183E202A0AA6844976B0496 /* AnimationKeypath.swift */; }; + CF28AE0CF7599B011DAD5E485E1D0DB2 /* GradientDirection.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5043540270E8CACE7C104E16E932D51 /* GradientDirection.swift */; }; + CF38C7EAE9C54B2000BE23D8549E6CDB /* AnimationImageProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA9B22BE2DA7ABC11AB8EF2A3D7C0BE0 /* AnimationImageProvider.swift */; }; + CF9DAAEC618DE435A7DF19579DE30AA2 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = D780C8593D2E40CC0D3C2A64F34E17E0 /* PriorityQueue.swift */; }; + D05116642C20C568B926B4025B6EF995 /* UISwitch+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1A71FD0103010BF1034EF966A3D7D4F /* UISwitch+Rx.swift */; }; + D0BA9ACEAB82794C851AE801199598C0 /* Notification+SkeletonFlow.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7D4209C642E4A22E0B375197F2EF315 /* Notification+SkeletonFlow.swift */; }; + D109B412294FE281603BF403C33C6EEB /* MoyaProvider+Internal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A9731354A24770FBC157F0AA7ACCE9A /* MoyaProvider+Internal.swift */; }; + D13D417B236E736EEAE7217B5CE3EC5C /* ConstraintMakerFinalizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8F067EB2F26B16397A4024118090762 /* ConstraintMakerFinalizable.swift */; }; + D13F75C1987BC40A12DA262771EB8178 /* ItemsExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ECFCAD5FD0C48632D983F15D90759CF /* ItemsExtension.swift */; }; + D14A5AB813E4DFF35A3B00A99BCA52A6 /* Dematerialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61AC97B1CC38C9AEF119A14A5E54D5E5 /* Dematerialize.swift */; }; + D15FEA31AA9625BBF041FB91E48A9995 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFBF22ADF874AFE81EF80D81FD0F1D03 /* Validation.swift */; }; + D17D6E8C80189277F66FF2EFD403BBE9 /* FilepathImageProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E2C669013911C6D4FB27F8CE2B6B058 /* FilepathImageProvider.swift */; }; + D1DE14077A54174F00E887101A48AE8A /* RxTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19D38A497544597217CC4F42869773F4 /* RxTarget.swift */; }; + D1FE79A7F36545B8CB44D97A93E74909 /* GradientFillNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41D5A48269E859CE9430419153128AB5 /* GradientFillNode.swift */; }; + D23BB4F9F4104BFA265E4E241C634BFD /* RenderNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B449B85DD9D71D971051E2AC440E59E /* RenderNode.swift */; }; + D26EB44DE97B01F75A7BD1238EECF902 /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8635C303D5A4896131561341C8493289 /* Deferred.swift */; }; + D276053C0849D80F7ADA470D657D14C1 /* GradientDirection+Animations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66DA767E2110B9DE41D6296EB97A51AC /* GradientDirection+Animations.swift */; }; + D27EDBD7FE5BC261F1B8BADD6AA9892B /* GradientFill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DA61552627F440050A87FAB1F0F46AB /* GradientFill.swift */; }; + D291B7FED40C98F386A898A6E1DB37DD /* Completable+AndThen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01D392B16678AA170E4995C96EB4EC87 /* Completable+AndThen.swift */; }; + D2A16148E1694719950E0A748086B3AF /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 003C339CFDEA10043C899DC5C6E3B963 /* TailRecursiveSink.swift */; }; + D2F4222D67ACD91E8139BBECFDFC381F /* Kingfisher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 91BC576A34535F04F3E41BB5F4A2BE19 /* Kingfisher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D49F135F9B911D7E1AE35870E8C7ADFA /* UICollectionView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94E98DD21F3A8AA85F9AA68B8CD5AF79 /* UICollectionView+Extensions.swift */; }; + D51F43300FBBF9F3642F4852BEB2D957 /* Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7251F730820CB2440AE47178A2E05925 /* Reactive.swift */; }; + D552C4D405D459DF6E986C8F1BAC6C3F /* Group.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E68D7FE551C4CDD777F3AAFE86821C1 /* Group.swift */; }; + D583F8FC3BFE7CE7368F5FE75679F388 /* RxTableViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D84A853B5EB7C03FF47C051BC1FAC9A /* RxTableViewDataSourceProxy.swift */; }; + D59C2826AD288ECFF576B2AFA312716C /* ConstraintRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F3974D8B2F35F6CEC4927FAD75F25DC /* ConstraintRelation.swift */; }; + D709A58FF6A694878122F7D24B4A9913 /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = E459B51C1885C4A8868D872E8BBD33CD /* Bag.swift */; }; + D74A1E17E125AFD63C56EB745F364878 /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 404BCF6A27A2F02EC5B5E6585FAC3202 /* SerialDispatchQueueScheduler.swift */; }; + D7CF7E80F7E4FB130EAC466BF410DD7E /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AA032F93E091953B93F1B96CC990C42 /* DispatchQueue+Extensions.swift */; }; + D84EC8CED594C059B08D47DEF08CF8E7 /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34A05C3B6C506CC2595668766B66335C /* CompactMap.swift */; }; + D8A4FE44301CF797B3E9655FA9F80FA6 /* _RXObjCRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D0D31D7FB33943C68B067F93D7639D2 /* _RXObjCRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D936EF159A167C7E4C5E5764C22F458F /* Then-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = BA073A17F7CF413B9B0A49B43CE73B77 /* Then-dummy.m */; }; + DA168E5E480E2F57B0BE8FD0A1FD64BD /* SizeValueProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3A5C82D7E3750C47DCC4D089790BBD9 /* SizeValueProvider.swift */; }; + DA47CB05965638DFE5B2A7062169534D /* KingfisherManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89BA5964A5E5D1A71F9E5858E4620E5A /* KingfisherManager.swift */; }; + DA65C3BA8B9C3048D8810BE53FEB6117 /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DB14BBD59D28FED37F0A07C663453D3 /* Throttle.swift */; }; + DB77444F78DE46BE31E894569DA13580 /* GroupInterpolator.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF9FEFFA9B7D920FE0827A598FAB6C8E /* GroupInterpolator.swift */; }; + DBF3771E8DE151A1D8A1692707B71501 /* SkeletonView-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 98F8064E2F318C1DDD89DC1186646E74 /* SkeletonView-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DC5E4DB7351FDA603E65BFED8D6178C3 /* SingleValueProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D49DD6592CAE4A4681462C888A5704F /* SingleValueProvider.swift */; }; + DCC85644FAA3FD3043D980859424A912 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5893E2F6BDE1656D9E2AED1E55AE57B /* InvocableScheduledItem.swift */; }; + DCD0C33A2B50811D53CF68F021284B47 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1691F065506461EF86886015CD5553E8 /* DispatchQueue+Alamofire.swift */; }; + DD58A00EACBEE274C381B491519C6B8C /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 071821BE495DDE9F3FADFDBCE93FA4F2 /* RedirectHandler.swift */; }; + DD724165EF3D8F209BD6EA6EEAA7EA0A /* RxSearchBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A849DE4AA3A30A8F9BA600C8F72D0C5 /* RxSearchBarDelegateProxy.swift */; }; + DDEF2B45CC47E733C9FCCD38F0BF6857 /* UIPickerView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB4DCE3C49F276788DC256A7CB221394 /* UIPickerView+Rx.swift */; }; + DE05924421F7CB823B4766BC14DBF066 /* Vectors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79BE205B7363AA5BD607C5AC7854113B /* Vectors.swift */; }; + DEB672EBC82C938FBA8595464B0761FF /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5519A274A3A23AC682FF2BCC079B33DB /* Optional.swift */; }; + DF20FA3D69BC752B01D65651AF876198 /* GradientStroke.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05BE1DF2E2240958B65FE14B975F3128 /* GradientStroke.swift */; }; + DFD30F96D602E6476B57BB16FF1785D2 /* SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77BCB87986D3BA89FAF5B76F32EF0E1F /* SharedSequence.swift */; }; + E0C65E16219718869CD2AFCA2C5465CB /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CB211AAE9491B71A132FC342B4CE0BD /* Request.swift */; }; + E1769C267E82B0C24FE0FFBF949F0A6E /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D3C1F9E5085E3C4B32CE68E6C6D5BF /* StringEncoding+Alamofire.swift */; }; + E1EF2C933B2B790C8D72E7914B36C8E8 /* AssetLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A7D4DA0A4088D7A5AA82C6475EFF6D5 /* AssetLibrary.swift */; }; + E32900C8E0BAEA6DED9E37EBC806809B /* CALayer+Animations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14E3019E082D1F606648001D96C0CAE7 /* CALayer+Animations.swift */; }; + E36244E8BF4AC941E82DAF16DDF4BBC2 /* ConstraintPriorityTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79100CD5FC439F8E474A63439EF9E8A6 /* ConstraintPriorityTarget.swift */; }; + E3C44D0364C9A3BDE105BC752FA90CBA /* ShapeContainerLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD6F904BE916FF77393166233CC2F108 /* ShapeContainerLayer.swift */; }; + E3CEBFA597BF0016EADDC35EF6C783BC /* ShapeItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD6C51736CC8C421D1FF2F68EFD04B85 /* ShapeItem.swift */; }; + E3EAE8A06C546BF367E779589458015D /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89C3D4B031C655927020FD3C14DDFCE3 /* HistoricalScheduler.swift */; }; + E41E3A6F3FAE1B76B9AB22687BC50CB5 /* ImageDataProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96E774AF77CBFC641B734B852F795BF0 /* ImageDataProvider.swift */; }; + E4A9C89EF8D2F5C2D78205B4BFA7623E /* TrimPathNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19BB2B091B613205ACE47BC3A9070BD8 /* TrimPathNode.swift */; }; + E4B2D5E0EF54A37DB3BCAE7328B5FD4F /* KingfisherOptionsInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09A5B581F7C28D047493EFE6DA37B80C /* KingfisherOptionsInfo.swift */; }; + E509D9386E5FD1690581CFA40DF43410 /* PreCompositionLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A49FCB95D8218F9C1184EE6009A97BD2 /* PreCompositionLayer.swift */; }; + E576A5317D9F3164C11702BAB11C464F /* SkeletonCollectionViewProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AB99139C81B8922DC500B24738C2EB9 /* SkeletonCollectionViewProtocols.swift */; }; + E5AB59421B29F44BCDE1F2A7D01A6801 /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93BF6B791D497D88399007FB4AD48570 /* ReplaySubject.swift */; }; + E6A1BF57511CE77AE62E000F61A5F48F /* _RXDelegateProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = CC949D9FB9157BF3A9C28C3CA361F44C /* _RXDelegateProxy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E824EBD8A2671CC76B497F4F5B65DB25 /* MoyaProvider+Defaults.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21AA5FE326683C0DBF2F60E8BF8FA2EF /* MoyaProvider+Defaults.swift */; }; + E82CCB58C2D28ECA230EF4E18C60FD1B /* Interpolatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17796C91B1AF123126FC9386C010BE4F /* Interpolatable.swift */; }; + E857ADCAD7B647883D5B2AEC3F16D1D5 /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CF303356DC7A4D17A311EE4B8598B16 /* URLSessionConfiguration+Alamofire.swift */; }; + E86216CD124BC804B02B0158BA303990 /* WKInterfaceImage+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55CD10ADFA2358EF18B237530DD80710 /* WKInterfaceImage+Kingfisher.swift */; }; + E8A1BCC9FD45BBCB48F8201286F65D82 /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC7535C78F2E9F180285E6E788E8B8DC /* Platform.Linux.swift */; }; + E8EAADACF3BAE33BDECBC7214EAE9CD2 /* ConstraintRelatableTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A531C42A7843B362B37D3DC18E18EC /* ConstraintRelatableTarget.swift */; }; + E969760912A8B3C7F8DA19AA0111000E /* FormatIndicatedCacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F3CFE254D1E97B15F75B7259F27814D /* FormatIndicatedCacheSerializer.swift */; }; + E9A6248F48B7EB642F3418875A5A9556 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 233C706C3317D2B175739DDCCCD493FA /* Observable.swift */; }; + E9BE1F32D0DA678D8593C665678862D3 /* AVAssetImageDataProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB80662DC88930A808766D75B58B8E0F /* AVAssetImageDataProvider.swift */; }; + E9C20CBEEA6B0F9C92E21B336DA24112 /* SkeletonView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2546C912AE8601CF7906404427FE332D /* SkeletonView.swift */; }; + EA0E379F526BD011CD5ED39FCB01E877 /* ColorExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E99ED7A5B57918151A962F031DA8B2D /* ColorExtension.swift */; }; + EA3850F7CA7A937EDAD766899110D730 /* LRUAnimationCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC6E46E41581F6F1F6C6898DD24FD7EB /* LRUAnimationCache.swift */; }; + EA40F22688E0DBF490B5160C3A347970 /* TextAnimatorNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7B7DCA28AC747E52ED2D5253ACE2EC1 /* TextAnimatorNode.swift */; }; + EA96920B163965469397F346A65043DF /* CallbackQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E6B622ADFB980BF374CBB86D3759C0F /* CallbackQueue.swift */; }; + EABAFC404B8375289AC500B725D8175B /* lottie-ios-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B220CFF8BD81422281651D25D997C0F8 /* lottie-ios-dummy.m */; }; + EB1DAE03A8C61696A29D130CA7BBD2DC /* UITextView+SKExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 093C38CAA4911B48486FD7BCD4563DDD /* UITextView+SKExtensions.swift */; }; + EB276B66D2562F17B084C0D83B9D8F27 /* UISearchBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1466CA4D101FAE23F9D08B8B63663EE /* UISearchBar+Rx.swift */; }; + EB7BC796352967DC142B4D17BB21AE0C /* BezierPath.swift in Sources */ = {isa = PBXBuildFile; fileRef = 367239DE49765930152EB321BB1AC71B /* BezierPath.swift */; }; + EBCA74E902BE99A736AEA573BEA5B6CD /* Infallible+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDE9FE7450171136DE2AC1641634C489 /* Infallible+Zip+arity.swift */; }; + EC11B17DA78F7EEBEBC3EFAF68C6DF9F /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = B77B9A720BE238A674C1DABB07F5CD46 /* Session.swift */; }; + EC741535DD70102DEE8FB9D57984AC0E /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD5BC5C7839120A1952E14BD41DC492A /* Observable+Bind.swift */; }; + EE253C86DD49455C9A9EDDFF5170FCDA /* MaskContainerLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32C3E6FFE6086B692332E200EB3E37FE /* MaskContainerLayer.swift */; }; + EE32D902912DDE67C15A0ABF1CE19B00 /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B6496DFF2CE2431D9089085DA8B38A8 /* SynchronizedDisposeType.swift */; }; + EE373836B715015237B9B2CC381A6D44 /* StrokeNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E89F63380C350E98B411CE7028B16D0 /* StrokeNode.swift */; }; + EE6C364198A763EBBF49237035D86439 /* ConstraintLayoutGuide.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC7A24FE2D50C8D81A33DAC6B009D5F6 /* ConstraintLayoutGuide.swift */; }; + EE80E1376D7F9E22682AE05EE3054388 /* UITabBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 338BFDEBE7A339FAFD9573A9926A4572 /* UITabBar+Rx.swift */; }; + EEAD705E4BB647E0BCEF532836557078 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FD05EBA82A3ECA1279623514C916302 /* Filter.swift */; }; + EF72D9648FAF9510F9F45DB54FD70918 /* First.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3D31D5552712947DD6DD4DD6D381390 /* First.swift */; }; + F059BB2BD4F7B156353739A55AEBE2A3 /* ObservableConvertibleType+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFC04AD25FB1DE14357C0CD2A244FCE1 /* ObservableConvertibleType+Driver.swift */; }; + F069E274658024F75333D4E423C4D050 /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48FAA3D40453DEB7997FAD69B09D646A /* BehaviorSubject.swift */; }; + F098338BE9A17E97B04340DAA5A0B660 /* ImagePrefetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 658B3E81297F503FE6CB67E23E559099 /* ImagePrefetcher.swift */; }; + F0AF301D8EF09CFE16C2145591BACE04 /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC38F5AE52B4EEB7D3604228631C5672 /* ImmediateSchedulerType.swift */; }; + F10586462FB54CEA169A1A7A469A926D /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20E5C057F14673FADC3619F20618F5B6 /* Debugging.swift */; }; + F1DA873728D70AB358E831F18AF284ED /* RxPickerViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 526ADF5A79C2CBC82F503FA0460D8C1A /* RxPickerViewDelegateProxy.swift */; }; + F219C2A0B49D73B93CEC939FEF1E7AB2 /* RxSearchControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDC82EB5069A011CA73BE1218B6698E9 /* RxSearchControllerDelegateProxy.swift */; }; + F24D06C23DAB2F52A30C886A7A8177C7 /* ConstraintView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67B9263F9767710808C7F9C6B017554E /* ConstraintView.swift */; }; + F2C47F7311D0B149A8FC0FF1B3838CB3 /* RxRelay-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 52794C382FB8922326B2F8777018068F /* RxRelay-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F2C817C166B2DE613222C41015A586C9 /* ConstraintMakerPriortizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB2079BBB30ED62D51431C9765C830CC /* ConstraintMakerPriortizable.swift */; }; + F2F6C65105BEF1168B87AF43B08DC062 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E30CE980C3C04353853E2AF1A39C145 /* SerialDisposable.swift */; }; + F2F8CDBFCE1889794E7A9F01B32AB9B5 /* Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97725CE91BDF719A6F66531F0753AE0A /* Infallible.swift */; }; + F30082074D26D27A95FE9F3D82EBCAA5 /* SkeletonDebug.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3A8E3C5F6FA0810BB8649881B922222 /* SkeletonDebug.swift */; }; + F343BA4E457FFDB0165492AECAEF0BCC /* ConstraintPriority.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD28CA8E650A4F97AFB97973D4630A2B /* ConstraintPriority.swift */; }; + F36D96A4346C90A2D11CB3B6A2ECF4CF /* AuthenticationInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = B41AEA65C66E7ACEA41AD1C1F3C68F20 /* AuthenticationInterceptor.swift */; }; + F387475B1EC3C098254F62698129B612 /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B15BB714A8520B79B914395B09633637 /* RxCocoaObjCRuntimeError+Extensions.swift */; }; + F3E9D2D841ED90799F0B52286BDAF937 /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E50D72CF25FF13AA891A3D3EB0801783 /* CurrentThreadScheduler.swift */; }; + F4EF5556C5D4CB38C03FC3322A768AB1 /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71D6937F919B2CBC07245D5F1D061843 /* StartWith.swift */; }; + F586BFBF4CCD51FE05A441FB76C9645D /* ImageLayerModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11F741538AE9A108ABB75A5F99AF1995 /* ImageLayerModel.swift */; }; + F5D2A31C7EB1DE010771140B6E7ABAD8 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C3816D0BD55363234509538304F2C98 /* URLEncodedFormEncoder.swift */; }; + F63BE0585331CAA3482EF736803F8243 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AF6124992AABDBAB9B673BD68F92F65 /* RequestInterceptor.swift */; }; + F6841C92A142C8F3680D83089B820CC4 /* ImageTransition.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE3DF2FB46BC58BC124C4CB365639907 /* ImageTransition.swift */; }; + F6919FE2F22301022F55ED6333F63FAA /* SizeExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798B36F771350D6304F48AA292794702 /* SizeExtensions.swift */; }; + F6E1B45243EF2546837B9099C53770E2 /* RxTableViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8966225B5C5536F8B019FCE27F737098 /* RxTableViewReactiveArrayDataSource.swift */; }; + F6F9C34492E47A611E31D2D63F476F13 /* ItemEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AFC9C1750CAEF5B9D510B41F4CE71AC /* ItemEvents.swift */; }; + F74B9496C841CAABC6F753FFDEAD7022 /* WithUnretained.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65DAAFBCF14E6735F9006742B5A0B053 /* WithUnretained.swift */; }; + F7A0AA8EA77891D0408D8CD9638D78A0 /* ListPlaceholder-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F48EE44D15434B52A20435C8D55CC02B /* ListPlaceholder-dummy.m */; }; + F84729EDCA858AF15F83257741352872 /* AtomicInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20CD4FEA06271824B989A8EDE3893D39 /* AtomicInt.swift */; }; + F89C351693522F78C6E85B6AAF7B76C4 /* RxCollectionViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C7C08ED1E8DC5B32FABE8E255A00EC6 /* RxCollectionViewDataSourceType.swift */; }; + F8D855D58CB3938A6A6781E73B53C411 /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0284223C1683F0B75775EB9666EAA694 /* ConcurrentDispatchQueueScheduler.swift */; }; + F8EA1161304015542DB2F9F4F5AE000F /* GroupNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = A48F8F6180E6DDC72D73DC1F0F803C76 /* GroupNode.swift */; }; + F9BC5623C245EAA0B9B811C9680C314F /* ShapeRenderLayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DF67815AB2355808DE38A66A22BF832 /* ShapeRenderLayer.swift */; }; + F9F9EEDDDE7B9C9DB5D0AE5A5F07BA21 /* GradientStrokeNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50C989774E4BEF7CC2CDCAA70573E81A /* GradientStrokeNode.swift */; }; + FA61B2655653E75EABEE2F65E3A55048 /* UICollectionView+CollectionSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15ABA7BBE4F022312F79CD0A4E4A0EA7 /* UICollectionView+CollectionSkeleton.swift */; }; + FAFB4D51449BA3500DED875A79120781 /* BehaviorRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3018780118D223690C258E639C92C46 /* BehaviorRelay.swift */; }; + FB5B8FF848673973A8AA577926781DF1 /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E19374B974D6A632F58ABEF0553D5B2F /* ConcurrentMainScheduler.swift */; }; + FC5FF4D5AE997DA8547B55E6DB0AF411 /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D7261008A0E169AEAF3B737D85A02AE /* SchedulerType.swift */; }; + FDB6B50F3AF189818D8962D74E37D552 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95E3F3825D907C4E21155D3E3E8F7DF0 /* RxTableViewDataSourcePrefetchingProxy.swift */; }; + FE9014A2371F738944ED0FDD3B2CFFB1 /* SkeletonMultilinesLayerConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BB56B503733457208BCD0A00863E25D /* SkeletonMultilinesLayerConfig.swift */; }; + FEDBAD32E2EDA85AD6E362B82892A74A /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4348EC0093037491BEA652EBE5DCA807 /* Alamofire.swift */; }; + FF753AA4B09998C58D092BAC010486F1 /* FillNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52B847EADB822730B47853A02A2E8F3B /* FillNode.swift */; }; + FFE93350F3FFCD907F5824BB097FCB52 /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD80162871DEA2C720EE5B7E21D17C19 /* AddRef.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 011CB0D0957212DB0175C9E6CF7B71B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 19622742EBA51E823D6DAE3F8CDBFAD4; + remoteInfo = SnapKit; + }; + 037FAA74DD47808B08A1C08B0EAF422B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + 1A642608849B947A198C41683C87B7FF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = E8022D22FAA6690B5E1C379C1BCE1491; + remoteInfo = Kingfisher; + }; + 3B0D29B425BC83DF1E83C2E073EBCD27 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = D118A6A04828FD3CDA8640CD2B6796D2; + remoteInfo = SwiftyJSON; + }; + 472834846DC97B551721422BFC9384A1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + 64AD9C22DCB9A294714602AC1A105581 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + 6D3BDF59251D134C6345E851B8FCB97B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8CEEFD1CB630CA790F0396E2E24A4C8C; + remoteInfo = SkeletonView; + }; + 6F772535556CB2FC9C6C1669AB0A4482 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 71E2315CBD1C572415F98045F62C3A87 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 77E57AFEA5397D1E7654B3A9604A0E5F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 833BD7AEDC7EA73809738EA6FF1E57A1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + 895A0CE95B38109B3072E60362355E34 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6; + remoteInfo = RxCocoa; + }; + AB0BAD6E58CC53A075ADF02F9047C8AB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 17F9141D333DA1A7BE5937F227221070; + remoteInfo = Moya; + }; + B4C22C549EE0010614ED89E0F8A93A10 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0B967D7F8561D42493EE289EC8D450D1; + remoteInfo = "lottie-ios"; + }; + B665499182DF664C7CA6F3BCF43A3EC5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 881D2AF3078426440580FAD64637BBE0; + remoteInfo = ListPlaceholder; + }; + D57F664D714513B525D72AECD7500DD6 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = C17AEFC79E770A2906EFAAB1A3757406; + remoteInfo = Then; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 003C339CFDEA10043C899DC5C6E3B963 /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + 00CA608937E7087A2803C3E379738798 /* Cancellable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancellable.swift; path = Sources/Moya/Cancellable.swift; sourceTree = ""; }; + 011A48617CAE79014E42ED17A15ABF48 /* AnimatedButton.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedButton.swift; path = "lottie-swift/src/Public/iOS/AnimatedButton.swift"; sourceTree = ""; }; + 015CD2874ABEA0E08CA67E1EBB1F7404 /* AnimationView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationView.swift; path = "lottie-swift/src/Public/Animation/AnimationView.swift"; sourceTree = ""; }; + 01D392B16678AA170E4995C96EB4EC87 /* Completable+AndThen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Completable+AndThen.swift"; path = "RxSwift/Traits/PrimitiveSequence/Completable+AndThen.swift"; sourceTree = ""; }; + 01E132FE01A0EF89DAC22F0090579748 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + 020972B007C5F08B995E8C1C1955D9A4 /* UILabel+IBInspectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILabel+IBInspectable.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+IBInspectable.swift"; sourceTree = ""; }; + 0284223C1683F0B75775EB9666EAA694 /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + 029298EC9C3BCB1FAAA6B0BF3F6B2A46 /* RetryStrategy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryStrategy.swift; path = Sources/Networking/RetryStrategy.swift; sourceTree = ""; }; + 02EFDE53819B941417FF687996AB3924 /* SkeletonView.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SkeletonView.release.xcconfig; sourceTree = ""; }; + 03E82BB2AAE6AB5C51DB74536D697019 /* 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 = ""; }; + 045B675D9753FDDDB0BFE1C846868669 /* ValueContainer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ValueContainer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueContainer.swift"; sourceTree = ""; }; + 056FD91F542A473CC393BE5FBB5B07F9 /* lottie-ios.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "lottie-ios.modulemap"; sourceTree = ""; }; + 05BD8CE141801C12386DB9E517293094 /* ConstraintMakerEditable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerEditable.swift; path = Source/ConstraintMakerEditable.swift; sourceTree = ""; }; + 05BE1DF2E2240958B65FE14B975F3128 /* GradientStroke.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientStroke.swift; path = "lottie-swift/src/Private/Model/ShapeItems/GradientStroke.swift"; sourceTree = ""; }; + 060D5947DF2A206EBACAC4D9141BA5C2 /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Just.swift; sourceTree = ""; }; + 0676D52867ED3A86854134835E52F0A0 /* PreCompLayerModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PreCompLayerModel.swift; path = "lottie-swift/src/Private/Model/Layers/PreCompLayerModel.swift"; sourceTree = ""; }; + 071821BE495DDE9F3FADFDBCE93FA4F2 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/RedirectHandler.swift; sourceTree = ""; }; + 07717BA267486AC9402D252D4961A068 /* GradientStrokeRenderer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientStrokeRenderer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientStrokeRenderer.swift"; sourceTree = ""; }; + 0782047E60E7337951DBC4FB782255D1 /* lottie-ios.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "lottie-ios.debug.xcconfig"; sourceTree = ""; }; + 0879FB18BD6A133DD98B8EF43021FF20 /* 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; }; + 088A593EA49F6CD6A9EB9B1445C3A5AD /* AnimationKeypathExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationKeypathExtension.swift; path = "lottie-swift/src/Private/Utility/Extensions/AnimationKeypathExtension.swift"; sourceTree = ""; }; + 08A274191F06572D07458949D5AD6657 /* CompatibleAnimationView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompatibleAnimationView.swift; path = "lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationView.swift"; sourceTree = ""; }; + 08ACDB5C9A8DBE46151E7C196E1A8991 /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 08DCD01DA45EC603BA3469CB31065493 /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + 08EFB0508FB59B5A9CC9C10BFBB5D669 /* AsMaybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsMaybe.swift; path = RxSwift/Observables/AsMaybe.swift; sourceTree = ""; }; + 08FBD5ED8C8FFF6DF290DCE8F8399024 /* ConstraintLayoutSupportDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupportDSL.swift; path = Source/ConstraintLayoutSupportDSL.swift; sourceTree = ""; }; + 093C38CAA4911B48486FD7BCD4563DDD /* UITextView+SKExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextView+SKExtensions.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+SKExtensions.swift"; sourceTree = ""; }; + 09693AC1A1B3A18F9FA52A7D51DD3971 /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Scan.swift; sourceTree = ""; }; + 09A5B581F7C28D047493EFE6DA37B80C /* KingfisherOptionsInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherOptionsInfo.swift; path = Sources/General/KingfisherOptionsInfo.swift; sourceTree = ""; }; + 0A293AC4105C62BC723877D10AE638D4 /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/AlamofireExtended.swift; sourceTree = ""; }; + 0A3E5441FDDA08B06D2C5D3C63A55FFF /* SnapKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SnapKit-Info.plist"; sourceTree = ""; }; + 0A9731354A24770FBC157F0AA7ACCE9A /* MoyaProvider+Internal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "MoyaProvider+Internal.swift"; path = "Sources/Moya/MoyaProvider+Internal.swift"; sourceTree = ""; }; + 0AB11D015902E3E50194C7855580589E /* AnimationFontProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationFontProvider.swift; path = "lottie-swift/src/Public/FontProvider/AnimationFontProvider.swift"; sourceTree = ""; }; + 0AB5A54E0682D80EBE2BBB6A2BCA2965 /* StarNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StarNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/StarNode.swift"; sourceTree = ""; }; + 0B449B85DD9D71D971051E2AC440E59E /* RenderNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RenderNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Protocols/RenderNode.swift"; sourceTree = ""; }; + 0B692AA196B6AFE8904EB2BCD1F07359 /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Concat.swift; sourceTree = ""; }; + 0BB56B503733457208BCD0A00863E25D /* SkeletonMultilinesLayerConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonMultilinesLayerConfig.swift; path = SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonMultilinesLayerConfig.swift; sourceTree = ""; }; + 0C8822E7100535F320D5E304F38D628F /* Pods-sopt_29th_Assignment.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-sopt_29th_Assignment.debug.xcconfig"; sourceTree = ""; }; + 0CC11B921788E101765C74857D6473EA /* EllipseNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EllipseNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/EllipseNode.swift"; sourceTree = ""; }; + 0E2C669013911C6D4FB27F8CE2B6B058 /* FilepathImageProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FilepathImageProvider.swift; path = "lottie-swift/src/Public/iOS/FilepathImageProvider.swift"; sourceTree = ""; }; + 0E89F63380C350E98B411CE7028B16D0 /* StrokeNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StrokeNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/StrokeNode.swift"; sourceTree = ""; }; + 0EFC2A7CCEE7FD68946B41699013C20C /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + 0FD6FB7BB4200891D8DB64A315EFC273 /* ObservableConvertibleType+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Signal.swift"; path = "RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift"; sourceTree = ""; }; + 104ED09FCA1D2D46F9F4ADCF6D2F06DC /* Pods-sopt_29th_Assignment.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-sopt_29th_Assignment.release.xcconfig"; sourceTree = ""; }; + 1079D87BD115E4351902A4B9A6A98EA3 /* SkeletonFlowHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonFlowHandler.swift; path = SkeletonViewCore/Sources/Internal/SkeletonFlowHandler.swift; sourceTree = ""; }; + 1090A2E25CADE447F0E441B7F86C09C4 /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Empty.swift; sourceTree = ""; }; + 10C11E72EAF8B195DDB1928BD42D7ABF /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/SingleAsync.swift; sourceTree = ""; }; + 10E0EBA8A23A9FD3551DCF70CE32FB5A /* DispatchQueueConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueConfiguration.swift; path = RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift; sourceTree = ""; }; + 11A089E572305D54324465FF35B215E3 /* LayerImageProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayerImageProvider.swift; path = "lottie-swift/src/Private/LayerContainers/Utility/LayerImageProvider.swift"; sourceTree = ""; }; + 11DE39107577F3D7973D85C19DC2DC4F /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Zip.swift; sourceTree = ""; }; + 11F741538AE9A108ABB75A5F99AF1995 /* ImageLayerModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageLayerModel.swift; path = "lottie-swift/src/Private/Model/Layers/ImageLayerModel.swift"; sourceTree = ""; }; + 12437FDC5507B09A5086FBF896237734 /* NSObject+Rx+KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+KVORepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift"; sourceTree = ""; }; + 12D7DDD5B9E3C6B66125EB05399AA92C /* ConstraintConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConfig.swift; path = Source/ConstraintConfig.swift; sourceTree = ""; }; + 13AE6E53A98B27F06918950C3CE6FAFB /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + 13CD233600EAFB966BBE0690A5CAD59C /* NetworkLoggerPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkLoggerPlugin.swift; path = Sources/Moya/Plugins/NetworkLoggerPlugin.swift; sourceTree = ""; }; + 13D91F6A2C0E62BC0F8D907BFDFC83EE /* URLRequest+Encoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Encoding.swift"; path = "Sources/Moya/URLRequest+Encoding.swift"; sourceTree = ""; }; + 13F92A11E3FCF33BA60FE05727A0BEDA /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + 1429C1A73E6127C81B743C89411AF246 /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Source/LayoutConstraint.swift; sourceTree = ""; }; + 14E3019E082D1F606648001D96C0CAE7 /* CALayer+Animations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CALayer+Animations.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/CALayer+Animations.swift"; sourceTree = ""; }; + 14F87B9368AD2DD04C9404B2B7C3D990 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 15ABA7BBE4F022312F79CD0A4E4A0EA7 /* UICollectionView+CollectionSkeleton.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+CollectionSkeleton.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UICollectionView+CollectionSkeleton.swift"; sourceTree = ""; }; + 1691F065506461EF86886015CD5553E8 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 16AFD5E477C7973D1144A718B6373568 /* _RX.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RX.h; path = RxCocoa/Runtime/include/_RX.h; sourceTree = ""; }; + 16B574E1489524A122ED5C62813A39BB /* Then-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Then-Info.plist"; sourceTree = ""; }; + 16CECFC90862F1ADBFB95E1D0F77C3F3 /* RxTableViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift; sourceTree = ""; }; + 171E4549F78434F865BCCEE30AF03C81 /* Kingfisher-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Kingfisher-Info.plist"; sourceTree = ""; }; + 17796C91B1AF123126FC9386C010BE4F /* Interpolatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Interpolatable.swift; path = "lottie-swift/src/Private/Utility/Interpolatable/Interpolatable.swift"; sourceTree = ""; }; + 17D3F5FECAC38602378868EA27A72126 /* ConstraintMakerRelatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerRelatable.swift; path = Source/ConstraintMakerRelatable.swift; sourceTree = ""; }; + 1833C016AFDFA598B3C7CE1DB8E431C5 /* Shape.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Shape.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Shape.swift"; sourceTree = ""; }; + 18E8574D9A7619ED4C44F466CEB9B55D /* ConstraintDescription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDescription.swift; path = Source/ConstraintDescription.swift; sourceTree = ""; }; + 192BBFC4C994D61C5F81913AA5E31305 /* RxSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxSwift-Info.plist"; sourceTree = ""; }; + 19BB2B091B613205ACE47BC3A9070BD8 /* TrimPathNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TrimPathNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/ModifierNodes/TrimPathNode.swift"; sourceTree = ""; }; + 19C712DA7B3CE570CB2D07BED0B93BB0 /* lottie-ios-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "lottie-ios-prefix.pch"; sourceTree = ""; }; + 19C735D18D612892EEDC5F487CB5ABA7 /* KeyframeGroup.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeyframeGroup.swift; path = "lottie-swift/src/Private/Model/Keyframes/KeyframeGroup.swift"; sourceTree = ""; }; + 19D38A497544597217CC4F42869773F4 /* RxTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTarget.swift; path = RxCocoa/Common/RxTarget.swift; sourceTree = ""; }; + 1A201CE6C47D308F8A0460BF3C410204 /* Transform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Transform.swift; path = "lottie-swift/src/Private/Model/Objects/Transform.swift"; sourceTree = ""; }; + 1A31C9A5DE11AFE106E3B36938178387 /* SwitchIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwitchIfEmpty.swift; path = RxSwift/Observables/SwitchIfEmpty.swift; sourceTree = ""; }; + 1A39BB18953213AFF2BE09075C24C3A2 /* ControlEvent+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Signal.swift"; path = "RxCocoa/Traits/Signal/ControlEvent+Signal.swift"; sourceTree = ""; }; + 1A435B7B2440EB29B92A6E97E5F426E4 /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + 1AEAC5C3F987A9644AD6C9C04B25B1A2 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + 1AFC9C1750CAEF5B9D510B41F4CE71AC /* ItemEvents.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ItemEvents.swift; path = RxCocoa/iOS/Events/ItemEvents.swift; sourceTree = ""; }; + 1B6FA3A0B046504259630EC69BE1968D /* Moya.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Moya.release.xcconfig; sourceTree = ""; }; + 1C1283162259A2F47FC79EB025ED886A /* SkeletonAnimationBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonAnimationBuilder.swift; path = SkeletonViewCore/Sources/API/AnimationBuilder/SkeletonAnimationBuilder.swift; sourceTree = ""; }; + 1C1AE02A6F340D553BE16E88C5986BE9 /* RxRelay-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxRelay-Info.plist"; sourceTree = ""; }; + 1C7BA86113D5C716B3A12925604B3936 /* Alamofire.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.debug.xcconfig; sourceTree = ""; }; + 1C861463227BAC0BB12CACF221FA5267 /* Alamofire.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.release.xcconfig; sourceTree = ""; }; + 1CF228A1EEF44F4A765F24BACC877FD9 /* SkeletonView.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SkeletonView.debug.xcconfig; sourceTree = ""; }; + 1D0751A1FB0F9C0431EFE99C2219FA91 /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Skip.swift; sourceTree = ""; }; + 1D8FD318337131921162F3040DA3E2DE /* UIView+AssociatedObjects.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+AssociatedObjects.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+AssociatedObjects.swift"; sourceTree = ""; }; + 1D92F82B9D0455965CA33B58CD326D06 /* UITextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextView+Rx.swift"; path = "RxCocoa/iOS/UITextView+Rx.swift"; sourceTree = ""; }; + 1DCE96AB9E9FA3053AC8B0DF7E2C066F /* UISlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISlider+Rx.swift"; path = "RxCocoa/iOS/UISlider+Rx.swift"; sourceTree = ""; }; + 1DDD5C32EEB0C67A01C78D27F8800267 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 1DDF1003EE8B21290AD02B9110DBCFAE /* RxCocoaRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoaRuntime.h; path = RxCocoa/Runtime/include/RxCocoaRuntime.h; sourceTree = ""; }; + 1DF70B89B4E437BE1FEE3E1384564301 /* SharedSequence+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Operators.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift"; sourceTree = ""; }; + 1E0771F18B5F0586F32DDA90BCC27E7A /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 1E2F62EDA4ABF8D09B58CCF5D39C40B0 /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Source/ConstraintInsetTarget.swift; sourceTree = ""; }; + 1E353EDBF4268085799BBFFF27229504 /* Stroke.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stroke.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Stroke.swift"; sourceTree = ""; }; + 1E5E8850920985F9BB50D6B6752F9093 /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; + 1EAF4EDBA81B4579F87F6B03975305E7 /* UINavigationController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UINavigationController+Rx.swift"; path = "RxCocoa/iOS/UINavigationController+Rx.swift"; sourceTree = ""; }; + 1FC173610BDE1E63571E4D11392019E3 /* CompositionLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositionLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/CompositionLayer.swift"; sourceTree = ""; }; + 1FD05EBA82A3ECA1279623514C916302 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Filter.swift; sourceTree = ""; }; + 207831A8AE3036D49F36C140A5487C63 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + 208E0A59F6812B839FEACDFDF42F6B01 /* ObservableConvertibleType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift"; sourceTree = ""; }; + 20C21FA8C4DD01B44A00ACDCC06C137E /* Rectangle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rectangle.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Rectangle.swift"; sourceTree = ""; }; + 20CD4FEA06271824B989A8EDE3893D39 /* AtomicInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AtomicInt.swift; path = Platform/AtomicInt.swift; sourceTree = ""; }; + 20E5C057F14673FADC3619F20618F5B6 /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Source/Debugging.swift; sourceTree = ""; }; + 21345028EFC317FB2DBC1A4C9ECA08FA /* AnimationPublic.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationPublic.swift; path = "lottie-swift/src/Public/Animation/AnimationPublic.swift"; sourceTree = ""; }; + 21376495DF6F8B0050143D1E33B305A3 /* ConstraintDirectionalInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsets.swift; path = Source/ConstraintDirectionalInsets.swift; sourceTree = ""; }; + 21AA5FE326683C0DBF2F60E8BF8FA2EF /* MoyaProvider+Defaults.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "MoyaProvider+Defaults.swift"; path = "Sources/Moya/MoyaProvider+Defaults.swift"; sourceTree = ""; }; + 220131E8E36EBD40284FAF5AF8CE03D8 /* SkeletonLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonLayer.swift; path = SkeletonViewCore/Sources/Internal/Models/SkeletonLayer.swift; sourceTree = ""; }; + 22C6807ACC5407C39AE3CFE3BEF30D50 /* AnyValueContainer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyValueContainer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyValueContainer.swift"; sourceTree = ""; }; + 233C706C3317D2B175739DDCCCD493FA /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + 23AA520C599D9905EA822AD7D599635F /* ExtensionHelpers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExtensionHelpers.swift; path = Sources/Utility/ExtensionHelpers.swift; sourceTree = ""; }; + 23AD8F2A2CD08E671C3FD51565E63057 /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/ToArray.swift; sourceTree = ""; }; + 243F6A556BC9324243FAC2BEF43E5154 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Sources/Moya/Response.swift; sourceTree = ""; }; + 2460FB307D49DA24619E67C6AC7D77D4 /* RxTabBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift; sourceTree = ""; }; + 246879F9E04EAD3592150755424A7EFC /* Protected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protected.swift; path = Source/Protected.swift; sourceTree = ""; }; + 2546C912AE8601CF7906404427FE332D /* SkeletonView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonView.swift; path = SkeletonViewCore/Sources/API/SkeletonView.swift; sourceTree = ""; }; + 25E58D99D7B2769C8099EB0C018414F4 /* Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Create.swift; path = RxSwift/Observables/Create.swift; sourceTree = ""; }; + 25EAC37D7B8734F5F6B503F33A1C8349 /* RecoverableViewState.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecoverableViewState.swift; path = SkeletonViewCore/Sources/Internal/Models/RecoverableViewState.swift; sourceTree = ""; }; + 25EEA2EDD084B84C71D534C5172BA41F /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + 2605E5A47D5C358C87DE3D160E420E4A /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + 26B8A4D3E4C2891D850DE42B3402AC27 /* UITextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextField+Rx.swift"; path = "RxCocoa/iOS/UITextField+Rx.swift"; sourceTree = ""; }; + 26F100ABE95688B8AFD9A91370832FC9 /* Pods-sopt_29th_Assignment-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-sopt_29th_Assignment-Info.plist"; sourceTree = ""; }; + 27F720B3CAA847C7E9C1D8382F05D5A6 /* TextLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextLayer.swift; path = "lottie-swift/src/Private/LayerContainers/Utility/TextLayer.swift"; sourceTree = ""; }; + 27F86901F0BC54C484DB217DFBB17E99 /* RxRelay.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.debug.xcconfig; sourceTree = ""; }; + 287C08308C6C979AD2AE20875F806582 /* PointValueProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PointValueProvider.swift; path = "lottie-swift/src/Public/DynamicProperties/ValueProviders/PointValueProvider.swift"; sourceTree = ""; }; + 28C41248617CC832243457A5AE5A72FD /* 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 = ""; }; + 299F2DCA91D09BC1CD72BF3DCF3D0637 /* ConstraintLayoutSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupport.swift; path = Source/ConstraintLayoutSupport.swift; sourceTree = ""; }; + 2A4FD77D127220741C07ECC1A4DB34FB /* UIRefreshControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIRefreshControl+Rx.swift"; path = "RxCocoa/iOS/UIRefreshControl+Rx.swift"; sourceTree = ""; }; + 2A6FDF9696B2561B33425CE9CFB52EDF /* Then.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Then.release.xcconfig; sourceTree = ""; }; + 2AF6124992AABDBAB9B673BD68F92F65 /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/RequestInterceptor.swift; sourceTree = ""; }; + 2C0CA2D40385C76935B1D18156E588E2 /* Kingfisher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-prefix.pch"; sourceTree = ""; }; + 2C1EF8E89F3F9C75C30DE4DFE7934AE9 /* AnyEncodable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyEncodable.swift; path = Sources/Moya/AnyEncodable.swift; sourceTree = ""; }; + 2D2CE551669C63D2247F730227904BC1 /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/CombineLatest.swift; sourceTree = ""; }; + 2D30BF91E8A5992C22B85D971C167223 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Sources/Moya/MultipartFormData.swift; sourceTree = ""; }; + 2D758A0D185CC311BCFAF0FF0CD32C44 /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Sink.swift; sourceTree = ""; }; + 2D873E925CE42958A7B41F3F37920F0D /* ShapeLayerModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShapeLayerModel.swift; path = "lottie-swift/src/Private/Model/Layers/ShapeLayerModel.swift"; sourceTree = ""; }; + 2D9607F168FFEFCF17906EDB2A22DFF3 /* UIView+SKExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+SKExtensions.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/UIView+SKExtensions.swift"; sourceTree = ""; }; + 2DB14BBD59D28FED37F0A07C663453D3 /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Throttle.swift; sourceTree = ""; }; + 2E360D14592776CF6F8A12605C00C389 /* Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Signal.swift; path = RxCocoa/Traits/Signal/Signal.swift; sourceTree = ""; }; + 2E471D37BD70D017261F532771D3652B /* CompatibleAnimationKeypath.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompatibleAnimationKeypath.swift; path = "lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationKeypath.swift"; sourceTree = ""; }; + 2EB64A1923FE3E6791208197EF53CD8A /* SwiftyJSON-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SwiftyJSON-Info.plist"; sourceTree = ""; }; + 2F3974D8B2F35F6CEC4927FAD75F25DC /* ConstraintRelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelation.swift; path = Source/ConstraintRelation.swift; sourceTree = ""; }; + 2F50F7590F13C2FEC54F3A2AF039F1DD /* GroupBy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupBy.swift; path = RxSwift/Observables/GroupBy.swift; sourceTree = ""; }; + 2F6F84E9FDFB7A1AD3349F7E93194D7C /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + 2FBFC9C2376164147EDEEB37CE43CF48 /* SolidLayerModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SolidLayerModel.swift; path = "lottie-swift/src/Private/Model/Layers/SolidLayerModel.swift"; sourceTree = ""; }; + 301AFE63C3AB09BD6D7E866765FB708D /* _RXKVOObserver.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXKVOObserver.h; path = RxCocoa/Runtime/include/_RXKVOObserver.h; sourceTree = ""; }; + 31FD46ECE4E238AEABFE3EA76B9F6F66 /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/TakeLast.swift; sourceTree = ""; }; + 3284940F014301795A4E512B8488B45C /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/EventMonitor.swift; sourceTree = ""; }; + 328D4B3B5F0D35672A572ED5EC36DF34 /* CGFloatExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CGFloatExtensions.swift; path = "lottie-swift/src/Private/Utility/Extensions/CGFloatExtensions.swift"; sourceTree = ""; }; + 32C25D90E00FED9797258D70F1F617DE /* PublishRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishRelay.swift; path = RxRelay/PublishRelay.swift; sourceTree = ""; }; + 32C3E6FFE6086B692332E200EB3E37FE /* MaskContainerLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MaskContainerLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/MaskContainerLayer.swift"; sourceTree = ""; }; + 33520700E00C9FBBBB89B24FBA4EDA44 /* LayerTransformNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayerTransformNode.swift; path = "lottie-swift/src/Private/LayerContainers/Utility/LayerTransformNode.swift"; sourceTree = ""; }; + 338BFDEBE7A339FAFD9573A9926A4572 /* UITabBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBar+Rx.swift"; path = "RxCocoa/iOS/UITabBar+Rx.swift"; sourceTree = ""; }; + 33C0F1AB46159D64DFA4C8B2970C0905 /* SkeletonView-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SkeletonView-prefix.pch"; sourceTree = ""; }; + 3409FC3583B82BE7AE393910A5C75F5E /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 346EFDE086B13ABF6504CE67C670CE68 /* KeyedDecodingContainerExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeyedDecodingContainerExtensions.swift; path = "lottie-swift/src/Private/Model/Extensions/KeyedDecodingContainerExtensions.swift"; sourceTree = ""; }; + 3485652A97F1EAFC84E390F4CDAF13B3 /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + 349681955FF4E7F5E8E163E05F167288 /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + 34A05C3B6C506CC2595668766B66335C /* CompactMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompactMap.swift; path = RxSwift/Observables/CompactMap.swift; sourceTree = ""; }; + 34C2783C40155C5656AD80D6A1501FCB /* SnapKit.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.release.xcconfig; sourceTree = ""; }; + 353F2BD4A9347C8D3533715105EC244C /* Disposables.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposables.swift; path = RxSwift/Disposables/Disposables.swift; sourceTree = ""; }; + 35497D877BD0C0976B31A79849E5852B /* Deprecated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecated.swift; path = SkeletonViewCore/Sources/API/Deprecated.swift; sourceTree = ""; }; + 354FB31B9128687D8F619B708088196A /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/HTTPHeaders.swift; sourceTree = ""; }; + 3593A9C676C986ADEC9A0D44D5E2E0F5 /* Then.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Then.debug.xcconfig; sourceTree = ""; }; + 36162C76DB6AF3C2B51AF1A95E380696 /* NodeProperty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NodeProperty.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/NodeProperty.swift"; sourceTree = ""; }; + 367239DE49765930152EB321BB1AC71B /* BezierPath.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BezierPath.swift; path = "lottie-swift/src/Private/Utility/Primitives/BezierPath.swift"; sourceTree = ""; }; + 36AB4A0D570C8199050F230FC5DD3C34 /* NullCompositionLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NullCompositionLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/NullCompositionLayer.swift"; sourceTree = ""; }; + 3756A9BBE41ABEE8DCBF5BCA6972C4DA /* Moya */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Moya; path = Moya.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 375F61A82A5F40C5FD6C91FCCA9DACE9 /* UIColor+Skeleton.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIColor+Skeleton.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIColor+Skeleton.swift"; sourceTree = ""; }; + 378854640F1106F95BAEBEB96DFE30C3 /* Kingfisher.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.debug.xcconfig; sourceTree = ""; }; + 37E494D03710E8D813D8044D134F16C7 /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Timer.swift; sourceTree = ""; }; + 37FDD05AFD5CE6C2AA7CC7C13A0686E9 /* RxPickerViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift; sourceTree = ""; }; + 391AC99DE47C2D48F06B251895B9C015 /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/ObserveOn.swift; sourceTree = ""; }; + 393CFBCF0BDEE619F1453EC0C3FE00F2 /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON/SwiftyJSON.swift; sourceTree = ""; }; + 3973EEB64C9D326DF952735E56A35608 /* UILabel+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILabel+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UILabel+Extensions.swift"; sourceTree = ""; }; + 39D7CBE018675DF98D1EEFB4F7070327 /* Debounce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debounce.swift; path = RxSwift/Observables/Debounce.swift; sourceTree = ""; }; + 39ED72107466232296E60B188AAD4A74 /* ConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintItem.swift; path = Source/ConstraintItem.swift; sourceTree = ""; }; + 3B4EAA7FDBF8CFE95F3696938910D562 /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Result+Alamofire.swift"; sourceTree = ""; }; + 3B9B5E120B5F7D089128B46F55F1BCAB /* LayerDebugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayerDebugging.swift; path = "lottie-swift/src/Private/Utility/Debugging/LayerDebugging.swift"; sourceTree = ""; }; + 3BBB970F55539B321B0665BC7C850687 /* Moya-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Moya-prefix.pch"; sourceTree = ""; }; + 3BEEE5E708E847867300037A0C0D8F16 /* AuthenticationChallengeResponsable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationChallengeResponsable.swift; path = Sources/Networking/AuthenticationChallengeResponsable.swift; sourceTree = ""; }; + 3C2A0E95B0BA6D0627206971E21E650C /* ConstraintInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsets.swift; path = Source/ConstraintInsets.swift; sourceTree = ""; }; + 3C7C08ED1E8DC5B32FABE8E255A00EC6 /* RxCollectionViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift; sourceTree = ""; }; + 3CA7DDF91B9AB1CDDBF143E802DACD59 /* UITableView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITableView+Rx.swift"; path = "RxCocoa/iOS/UITableView+Rx.swift"; sourceTree = ""; }; + 3CB211AAE9491B71A132FC342B4CE0BD /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 3D84A853B5EB7C03FF47C051BC1FAC9A /* RxTableViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift; sourceTree = ""; }; + 3D9F3C8963492DF9D8C22D7704478402 /* ListPlaceholder */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = ListPlaceholder; path = ListPlaceholder.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 3ECFCAD5FD0C48632D983F15D90759CF /* ItemsExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ItemsExtension.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Extensions/ItemsExtension.swift"; sourceTree = ""; }; + 3F4EEAAD35116C85CB0C374EFE4E28DA /* RxCocoa.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoa.h; path = RxCocoa/RxCocoa.h; sourceTree = ""; }; + 404BCF6A27A2F02EC5B5E6585FAC3202 /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + 40833CDFE3A86FC1485A6A8F67ABD5E6 /* Delegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delegate.swift; path = Sources/Utility/Delegate.swift; sourceTree = ""; }; + 40D34EBDA2B1EA531EE140BE3FA0AAD9 /* 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; }; + 40FD9C80907D086CB5E915BB58C9CFFD /* String+MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+MD5.swift"; path = "Sources/Utility/String+MD5.swift"; sourceTree = ""; }; + 4153857072584D894C8031B00E5FE798 /* SkeletonReusableCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonReusableCell.swift; path = SkeletonViewCore/Sources/Internal/Collections/SkeletonReusableCell.swift; sourceTree = ""; }; + 41D5A48269E859CE9430419153128AB5 /* GradientFillNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientFillNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientFillNode.swift"; sourceTree = ""; }; + 4264469B6581B43C3A3379E6C8927360 /* NSButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSButton+Kingfisher.swift"; path = "Sources/Extensions/NSButton+Kingfisher.swift"; sourceTree = ""; }; + 42C2D48C54A7871FC049E1A1E12314BB /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + 4304FC34470876F5AE58F762218D8E27 /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + 433B80DE9E0F4B1F42A3E818AE8B40DC /* AnimatedImageView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedImageView.swift; path = Sources/Views/AnimatedImageView.swift; sourceTree = ""; }; + 4348EC0093037491BEA652EBE5DCA807 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 4366C669579E73C3ADCF0EFABC667C90 /* RxCocoa-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxCocoa-dummy.m"; sourceTree = ""; }; + 4379622FBB2CEFDC5335AB006D956909 /* SwiftyJSON.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.debug.xcconfig; sourceTree = ""; }; + 438454217A3C55CD48E9CBD2755D3F22 /* CacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CacheSerializer.swift; path = Sources/Cache/CacheSerializer.swift; sourceTree = ""; }; + 4392138897B7F1D2D744E42BD42A8666 /* RxRelay.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.release.xcconfig; sourceTree = ""; }; + 43CFF9BDD3A181526EF302B0229AAECC /* PrecompAsset.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrecompAsset.swift; path = "lottie-swift/src/Private/Model/Assets/PrecompAsset.swift"; sourceTree = ""; }; + 43DA4FB5DBD9F9E7FA2D72E5116CE1AD /* Star.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Star.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Star.swift"; sourceTree = ""; }; + 43E3AA26E37DAE4D93A957A8160603F5 /* RxRelay.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxRelay.modulemap; sourceTree = ""; }; + 443E4EF8CB08E7C6C16C8F9A2F7019C7 /* RxCocoa-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-prefix.pch"; sourceTree = ""; }; + 444F5668DB1CCE1EEE4C56A44681A9A1 /* PathOutputNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PathOutputNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PathOutputNode.swift"; sourceTree = ""; }; + 446E3EB3F699A644D3549F0D2657CB69 /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/RetryPolicy.swift; sourceTree = ""; }; + 44B994A40E780755A43AB36546BE247B /* ConstraintViewDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintViewDSL.swift; path = Source/ConstraintViewDSL.swift; sourceTree = ""; }; + 44F6BDD6C63042363FABEB4018BD511F /* _RXObjCRuntime.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXObjCRuntime.m; path = RxCocoa/Runtime/_RXObjCRuntime.m; sourceTree = ""; }; + 44FEACAACB5FD6154FE9B04A8A54FEE1 /* MoyaProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MoyaProvider.swift; path = Sources/Moya/MoyaProvider.swift; sourceTree = ""; }; + 456259D8BA3A3A1A953B73B998EC12B9 /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/ParameterEncoder.swift; sourceTree = ""; }; + 45A00219A0362BFAB2AF1BE55BFACA9F /* SkeletonExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonExtended.swift; path = SkeletonViewCore/Sources/API/SkeletonExtended.swift; sourceTree = ""; }; + 45FEFE36956CF674FB10839C7EC507D3 /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Producer.swift; sourceTree = ""; }; + 4648526110FA513D5C2B2E4598FE0416 /* ImageProgressive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProgressive.swift; path = Sources/Image/ImageProgressive.swift; sourceTree = ""; }; + 4701D61B9E8B58C7B8DE650388D62501 /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/HTTPMethod.swift; sourceTree = ""; }; + 474C1BE238A9FD53D68B97640CA2FE74 /* TargetType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TargetType.swift; path = Sources/Moya/TargetType.swift; sourceTree = ""; }; + 4764E8A7D0A60A2B1959E62D5EE630A8 /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/SkipWhile.swift; sourceTree = ""; }; + 4826213952103BBABC0B948C3A1540D7 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + 4828B93FADCCFD4794B2484CAACCC552 /* NSObject+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx.swift"; path = "RxCocoa/Foundation/NSObject+Rx.swift"; sourceTree = ""; }; + 482DA72C97FEBA660F16267D96D5E285 /* ListPlaceholder.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = ListPlaceholder.release.xcconfig; sourceTree = ""; }; + 48C7604CA62FB6215DFBB6A7C45EDB5F /* ControlTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlTarget.swift; path = RxCocoa/Common/ControlTarget.swift; sourceTree = ""; }; + 48FAA3D40453DEB7997FAD69B09D646A /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + 49B32A5355B9E0D5930A79C4C83652C2 /* AnimationCacheProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationCacheProvider.swift; path = "lottie-swift/src/Public/AnimationCache/AnimationCacheProvider.swift"; sourceTree = ""; }; + 49E03A057A79F330524962695F9FFA94 /* lottie-ios-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "lottie-ios-Info.plist"; sourceTree = ""; }; + 4A03336AD1E639C291FCB24745455335 /* NetworkActivityPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkActivityPlugin.swift; path = Sources/Moya/Plugins/NetworkActivityPlugin.swift; sourceTree = ""; }; + 4A8C9E61C5B107DF52BFA41FF3621A6B /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + 4AA032F93E091953B93F1B96CC990C42 /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/FoundationExtensions/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 4AB99139C81B8922DC500B24738C2EB9 /* SkeletonCollectionViewProtocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonCollectionViewProtocols.swift; path = SkeletonViewCore/Sources/API/Collections/CollectionViews/SkeletonCollectionViewProtocols.swift; sourceTree = ""; }; + 4C4579507D0921EBF1E697F281041418 /* ControlProperty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlProperty.swift; path = RxCocoa/Traits/ControlProperty.swift; sourceTree = ""; }; + 4CD09121D5921CA90BF4362D690AF12A /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Amb.swift; sourceTree = ""; }; + 4D13749C1361D3E0309897785A6F01FE /* UITableView+CollectionSkeleton.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITableView+CollectionSkeleton.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+CollectionSkeleton.swift"; sourceTree = ""; }; + 4D7261008A0E169AEAF3B737D85A02AE /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + 4DDF961CC34E9D9CEC76F2A52AEA6708 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Map.swift; sourceTree = ""; }; + 4DF448AB4ED97D9C8A49D8B950451DEF /* PathElement.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PathElement.swift; path = "lottie-swift/src/Private/Utility/Primitives/PathElement.swift"; sourceTree = ""; }; + 4EA480CD3DBE3432276B6BC5B8469E3E /* SkeletonTreeNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonTreeNode.swift; path = SkeletonViewCore/Sources/Internal/SkeletonTree/SkeletonTreeNode.swift; sourceTree = ""; }; + 4ED733DB06AC8A291976B4A6AEED7AE0 /* Runtime.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Runtime.swift; path = Sources/Utility/Runtime.swift; sourceTree = ""; }; + 4F126DE82378F3C5075DC5D1E4F2C04B /* ConstraintMultiplierTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMultiplierTarget.swift; path = Source/ConstraintMultiplierTarget.swift; sourceTree = ""; }; + 500EA97058AF35437C7881D78F36791E /* SkeletonMultilineLayerBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonMultilineLayerBuilder.swift; path = SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonMultilineLayerBuilder.swift; sourceTree = ""; }; + 504F6A77D82470D4C99C670B2C9F0049 /* Completable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Completable.swift; path = RxSwift/Traits/PrimitiveSequence/Completable.swift; sourceTree = ""; }; + 50535740A752839EFCC7E5D87EEDC917 /* lottie-ios-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "lottie-ios-umbrella.h"; sourceTree = ""; }; + 506581462DCF2AD73F7FFB993DE007D8 /* NSTextAttachment+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextAttachment+Kingfisher.swift"; path = "Sources/Extensions/NSTextAttachment+Kingfisher.swift"; sourceTree = ""; }; + 50C989774E4BEF7CC2CDCAA70573E81A /* GradientStrokeNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientStrokeNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientStrokeNode.swift"; sourceTree = ""; }; + 51057370900323FCEB104A0AFA33850C /* UIView+Transitions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Transitions.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Transitions.swift"; sourceTree = ""; }; + 513FD6E24419295D861763CE18D52C4D /* DiskStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DiskStorage.swift; path = Sources/Cache/DiskStorage.swift; sourceTree = ""; }; + 514A2A555C799CAE4A62B986735C1A78 /* RxWKNavigationDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxWKNavigationDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift; sourceTree = ""; }; + 514C29EF868B36167A28F263FB084B02 /* RxRelay-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-prefix.pch"; sourceTree = ""; }; + 51AFF4C368AA3CBD436E0DC6CC0942AC /* RxNavigationControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxNavigationControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift; sourceTree = ""; }; + 51BA97E8B5085EFFB47BC9C0B785CEA7 /* lottie-ios */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "lottie-ios"; path = Lottie.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 51BCE2958D21169BE85CC73B5D398D2C /* Infallible+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Bind.swift"; path = "RxCocoa/Common/Infallible+Bind.swift"; sourceTree = ""; }; + 51C9D42FAF78B6A8609A0BB2C9215532 /* ImageProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProcessor.swift; path = Sources/Image/ImageProcessor.swift; sourceTree = ""; }; + 526ADF5A79C2CBC82F503FA0460D8C1A /* RxPickerViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift; sourceTree = ""; }; + 52794C382FB8922326B2F8777018068F /* RxRelay-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-umbrella.h"; sourceTree = ""; }; + 527FA930D9A852867C15A579A4F01D92 /* Moya-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Moya-dummy.m"; sourceTree = ""; }; + 52B847EADB822730B47853A02A2E8F3B /* FillNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FillNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/FillNode.swift"; sourceTree = ""; }; + 53827C32DF6393C2BD736C97B9831F75 /* ImageDownloaderDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloaderDelegate.swift; path = Sources/Networking/ImageDownloaderDelegate.swift; sourceTree = ""; }; + 544395BC5A4545A205B84129662C3839 /* AnimationContext.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationContext.swift; path = "lottie-swift/src/Private/Utility/Helpers/AnimationContext.swift"; sourceTree = ""; }; + 5519A274A3A23AC682FF2BCC079B33DB /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RxSwift/Observables/Optional.swift; sourceTree = ""; }; + 552D72B0197B86C4795FDBC92B632740 /* Driver+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Driver+Subscription.swift"; path = "RxCocoa/Traits/Driver/Driver+Subscription.swift"; sourceTree = ""; }; + 5571BC824BE85B8DEDD7C5FB972803F1 /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + 557A68D20A14109ADEC30EE3A1D38C45 /* PublishRelay+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PublishRelay+Signal.swift"; path = "RxCocoa/Traits/Signal/PublishRelay+Signal.swift"; sourceTree = ""; }; + 55CD10ADFA2358EF18B237530DD80710 /* WKInterfaceImage+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "WKInterfaceImage+Kingfisher.swift"; path = "Sources/Extensions/WKInterfaceImage+Kingfisher.swift"; sourceTree = ""; }; + 56944244C79D6B7A8CD6B1AA50E54632 /* RequestModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestModifier.swift; path = Sources/Networking/RequestModifier.swift; sourceTree = ""; }; + 56A3C9241FB780123BA22D4870B8781F /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SwiftyJSON.modulemap; sourceTree = ""; }; + 5801960901D0BADB1E4BD40CA6C67C66 /* Infallible+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Operators.swift"; path = "RxSwift/Traits/Infallible/Infallible+Operators.swift"; sourceTree = ""; }; + 5874F841747FFE1D064649C299B37A77 /* ListLoader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ListLoader.swift; path = ListPlaceholder/Classes/ListLoader.swift; sourceTree = ""; }; + 59479749C35D07AD73D552FEF1A3F790 /* DelegateProxyType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxyType.swift; path = RxCocoa/Common/DelegateProxyType.swift; sourceTree = ""; }; + 5988D1FB2FF114A5F12FAEA50CC10BE2 /* ConstraintLayoutGuide+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintLayoutGuide+Extensions.swift"; path = "Source/ConstraintLayoutGuide+Extensions.swift"; sourceTree = ""; }; + 5A6C58F1D4435C0AB86B565F53116FCA /* ListPlaceholder.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = ListPlaceholder.debug.xcconfig; sourceTree = ""; }; + 5A849DE4AA3A30A8F9BA600C8F72D0C5 /* RxSearchBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift; sourceTree = ""; }; + 5AED798F345A7AB54BF82C5FD690CEEC /* Bag+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bag+Rx.swift"; path = "RxSwift/Extensions/Bag+Rx.swift"; sourceTree = ""; }; + 5B294D750DF2AE93BF7C04FF7C1D8B7B /* Kingfisher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Kingfisher-dummy.m"; sourceTree = ""; }; + 5C12F9EE80F91F13B4B83C977CD01AE8 /* Asset.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Asset.swift; path = "lottie-swift/src/Private/Model/Assets/Asset.swift"; sourceTree = ""; }; + 5CB3E26C685C33AAD94DDAC2A13DD470 /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Never.swift; sourceTree = ""; }; + 5CC5E86D7D71B850C7D72A19A6FCD417 /* PrepareViewForSkeleton.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrepareViewForSkeleton.swift; path = SkeletonViewCore/Sources/Internal/SkeletonExtensions/PrepareViewForSkeleton.swift; sourceTree = ""; }; + 5CF303356DC7A4D17A311EE4B8598B16 /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; + 5D0D31D7FB33943C68B067F93D7639D2 /* _RXObjCRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXObjCRuntime.h; path = RxCocoa/Runtime/include/_RXObjCRuntime.h; sourceTree = ""; }; + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5E30CE980C3C04353853E2AF1A39C145 /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + 5E5F0AEB88A75A924160B8991DC64A4D /* AsyncSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncSubject.swift; path = RxSwift/Subjects/AsyncSubject.swift; sourceTree = ""; }; + 5E68D7FE551C4CDD777F3AAFE86821C1 /* Group.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Group.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Group.swift"; sourceTree = ""; }; + 5E99ED7A5B57918151A962F031DA8B2D /* ColorExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ColorExtension.swift; path = "lottie-swift/src/Private/Utility/Primitives/ColorExtension.swift"; sourceTree = ""; }; + 5F5AE1F6568B946172123A13DD26E4AC /* Maybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Maybe.swift; path = RxSwift/Traits/PrimitiveSequence/Maybe.swift; sourceTree = ""; }; + 5FA4E4F7F53DBC89CE7DD14EC091577B /* Keyframe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Keyframe.swift; path = "lottie-swift/src/Private/Model/Keyframes/Keyframe.swift"; sourceTree = ""; }; + 601A2832945FACAC50820FDBB3B05BCF /* InterpolatableExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InterpolatableExtensions.swift; path = "lottie-swift/src/Private/Utility/Interpolatable/InterpolatableExtensions.swift"; sourceTree = ""; }; + 60DAF39780BEBA99153B7A449B8B5A5A /* TextCompositionLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextCompositionLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/TextCompositionLayer.swift"; sourceTree = ""; }; + 60E8F31B3DA3B9958C36DA86B0A97F0E /* SubviewsSkeletonables.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubviewsSkeletonables.swift; path = SkeletonViewCore/Sources/Internal/SkeletonExtensions/SubviewsSkeletonables.swift; sourceTree = ""; }; + 61900EC8CBFE35E647E8EFF142E70217 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + 61AC97B1CC38C9AEF119A14A5E54D5E5 /* Dematerialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Dematerialize.swift; path = RxSwift/Observables/Dematerialize.swift; sourceTree = ""; }; + 61BCD1938C7E8E565B52A5E0BE04084C /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Timeout.swift; sourceTree = ""; }; + 61CAA5048FAA6F86DBCA93B8B7B6FB05 /* ImageAsset.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageAsset.swift; path = "lottie-swift/src/Private/Model/Assets/ImageAsset.swift"; sourceTree = ""; }; + 62A531319033D427E8405BE7B48DFB62 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 6337BB2269CC5F2DB6B494F7F76148F4 /* UIView+AppLifecycleNotifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+AppLifecycleNotifications.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+AppLifecycleNotifications.swift"; sourceTree = ""; }; + 6353C2C95453DCBB87CC569B4A188FCC /* Pods-sopt_29th_Assignment-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-sopt_29th_Assignment-dummy.m"; sourceTree = ""; }; + 637A7B8E0568D3EF7B0A2556D5DE4A06 /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 64592E246FA7D5B9EF0A591746D1F2EC /* Zip+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+Collection.swift"; path = "RxSwift/Observables/Zip+Collection.swift"; sourceTree = ""; }; + 64B2FD33538D38B86472940515F0DCC5 /* FloatValueProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FloatValueProvider.swift; path = "lottie-swift/src/Public/DynamicProperties/ValueProviders/FloatValueProvider.swift"; sourceTree = ""; }; + 65805841B5A618A05FAAF656AE93E772 /* Moya+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Moya+Alamofire.swift"; path = "Sources/Moya/Moya+Alamofire.swift"; sourceTree = ""; }; + 658B3E81297F503FE6CB67E23E559099 /* ImagePrefetcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImagePrefetcher.swift; path = Sources/Networking/ImagePrefetcher.swift; sourceTree = ""; }; + 65DAAFBCF14E6735F9006742B5A0B053 /* WithUnretained.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithUnretained.swift; path = RxSwift/Observables/WithUnretained.swift; sourceTree = ""; }; + 668793E6F8B1D1C36659901F3D212F86 /* CALayer+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CALayer+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/CALayer+Extensions.swift"; sourceTree = ""; }; + 66DA767E2110B9DE41D6296EB97A51AC /* GradientDirection+Animations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "GradientDirection+Animations.swift"; path = "SkeletonViewCore/Sources/Internal/SkeletonExtensions/GradientDirection+Animations.swift"; sourceTree = ""; }; + 66FBA686CFD090AA2B166227E4ECF81E /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + 66FBAC3E0E191ED981538DBCFFBFBD83 /* Source.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Source.swift; path = Sources/General/ImageSource/Source.swift; sourceTree = ""; }; + 67A269CCEF3E54285735630AE7BB7253 /* AnimationContainer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationContainer.swift; path = "lottie-swift/src/Private/LayerContainers/AnimationContainer.swift"; sourceTree = ""; }; + 67AEAD300238A4E2EB710FE822BB3A5A /* Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Kingfisher.swift; path = Sources/General/Kingfisher.swift; sourceTree = ""; }; + 67B9263F9767710808C7F9C6B017554E /* ConstraintView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintView.swift; path = Source/ConstraintView.swift; sourceTree = ""; }; + 681C7085B058D412CDBAE81D6CC3590F /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 683A06F221EAF470EDECF217893A1459 /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + 68424BAC950DB41E65054A2379D3970E /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 6992F289EBE32043726DD989AE0E75F9 /* ListPlaceholder-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ListPlaceholder-prefix.pch"; sourceTree = ""; }; + 6994931C5C5549C924814ED0DECA00A0 /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Zip+arity.swift"; sourceTree = ""; }; + 699C754CB7A4A4F2D0BBB08B976D0EFC /* VectorsExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VectorsExtensions.swift; path = "lottie-swift/src/Private/Utility/Primitives/VectorsExtensions.swift"; sourceTree = ""; }; + 69B2B19CD8426F161013829AABAA4A64 /* 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; }; + 69E2C711E5C8B7DB42DDBBD92A6845D1 /* CurveVertex.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurveVertex.swift; path = "lottie-swift/src/Private/Utility/Primitives/CurveVertex.swift"; sourceTree = ""; }; + 69F3FFEF813BEAA0DD193DA5CF47F469 /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxSwift.modulemap; sourceTree = ""; }; + 6ADB32B034C4EC108D132E1D1886EB47 /* WKWebView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "WKWebView+Rx.swift"; path = "RxCocoa/iOS/WKWebView+Rx.swift"; sourceTree = ""; }; + 6B6496DFF2CE2431D9089085DA8B38A8 /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + 6B93B89B4A289CE40673582EAB3EEABF /* 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; }; + 6BB013FF0D1B8DC50E478E8D80AED779 /* MultiTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultiTarget.swift; path = Sources/Moya/MultiTarget.swift; sourceTree = ""; }; + 6BDB661C93B87F00D167E4709AD2A86C /* KeypathSearchable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeypathSearchable.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/KeypathSearchable.swift"; sourceTree = ""; }; + 6C0EC79BB2684684092112E66097E51C /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/MultipartUpload.swift; sourceTree = ""; }; + 6C242DB41AE52F6AFD5C52D96966223A /* SkeletonTreeNode+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SkeletonTreeNode+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/SkeletonTreeNode+Extensions.swift"; sourceTree = ""; }; + 6C8C603268BD296934CEC35FB0BC8923 /* ImageView+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ImageView+Kingfisher.swift"; path = "Sources/Extensions/ImageView+Kingfisher.swift"; sourceTree = ""; }; + 6CDDF1EB0C34D6D1DFAC3CB89513B98E /* RxCocoa-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-umbrella.h"; sourceTree = ""; }; + 6DD295E670FAB94E394EA854B93616CF /* GroupOutputNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupOutputNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/GroupOutputNode.swift"; sourceTree = ""; }; + 6DD434842DAF29DF870CB0898C2BECDD /* UIScrollView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIScrollView+Rx.swift"; path = "RxCocoa/iOS/UIScrollView+Rx.swift"; sourceTree = ""; }; + 6DE7E81B55F89A333B743EB3C1FB84E4 /* UIView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Extensions.swift"; sourceTree = ""; }; + 6DF67815AB2355808DE38A66A22BF832 /* ShapeRenderLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShapeRenderLayer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeRenderLayer.swift"; sourceTree = ""; }; + 6E0F121593C5A360AD45CB450EF3EF36 /* RxScrollViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxScrollViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift; sourceTree = ""; }; + 6E19FA12109EA2B1D8E939B3434B1332 /* AnimatedSwitch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedSwitch.swift; path = "lottie-swift/src/Public/iOS/AnimatedSwitch.swift"; sourceTree = ""; }; + 6E21A1D9ABB6E3BF10CF6276800D7EAF /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 6EB10D17D9BEBBA990AEF87BA0F42A6A /* SkeletonConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonConfig.swift; path = SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonConfig.swift; sourceTree = ""; }; + 6EBADBDD2F7B15C127B92289C76915E4 /* DashPattern.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DashPattern.swift; path = "lottie-swift/src/Private/Model/Objects/DashPattern.swift"; sourceTree = ""; }; + 6F3CFE254D1E97B15F75B7259F27814D /* FormatIndicatedCacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormatIndicatedCacheSerializer.swift; path = Sources/Cache/FormatIndicatedCacheSerializer.swift; sourceTree = ""; }; + 6F79D038FA893AD60C0B9929B99012B4 /* RxCocoa.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxCocoa.modulemap; sourceTree = ""; }; + 7067BB1DCEE4AEFF65144415F41FD9B9 /* URLSession+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSession+Rx.swift"; path = "RxCocoa/Foundation/URLSession+Rx.swift"; sourceTree = ""; }; + 71933B6884EC0E04F1FB08D3D531237A /* DelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxy.swift; path = RxCocoa/Common/DelegateProxy.swift; sourceTree = ""; }; + 71D272C276387B42DE9C3FF7D1711F7D /* UISearchController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchController+Rx.swift"; path = "RxCocoa/iOS/UISearchController+Rx.swift"; sourceTree = ""; }; + 71D6937F919B2CBC07245D5F1D061843 /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/StartWith.swift; sourceTree = ""; }; + 7251F730820CB2440AE47178A2E05925 /* Reactive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reactive.swift; path = RxSwift/Reactive.swift; sourceTree = ""; }; + 72D98974480C49492DA09E6CDDE9A7FE /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/SkipUntil.swift; sourceTree = ""; }; + 72FA3260F540C02E616019AF7AF70861 /* ColorValueProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ColorValueProvider.swift; path = "lottie-swift/src/Public/DynamicProperties/ValueProviders/ColorValueProvider.swift"; sourceTree = ""; }; + 7486E5C476617A9E62DF0845B3133A84 /* RxCollectionViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift; sourceTree = ""; }; + 75207E1DC5C483BB5DE0C5B790629BB4 /* Recursive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Recursive.swift; path = SkeletonViewCore/Sources/Internal/Helpers/Recursive.swift; sourceTree = ""; }; + 7520D72882C54D369DC3AB4761527968 /* AsSingle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsSingle.swift; path = RxSwift/Observables/AsSingle.swift; sourceTree = ""; }; + 75AE3E15F1F864EB067AB303139E6202 /* Endpoint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Endpoint.swift; path = Sources/Moya/Endpoint.swift; sourceTree = ""; }; + 75D32CA634B512FB58E0DFC658CA4C36 /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Source/ConstraintAttributes.swift; sourceTree = ""; }; + 7604183F01BAC07BC713363B6728A161 /* Moya.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Moya.modulemap; sourceTree = ""; }; + 7733913F39955FAD01EB941C89BD73FB /* SkeletonGradient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonGradient.swift; path = SkeletonViewCore/Sources/API/Models/SkeletonGradient.swift; sourceTree = ""; }; + 778BBEE465580922EF19056B1FB95575 /* Delay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delay.swift; path = RxSwift/Observables/Delay.swift; sourceTree = ""; }; + 779509B5AC8A026D6CCF04664FE67F0C /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Utility/Box.swift; sourceTree = ""; }; + 7799020F51899D03AA1E835BF03E4F71 /* SkeletonView-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SkeletonView-Info.plist"; sourceTree = ""; }; + 77BCB87986D3BA89FAF5B76F32EF0E1F /* SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SharedSequence.swift; path = RxCocoa/Traits/SharedSequence/SharedSequence.swift; sourceTree = ""; }; + 77F3F1B5A07B282D5E743E607B0110B4 /* Pods-sopt_29th_Assignment */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-sopt_29th_Assignment"; path = Pods_sopt_29th_Assignment.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 788E707B4401762A4BA111312D0317F9 /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + 78B5248C51B733A30C1C2CEFBD955431 /* Glyph.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Glyph.swift; path = "lottie-swift/src/Private/Model/Text/Glyph.swift"; sourceTree = ""; }; + 78EE67455BC257C012D56E3CF4289753 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Multicast.swift; sourceTree = ""; }; + 79100CD5FC439F8E474A63439EF9E8A6 /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Source/ConstraintPriorityTarget.swift; sourceTree = ""; }; + 7928AE6F54492F85775B5EEDC096789C /* NSControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSControl+Rx.swift"; path = "RxCocoa/macOS/NSControl+Rx.swift"; sourceTree = ""; }; + 79890AAA4FBE26BD1D68BED9C1DBF801 /* Pods-sopt_29th_Assignment-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-sopt_29th_Assignment-acknowledgements.plist"; sourceTree = ""; }; + 798B36F771350D6304F48AA292794702 /* SizeExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SizeExtensions.swift; path = Sources/Utility/SizeExtensions.swift; sourceTree = ""; }; + 79BE205B7363AA5BD607C5AC7854113B /* Vectors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Vectors.swift; path = "lottie-swift/src/Public/Primitives/Vectors.swift"; sourceTree = ""; }; + 79C9F7290555E8206ECC8A5A27A6FB84 /* Typealiases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Typealiases.swift; path = Source/Typealiases.swift; sourceTree = ""; }; + 79CCBA90D8565C6D22EFAC3E476BAD52 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Catch.swift; sourceTree = ""; }; + 79CCD96014790B1C04490CC18D92C41A /* SwiftSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftSupport.swift; path = RxSwift/SwiftSupport/SwiftSupport.swift; sourceTree = ""; }; + 7A6BDC77EAEBCA14DA677FCC3FE310A9 /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/WithLatestFrom.swift; sourceTree = ""; }; + 7AD41A4730360AF228ACA97E7BCE4212 /* Combine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Combine.swift; path = Source/Combine.swift; sourceTree = ""; }; + 7ADD9BE3E7CF0D7114194C3E5B4E20CF /* RxRelay-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxRelay-dummy.m"; sourceTree = ""; }; + 7B46F7D182E6FCA5635A2BEA65BCF483 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + 7B5C178ABA8010A0DEC30E331EB4DF64 /* TextDocument.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextDocument.swift; path = "lottie-swift/src/Private/Model/Text/TextDocument.swift"; sourceTree = ""; }; + 7BEF0FAAC7C86B3C907BF5962D972DC3 /* NSTextStorage+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextStorage+Rx.swift"; path = "RxCocoa/iOS/NSTextStorage+Rx.swift"; sourceTree = ""; }; + 7C03C324DCEC33D1BCDC0F49FEA3BF5A /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + 7C201370A855FCF81DC8E1D8DA720491 /* Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Driver.swift; path = RxCocoa/Traits/Driver/Driver.swift; sourceTree = ""; }; + 7C55FC5EF514FB4258BC99DB4703D221 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 7DAC87840CE67D59C51D0B26BA74041A /* CollectionSkeleton.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CollectionSkeleton.swift; path = SkeletonViewCore/Sources/Internal/Collections/CollectionSkeleton.swift; sourceTree = ""; }; + 7DCF16C57C75BF50B3F5CCB76DD8EFB5 /* 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; }; + 7E6B622ADFB980BF374CBB86D3759C0F /* CallbackQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CallbackQueue.swift; path = Sources/Utility/CallbackQueue.swift; sourceTree = ""; }; + 7ECE50328AD6B4F70001FD7342D1AC24 /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + 7ED739459C8BBA3A49BDF0C535E3D6C3 /* Font.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Font.swift; path = "lottie-swift/src/Private/Model/Text/Font.swift"; sourceTree = ""; }; + 808B587D23A5746A071DBE671C0B134F /* Decode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Decode.swift; path = RxSwift/Observables/Decode.swift; sourceTree = ""; }; + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxSwift; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 812B2824CD60068C30219DE3B73F8FB0 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 822AD736BB3D75AC5047E27811EC926F /* ControlEvent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlEvent.swift; path = RxCocoa/Traits/ControlEvent.swift; sourceTree = ""; }; + 8368A92C8EA09600C9E2C855F83C8C01 /* PathNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PathNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Protocols/PathNode.swift"; sourceTree = ""; }; + 83A0C8E7D0862A9B6C7BD32F2EACC537 /* SnapKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SnapKit.modulemap; sourceTree = ""; }; + 84B58261A8D6FC70BD19808D6EF5D68D /* UIGestureRecognizer+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIGestureRecognizer+Rx.swift"; path = "RxCocoa/iOS/UIGestureRecognizer+Rx.swift"; sourceTree = ""; }; + 853087100942AF514143837601F12DCC /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/CombineLatest+arity.swift"; sourceTree = ""; }; + 85328C52C4A45C6C830C8F5D72D13AEE /* ConstraintDirectionalInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsetTarget.swift; path = Source/ConstraintDirectionalInsetTarget.swift; sourceTree = ""; }; + 8635C303D5A4896131561341C8493289 /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Deferred.swift; sourceTree = ""; }; + 8741F7E10B36E8F94F04D711CAAEFFE9 /* Plugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Plugin.swift; path = Sources/Moya/Plugin.swift; sourceTree = ""; }; + 87587A4BCD25F7ABE2B906B50D52E516 /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/ElementAt.swift; sourceTree = ""; }; + 876658971488280401D29AE699396A1C /* TextInput.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextInput.swift; path = RxCocoa/Common/TextInput.swift; sourceTree = ""; }; + 87735C0487D6CA4F171CF8DA7CD1278B /* AssociationPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AssociationPolicy.swift; path = SkeletonViewCore/Sources/Internal/Helpers/AssociationPolicy.swift; sourceTree = ""; }; + 881461D11DAD4B0D0627B6EFE37D1926 /* UIButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Kingfisher.swift"; path = "Sources/Extensions/UIButton+Kingfisher.swift"; sourceTree = ""; }; + 8966225B5C5536F8B019FCE27F737098 /* RxTableViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift; sourceTree = ""; }; + 89BA5964A5E5D1A71F9E5858E4620E5A /* KingfisherManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherManager.swift; path = Sources/General/KingfisherManager.swift; sourceTree = ""; }; + 89C3D4B031C655927020FD3C14DDFCE3 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + 89D812681CA39BEB09D4C419C19E684E /* ControlProperty+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlProperty+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlProperty+Driver.swift"; sourceTree = ""; }; + 8A5C88CC7FE36F1A405C15CDFC255FCF /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + 8A75C74B3699B0CDC64C7C23892A9BA1 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; + 8A7D4DA0A4088D7A5AA82C6475EFF6D5 /* AssetLibrary.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AssetLibrary.swift; path = "lottie-swift/src/Private/Model/Assets/AssetLibrary.swift"; sourceTree = ""; }; + 8AD24F3A7AC53743B10C3F63B5866547 /* Deprecated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecated.swift; path = Sources/General/Deprecated.swift; sourceTree = ""; }; + 8B6946CBE7861917F027FE6008918B0C /* LottieView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LottieView.swift; path = "lottie-swift/src/Public/iOS/LottieView.swift"; sourceTree = ""; }; + 8C3816D0BD55363234509538304F2C98 /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/URLEncodedFormEncoder.swift; sourceTree = ""; }; + 8CA31AE5F7ECFABC6C659814E6834818 /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Sources/Image/Image.swift; sourceTree = ""; }; + 8CBA8D2D8781420D04B92B32FADC98A1 /* ConstraintConstantTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConstantTarget.swift; path = Source/ConstraintConstantTarget.swift; sourceTree = ""; }; + 8CD3719C675D6F03542CD7EFCE7B46EB /* Placeholder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Placeholder.swift; path = Sources/Image/Placeholder.swift; sourceTree = ""; }; + 8D168476D52EFA1C2C2052BBFC538ED3 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 8D9520E93F1C6E181AB64C6705EEDEC9 /* UIView+Swizzling.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Swizzling.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Swizzling.swift"; sourceTree = ""; }; + 8E56681B529C28A6E689C753AFB5C5A9 /* BundleImageProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BundleImageProvider.swift; path = "lottie-swift/src/Public/iOS/BundleImageProvider.swift"; sourceTree = ""; }; + 8E7ACE526EED15B718B4B164D40F7834 /* PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrimitiveSequence.swift; path = RxSwift/Traits/PrimitiveSequence/PrimitiveSequence.swift; sourceTree = ""; }; + 8EA592B787975BD740DF85A0C27FD2A8 /* ImageModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageModifier.swift; path = Sources/Networking/ImageModifier.swift; sourceTree = ""; }; + 8EC82515D323F64C29E236D7341AE7AE /* CompositionLayersInitializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositionLayersInitializer.swift; path = "lottie-swift/src/Private/LayerContainers/Utility/CompositionLayersInitializer.swift"; sourceTree = ""; }; + 8EF1F2977FAC819C88157477780EA4CA /* SnapKit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.debug.xcconfig; sourceTree = ""; }; + 8F0A8B19E1BC4E88AA8159FDE0A173A3 /* Indicator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Indicator.swift; path = Sources/Views/Indicator.swift; sourceTree = ""; }; + 8F69100E0147D6C4D38EDDD7A1E58A5E /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + 8FC7A302AF558DC2FFCCDA0282CD0E63 /* Kingfisher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Kingfisher.h; path = Sources/Kingfisher.h; sourceTree = ""; }; + 9166244941FB647F587BB858C1470031 /* RxPickerViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift; sourceTree = ""; }; + 91BC576A34535F04F3E41BB5F4A2BE19 /* Kingfisher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-umbrella.h"; sourceTree = ""; }; + 91C6DD2377283D6623801DB391EC90AF /* Kingfisher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Kingfisher.modulemap; sourceTree = ""; }; + 920C05BEAC13D0E9DDC0F0804DCC706D /* SnapKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-prefix.pch"; sourceTree = ""; }; + 92ABA31BDF9745B8D40F3B5E55502350 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Sources/Networking/RedirectHandler.swift; sourceTree = ""; }; + 92D160F41A5F10649E32F3FD52D41D21 /* RxTabBarControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift; sourceTree = ""; }; + 9317E4947CA2FE1B5D5999034C09CCA7 /* Then */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Then; path = Then.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 93AF1A70F61D237BFA37E52EC09B3345 /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + 93BF6B791D497D88399007FB4AD48570 /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 93D42DBBE4B2B3C7F405C325CE7ED02D /* AnimatedControl.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedControl.swift; path = "lottie-swift/src/Public/iOS/AnimatedControl.swift"; sourceTree = ""; }; + 93E79E4061F7310825626A571136E52C /* ShapeTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShapeTransform.swift; path = "lottie-swift/src/Private/Model/ShapeItems/ShapeTransform.swift"; sourceTree = ""; }; + 94144BB3737DFCA50D6CBDA921B288CB /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + 944DA138D0F8B5754B4374EDCE6E9B0D /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 948610301CCEBB19AAA757417190F369 /* UIControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIControl+Rx.swift"; path = "RxCocoa/iOS/UIControl+Rx.swift"; sourceTree = ""; }; + 949BBB5ECE7B5436603B7FC04CF44AE3 /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/DistinctUntilChanged.swift; sourceTree = ""; }; + 94E98DD21F3A8AA85F9AA68B8CD5AF79 /* UICollectionView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+Extensions.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/UICollectionView+Extensions.swift"; sourceTree = ""; }; + 952BA62F6689CB4B398C16DBE3471008 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Merge.swift"; sourceTree = ""; }; + 958990AC25E732E67FE51103C087723C /* StringExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StringExtensions.swift; path = "lottie-swift/src/Private/Utility/Extensions/StringExtensions.swift"; sourceTree = ""; }; + 95E3F3825D907C4E21155D3E3E8F7DF0 /* RxTableViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + 964824591CA2DE2B4FB7B566519B80FE /* Single.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Single.swift; path = RxSwift/Traits/PrimitiveSequence/Single.swift; sourceTree = ""; }; + 968326A729170F8CF833DC5AE0E14E9D /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + 96E774AF77CBFC641B734B852F795BF0 /* ImageDataProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDataProvider.swift; path = Sources/General/ImageSource/ImageDataProvider.swift; sourceTree = ""; }; + 97725CE91BDF719A6F66531F0753AE0A /* Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Infallible.swift; path = RxSwift/Traits/Infallible/Infallible.swift; sourceTree = ""; }; + 979486118B3E90C08386079D57962701 /* SnapKit */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SnapKit; path = SnapKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 97F8A41D5BE85EF128CB8F2401A2E9DB /* ControlEvent+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlEvent+Driver.swift"; sourceTree = ""; }; + 98A27FB74C2C193735A702F70EEAFC2D /* RxTextStorageDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextStorageDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift; sourceTree = ""; }; + 98F8064E2F318C1DDD89DC1186646E74 /* SkeletonView-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SkeletonView-umbrella.h"; sourceTree = ""; }; + 99257C69694C651E2522624CF9C224FD /* CredentialsPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CredentialsPlugin.swift; path = Sources/Moya/Plugins/CredentialsPlugin.swift; sourceTree = ""; }; + 99430E20314FA52AE89A8E413268C90D /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + 99D2BEA76FA15F487ADF926CB89CF093 /* MemoryStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MemoryStorage.swift; path = Sources/Cache/MemoryStorage.swift; sourceTree = ""; }; + 9B221BB5199889A8401D51EAAC1E618E /* NSView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSView+Rx.swift"; path = "RxCocoa/macOS/NSView+Rx.swift"; sourceTree = ""; }; + 9C156DEDEE5322CEF2B1F759D8B69489 /* ShapeNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShapeNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift"; sourceTree = ""; }; + 9C3783A8A3F5F65A635AF839F252AA0F /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Repeat.swift; sourceTree = ""; }; + 9D49DD6592CAE4A4681462C888A5704F /* SingleValueProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleValueProvider.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/SingleValueProvider.swift"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9DA61552627F440050A87FAB1F0F46AB /* GradientFill.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientFill.swift; path = "lottie-swift/src/Private/Model/ShapeItems/GradientFill.swift"; sourceTree = ""; }; + 9E0E9B03955AD5C69E96676AC5F31FD5 /* Marker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Marker.swift; path = "lottie-swift/src/Private/Model/Objects/Marker.swift"; sourceTree = ""; }; + 9E4D3CDCE6607CA1788A973945B813DB /* RxCollectionViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + 9E963FDB21BEC3F2CBFF40253B0B1671 /* Mask.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Mask.swift; path = "lottie-swift/src/Private/Model/Objects/Mask.swift"; sourceTree = ""; }; + 9EE72C751257B211AA10C4EBA38EA378 /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + 9FF3A9A33C900F71DA5EF5C29BE949A4 /* NSObject+Rx+RawRepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+RawRepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift"; sourceTree = ""; }; + 9FF59D35D100AB4908E8C05EA0DDBBBA /* ConstraintOffsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintOffsetTarget.swift; path = Source/ConstraintOffsetTarget.swift; sourceTree = ""; }; + A0284DCEBF435B8B9683A5409873BEA7 /* UIActivityIndicatorView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActivityIndicatorView+Rx.swift"; path = "RxCocoa/iOS/UIActivityIndicatorView+Rx.swift"; sourceTree = ""; }; + A04CAB33A23F87A51DD2CD941A6895F9 /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; + A07764B25F14323CC34D8697ECD39487 /* TextLayerModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextLayerModel.swift; path = "lottie-swift/src/Private/Model/Layers/TextLayerModel.swift"; sourceTree = ""; }; + A097698ED559F253065E3FE68B41B5AE /* SkeletonLayerBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonLayerBuilder.swift; path = SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonLayerBuilder.swift; sourceTree = ""; }; + A13C79480FE01C9508D13C16018BEADA /* NSTextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextView+Rx.swift"; path = "RxCocoa/macOS/NSTextView+Rx.swift"; sourceTree = ""; }; + A178A97BCE6505C2B3FD32FCFA25A45F /* AnyNodeProperty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyNodeProperty.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyNodeProperty.swift"; sourceTree = ""; }; + A1A71FD0103010BF1034EF966A3D7D4F /* UISwitch+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISwitch+Rx.swift"; path = "RxCocoa/iOS/UISwitch+Rx.swift"; sourceTree = ""; }; + A210044777925BBC8576B70CCA87AEB0 /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; + A2A62ACB1FA99BED968D941C78B678FE /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + A351B9E7F7C039CD709E1333C4329FC3 /* Pods-sopt_29th_Assignment-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-sopt_29th_Assignment-umbrella.h"; sourceTree = ""; }; + A3A5C82D7E3750C47DCC4D089790BBD9 /* SizeValueProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SizeValueProvider.swift; path = "lottie-swift/src/Public/DynamicProperties/ValueProviders/SizeValueProvider.swift"; sourceTree = ""; }; + A3FD5F1676F6BE15B29D02BACF63E175 /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Generate.swift; sourceTree = ""; }; + A3FE18E0C1AB2C67F76AA021FEEBEE28 /* RxCollectionViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift; sourceTree = ""; }; + A48F8F6180E6DDC72D73DC1F0F803C76 /* GroupNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderContainers/GroupNode.swift"; sourceTree = ""; }; + A49FCB95D8218F9C1184EE6009A97BD2 /* PreCompositionLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PreCompositionLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/PreCompositionLayer.swift"; sourceTree = ""; }; + A4C19766D6627B764323CAA1F56C4BE8 /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + A5043540270E8CACE7C104E16E932D51 /* GradientDirection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientDirection.swift; path = SkeletonViewCore/Sources/API/Models/GradientDirection.swift; sourceTree = ""; }; + A6D1220EF0F905357EBF2ABB4C0F553D /* ListPlaceholder-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ListPlaceholder-umbrella.h"; sourceTree = ""; }; + A78137DC94228E968FFEC6F480F98303 /* ListPlaceholder-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ListPlaceholder-Info.plist"; sourceTree = ""; }; + A7B7DCA28AC747E52ED2D5253ACE2EC1 /* TextAnimatorNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextAnimatorNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/Text/TextAnimatorNode.swift"; sourceTree = ""; }; + A978D283A5C9E40B939D66C2AE26925D /* Moya-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Moya-Info.plist"; sourceTree = ""; }; + A9967B03CCF1284AA798AE8C3724EAEA /* GroupedObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupedObservable.swift; path = RxSwift/GroupedObservable.swift; sourceTree = ""; }; + AA353B32D4E255B5032D0EB172EC1338 /* SessionDataTask.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDataTask.swift; path = Sources/Networking/SessionDataTask.swift; sourceTree = ""; }; + AB4DCE3C49F276788DC256A7CB221394 /* UIPickerView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIPickerView+Rx.swift"; path = "RxCocoa/iOS/UIPickerView+Rx.swift"; sourceTree = ""; }; + AC3687208B7F8431C226C956B3D8A795 /* Then.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Then.modulemap; sourceTree = ""; }; + AC38F5AE52B4EEB7D3604228631C5672 /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + AC6E4149138E959D0E81F99FB12B5708 /* Int+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Int+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/FoundationExtensions/Int+Extensions.swift"; sourceTree = ""; }; + ACB48AE1C8CD94FA8E742A31AC787215 /* Then-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Then-prefix.pch"; sourceTree = ""; }; + ACBF41845B42A62975644A4A871D0276 /* UILayoutSupport+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutSupport+Extensions.swift"; path = "Source/UILayoutSupport+Extensions.swift"; sourceTree = ""; }; + AD3D6EEF925607AD0B298BEE42319A52 /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Buffer.swift; sourceTree = ""; }; + AD54988AAEF3476D7CDFD2076F4F7D35 /* Repeater.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeater.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Repeater.swift"; sourceTree = ""; }; + AE2F81EE0A1DEAFA1442491D488A81D9 /* NSTextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextField+Rx.swift"; path = "RxCocoa/macOS/NSTextField+Rx.swift"; sourceTree = ""; }; + B04EFFB7E4883C11B13334C7E9B5D414 /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + B0B8965EB066B4207C18FA0BB86BB3F5 /* AnimationTextProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationTextProvider.swift; path = "lottie-swift/src/Public/TextProvider/AnimationTextProvider.swift"; sourceTree = ""; }; + B1466CA4D101FAE23F9D08B8B63663EE /* UISearchBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchBar+Rx.swift"; path = "RxCocoa/iOS/UISearchBar+Rx.swift"; sourceTree = ""; }; + B15BB714A8520B79B914395B09633637 /* RxCocoaObjCRuntimeError+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RxCocoaObjCRuntimeError+Extensions.swift"; path = "RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift"; sourceTree = ""; }; + B1D3B3A052D7F825E2B4B74BC66DE801 /* ConstraintView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintView+Extensions.swift"; path = "Source/ConstraintView+Extensions.swift"; sourceTree = ""; }; + B220CFF8BD81422281651D25D997C0F8 /* lottie-ios-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "lottie-ios-dummy.m"; sourceTree = ""; }; + B3A8E3C5F6FA0810BB8649881B922222 /* SkeletonDebug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonDebug.swift; path = SkeletonViewCore/Sources/Internal/Debug/SkeletonDebug.swift; sourceTree = ""; }; + B3D31D5552712947DD6DD4DD6D381390 /* First.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = First.swift; path = RxSwift/Observables/First.swift; sourceTree = ""; }; + B41AEA65C66E7ACEA41AD1C1F3C68F20 /* AuthenticationInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationInterceptor.swift; path = Source/AuthenticationInterceptor.swift; sourceTree = ""; }; + B44E8DFF310AA7060F227B091F7A87C0 /* UIView+SkeletonView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+SkeletonView.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+SkeletonView.swift"; sourceTree = ""; }; + B484FCBAC5748316D28EE3BB31442683 /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Using.swift; sourceTree = ""; }; + B4E560FCC7FB3037CD48F0A911A4B06D /* KingfisherError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherError.swift; path = Sources/General/KingfisherError.swift; sourceTree = ""; }; + B5893E2F6BDE1656D9E2AED1E55AE57B /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + B58CBA3AA57CA05996897232EC752A91 /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Sample.swift; sourceTree = ""; }; + B5CE0BDCFF01EB2384FC3A771ACD4E43 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/ServerTrustEvaluation.swift; sourceTree = ""; }; + B63B29F6B0F59E6DE8F568AEB205CBF1 /* ObservableType+PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+PrimitiveSequence.swift"; path = "RxSwift/Traits/PrimitiveSequence/ObservableType+PrimitiveSequence.swift"; sourceTree = ""; }; + B640A6E4F170CB420AEF0F40319B8A78 /* Animation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Animation.swift; path = "lottie-swift/src/Private/Model/Animation.swift"; sourceTree = ""; }; + B744D0CCE9CE83FFF1F579AE0B296541 /* NodePropertyMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NodePropertyMap.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/NodePropertyMap.swift"; sourceTree = ""; }; + B74A78EF31C6F1542EAABDF86E9045D8 /* SwiftyJSON.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.release.xcconfig; sourceTree = ""; }; + B77639677D7E536F13ADA0C3B0E12156 /* RxTableViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift; sourceTree = ""; }; + B77B9A720BE238A674C1DABB07F5CD46 /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Session.swift; sourceTree = ""; }; + B7AA4E90F7000B003BDC0E9BC7B633EB /* Pods-sopt_29th_Assignment.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-sopt_29th_Assignment.modulemap"; sourceTree = ""; }; + B7E83FBCF31EBBE7B947981E091EE7D6 /* AccessTokenPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AccessTokenPlugin.swift; path = Sources/Moya/Plugins/AccessTokenPlugin.swift; sourceTree = ""; }; + B833736B901BD30A23F443B52BCDE473 /* Binder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Binder.swift; path = RxSwift/Binder.swift; sourceTree = ""; }; + B8F067EB2F26B16397A4024118090762 /* ConstraintMakerFinalizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerFinalizable.swift; path = Source/ConstraintMakerFinalizable.swift; sourceTree = ""; }; + B8FDDD0C23DABA7732501CD8AF1CCE6D /* Notification+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Notification+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/FoundationExtensions/Notification+Extensions.swift"; sourceTree = ""; }; + B93578502709168269517790C6A933EA /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Reduce.swift; sourceTree = ""; }; + B958D6DAA7CC8E707A980E42F41B9E7B /* _RX.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RX.m; path = RxCocoa/Runtime/_RX.m; sourceTree = ""; }; + BA03E550D12601C16729AAADF5DD65F0 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Sources/Networking/SessionDelegate.swift; sourceTree = ""; }; + BA073A17F7CF413B9B0A49B43CE73B77 /* Then-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Then-dummy.m"; sourceTree = ""; }; + BAD21644D07C588A6BB916B9CE6FADD7 /* NSButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSButton+Rx.swift"; path = "RxCocoa/macOS/NSButton+Rx.swift"; sourceTree = ""; }; + BAF26B7796406D469664118D70F8B582 /* Then.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Then.swift; path = Sources/Then/Then.swift; sourceTree = ""; }; + BB6402E753D04F905BC4852F64AF7029 /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+Collection.swift"; path = "RxSwift/Observables/CombineLatest+Collection.swift"; sourceTree = ""; }; + BB73A1C3B4A7F9EE2A1685D474B50FA1 /* Infallible+Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Create.swift"; path = "RxSwift/Traits/Infallible/Infallible+Create.swift"; sourceTree = ""; }; + BB872120E955C14C936A66F79C63056E /* ConstraintDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDSL.swift; path = Source/ConstraintDSL.swift; sourceTree = ""; }; + BBE5754AAA9F6ACD8F57F8DD39D05E07 /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Switch.swift; sourceTree = ""; }; + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxCocoa; path = RxCocoa.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + BC4858AAE41174640ADC6C4F4EBB738A /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/RequestTaskMap.swift; sourceTree = ""; }; + BC943D97ED350208583B6BA939BB98D2 /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/RetryWhen.swift; sourceTree = ""; }; + BCB9B7980E4C45EF00EDD72D1DAA9B70 /* GradientValueProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientValueProvider.swift; path = "lottie-swift/src/Public/DynamicProperties/ValueProviders/GradientValueProvider.swift"; sourceTree = ""; }; + BD28CA8E650A4F97AFB97973D4630A2B /* ConstraintPriority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriority.swift; path = Source/ConstraintPriority.swift; sourceTree = ""; }; + BD8F63AEB8F29A078DB6D1994472EA53 /* ImageCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageCache.swift; path = Sources/Cache/ImageCache.swift; sourceTree = ""; }; + BE492532FB512F9B783CFB73C24D696C /* SchedulerType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift"; sourceTree = ""; }; + BE7F07175183E202A0AA6844976B0496 /* AnimationKeypath.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationKeypath.swift; path = "lottie-swift/src/Public/DynamicProperties/AnimationKeypath.swift"; sourceTree = ""; }; + BEE5B6721BB2351DE21380FD23EFD7C6 /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/URLRequest+Alamofire.swift"; sourceTree = ""; }; + BF0D1DC6BF577BEA4933CC9E9904D5E7 /* NSSlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSSlider+Rx.swift"; path = "RxCocoa/macOS/NSSlider+Rx.swift"; sourceTree = ""; }; + BFD49E72672C87106DCAACF65BA77F61 /* PassThroughOutputNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PassThroughOutputNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PassThroughOutputNode.swift"; sourceTree = ""; }; + BFD786257ABB39B40D70F3165D42C01F /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Sequence.swift; sourceTree = ""; }; + C052ECF294DA36289A931FCE885FCCE2 /* GradientFillRenderer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GradientFillRenderer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientFillRenderer.swift"; sourceTree = ""; }; + C0C51C8150CA22332D6DAC6B496EDF75 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + C2E159B34E820BB317F60272565E6888 /* Pods-sopt_29th_Assignment-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-sopt_29th_Assignment-frameworks.sh"; sourceTree = ""; }; + C3B13E7ED22E76C5EF80A1F86662E19D /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/DelaySubscription.swift; sourceTree = ""; }; + C3BFC79BAF981C0610BE473F2FC97028 /* UITextView+IBInspectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextView+IBInspectable.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+IBInspectable.swift"; sourceTree = ""; }; + C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Kingfisher; path = Kingfisher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C47E28487EDD76C42BA8438285F90A17 /* FillI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FillI.swift; path = "lottie-swift/src/Private/Model/ShapeItems/FillI.swift"; sourceTree = ""; }; + C4AA012F0B4AD6EDD134E7938E204847 /* TakeWithPredicate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWithPredicate.swift; path = RxSwift/Observables/TakeWithPredicate.swift; sourceTree = ""; }; + C506ECDECE2EF8C2FB2CCD2D763931DB /* RxCocoa.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.debug.xcconfig; sourceTree = ""; }; + C5A531C42A7843B362B37D3DC18E18EC /* ConstraintRelatableTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelatableTarget.swift; path = Source/ConstraintRelatableTarget.swift; sourceTree = ""; }; + C63608A86051287DCC19717603B2BF81 /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Take.swift; sourceTree = ""; }; + C70255F45E310C14D25E974842ACE0C9 /* Ellipse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Ellipse.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Ellipse.swift"; sourceTree = ""; }; + C7A8B74BEBC874E98F39F2E95F0E5A2E /* UIStepper+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIStepper+Rx.swift"; path = "RxCocoa/iOS/UIStepper+Rx.swift"; sourceTree = ""; }; + C7C6AA01643D62A174BC4D0FEE7347CC /* SkeletonView.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SkeletonView.modulemap; sourceTree = ""; }; + C8A5986178C2D57C6A6D36F0FBDA1536 /* PolygonNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PolygonNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/PolygonNode.swift"; sourceTree = ""; }; + C8F0BE0C794A61C7EB4634CDF63FCEA4 /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Sources/Moya/Image.swift; sourceTree = ""; }; + C9015A681DA4DF2A9AF382E9A5D3BCA4 /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + C97468661B020B68BD7AC08EAAA90D1E /* SkeletonTableViewProtocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonTableViewProtocols.swift; path = SkeletonViewCore/Sources/API/Collections/TableViews/SkeletonTableViewProtocols.swift; sourceTree = ""; }; + C97506E3F057F8206D153A604935B805 /* ObservableType+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+Extensions.swift"; path = "RxSwift/ObservableType+Extensions.swift"; sourceTree = ""; }; + C993FA1C50C448867D6FA9026008D4B0 /* Storage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Storage.swift; path = Sources/Cache/Storage.swift; sourceTree = ""; }; + C9FB3F0C1C99CBB4ABF104F8AC950FE0 /* RxCocoa.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCocoa.swift; path = RxCocoa/RxCocoa.swift; sourceTree = ""; }; + CAC7D9C80495BBF05241A594E6C87603 /* _RXKVOObserver.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXKVOObserver.m; path = RxCocoa/Runtime/_RXKVOObserver.m; sourceTree = ""; }; + CB0164FE6305B6D92B73DFD76AB7F27E /* UIDatePicker+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIDatePicker+Rx.swift"; path = "RxCocoa/iOS/UIDatePicker+Rx.swift"; sourceTree = ""; }; + CB3D0AD0E7F8C7B3D7C26CABDA7846D4 /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DefaultIfEmpty.swift; path = RxSwift/Observables/DefaultIfEmpty.swift; sourceTree = ""; }; + CC5618864BECF00765464BFADD6D457E /* Materialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Materialize.swift; path = RxSwift/Observables/Materialize.swift; sourceTree = ""; }; + CC6E46E41581F6F1F6C6898DD24FD7EB /* LRUAnimationCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LRUAnimationCache.swift; path = "lottie-swift/src/Public/AnimationCache/LRUAnimationCache.swift"; sourceTree = ""; }; + CC949D9FB9157BF3A9C28C3CA361F44C /* _RXDelegateProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXDelegateProxy.h; path = RxCocoa/Runtime/include/_RXDelegateProxy.h; sourceTree = ""; }; + CC950DA283FF7D67AD9F5BB2852CEC51 /* Then-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Then-umbrella.h"; sourceTree = ""; }; + CCCF394F33FE3DF08000C2539A447036 /* ListPlaceholder.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = ListPlaceholder.modulemap; sourceTree = ""; }; + CD14B52B0A8703B45487AEE16E0D0AFE /* SkeletonView-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SkeletonView-dummy.m"; sourceTree = ""; }; + CD5BC5C7839120A1952E14BD41DC492A /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxRelay/Observable+Bind.swift"; sourceTree = ""; }; + CD6F904BE916FF77393166233CC2F108 /* ShapeContainerLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShapeContainerLayer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeContainerLayer.swift"; sourceTree = ""; }; + CD80162871DEA2C720EE5B7E21D17C19 /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/AddRef.swift; sourceTree = ""; }; + CD891281D4AE67F534654AC87653323E /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + CDC8C1E54D1F3A8B5CAC89FFFF6A3F80 /* SkeletonView */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SkeletonView; path = SkeletonView.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + CEC45818B7595FAE44DBD16AA13C3096 /* Swizzling.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Swizzling.swift; path = SkeletonViewCore/Sources/Internal/Helpers/Swizzling.swift; sourceTree = ""; }; + CFBF22ADF874AFE81EF80D81FD0F1D03 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + CFEF22F3B4602DC87F04B456C1EE28D2 /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + CFF0769755F5BA666BB460EFCB21376E /* LayerModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayerModel.swift; path = "lottie-swift/src/Private/Model/Layers/LayerModel.swift"; sourceTree = ""; }; + D03B4C2B16C9EF8A9E6B858BBCE8BF5A /* MathKit.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MathKit.swift; path = "lottie-swift/src/Private/Utility/Extensions/MathKit.swift"; sourceTree = ""; }; + D220985C78D75C384CDF8B81DB6B3D91 /* FillRenderer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FillRenderer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/FillRenderer.swift"; sourceTree = ""; }; + D2516CD94F1705F41F9E9975E40EA932 /* UITableView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITableView+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+Extensions.swift"; sourceTree = ""; }; + D2FD251C9AE8976588211B879701AFB3 /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + D3018780118D223690C258E639C92C46 /* BehaviorRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorRelay.swift; path = RxRelay/BehaviorRelay.swift; sourceTree = ""; }; + D36F1A384BC0E8912C9656D9E9FC32E1 /* UICollectionView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+Rx.swift"; path = "RxCocoa/iOS/UICollectionView+Rx.swift"; sourceTree = ""; }; + D483C06CDB9E8C25AF3499A532E7326C /* AnimationSubview.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationSubview.swift; path = "lottie-swift/src/Public/iOS/AnimationSubview.swift"; sourceTree = ""; }; + D50E0E8195DD834A2F4829C5EAEBA725 /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Source/ConstraintMaker.swift; sourceTree = ""; }; + D54C98DE7CEBB2D8F1131C7B50E7FD04 /* SolidCompositionLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SolidCompositionLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/SolidCompositionLayer.swift"; sourceTree = ""; }; + D5BEB05D94BDF212CDD826BE2A283F2E /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/SubscribeOn.swift; sourceTree = ""; }; + D5D4436D14D000A1E81E60708A232A60 /* ConstraintLayoutGuideDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuideDSL.swift; path = Source/ConstraintLayoutGuideDSL.swift; sourceTree = ""; }; + D62EA072C6C22D3A5C278C866B397AD2 /* SectionedViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SectionedViewDataSourceType.swift; path = RxCocoa/Common/SectionedViewDataSourceType.swift; sourceTree = ""; }; + D6A7F9A69B7D9163B17A60B7AA14A78C /* RxPickerViewAdapter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewAdapter.swift; path = RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift; sourceTree = ""; }; + D6D3C1F9E5085E3C4B32CE68E6C6D5BF /* StringEncoding+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "StringEncoding+Alamofire.swift"; path = "Source/StringEncoding+Alamofire.swift"; sourceTree = ""; }; + D6D6B51E110B6440442F78F8CA9BADC9 /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; + D73F4F7EAF190B3B0E9D75100191A449 /* ObservableConvertibleType+Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Infallible.swift"; path = "RxSwift/Traits/Infallible/ObservableConvertibleType+Infallible.swift"; sourceTree = ""; }; + D780C8593D2E40CC0D3C2A64F34E17E0 /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + D7B6034196E136373C741FBCDB769798 /* UIView+CollectionSkeleton.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+CollectionSkeleton.swift"; path = "SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+CollectionSkeleton.swift"; sourceTree = ""; }; + D7D4209C642E4A22E0B375197F2EF315 /* Notification+SkeletonFlow.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Notification+SkeletonFlow.swift"; path = "SkeletonViewCore/Sources/API/FoundationExtensions/Notification+SkeletonFlow.swift"; sourceTree = ""; }; + D8B0FF0EDE8D0EF1213F63DD747002C2 /* RxCocoa.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.release.xcconfig; sourceTree = ""; }; + D94A28A6B8ADE4854BB40514512CBD9E /* Date+Dispatch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Date+Dispatch.swift"; path = "RxSwift/Date+Dispatch.swift"; sourceTree = ""; }; + D9569A95E5B6C6404B3DE7ADAC9DB01A /* CompoundBezierPath.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompoundBezierPath.swift; path = "lottie-swift/src/Private/Utility/Primitives/CompoundBezierPath.swift"; sourceTree = ""; }; + D95787CC4368F63D40C76E31152FB436 /* UIApplication+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIApplication+Rx.swift"; path = "RxCocoa/iOS/UIApplication+Rx.swift"; sourceTree = ""; }; + D9896557140AD1D536F8409779DBAEFF /* AnimationViewInitializers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationViewInitializers.swift; path = "lottie-swift/src/Public/Animation/AnimationViewInitializers.swift"; sourceTree = ""; }; + DA353CE7AE8D250EFA8C4A3247EB25C1 /* ShapeCompositionLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShapeCompositionLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/ShapeCompositionLayer.swift"; sourceTree = ""; }; + DA79228103DCF330C6CF010CF0F509B5 /* Color.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Color.swift; path = "lottie-swift/src/Public/Primitives/Color.swift"; sourceTree = ""; }; + DAE8E84076D904366DAFA886774421A5 /* RxSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.debug.xcconfig; sourceTree = ""; }; + DB2079BBB30ED62D51431C9765C830CC /* ConstraintMakerPriortizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerPriortizable.swift; path = Source/ConstraintMakerPriortizable.swift; sourceTree = ""; }; + DCC4D9306A4093C2303CE6A5013C8F4A /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxCocoa/Common/Observable+Bind.swift"; sourceTree = ""; }; + DCF4EDC3F12B4511CA85D4FC7A5911E1 /* AnimatorNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatorNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Protocols/AnimatorNode.swift"; sourceTree = ""; }; + DD6C51736CC8C421D1FF2F68EFD04B85 /* ShapeItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShapeItem.swift; path = "lottie-swift/src/Private/Model/ShapeItems/ShapeItem.swift"; sourceTree = ""; }; + DD8BC706C48603A873CD59F14C5EF00B /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/OperationQueue+Alamofire.swift"; sourceTree = ""; }; + DE19B39C1F7D2C6F8EA095F0F0DC429F /* Kingfisher.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.release.xcconfig; sourceTree = ""; }; + DE387A021380A1F97903F86356357253 /* Task.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Task.swift; path = Sources/Moya/Task.swift; sourceTree = ""; }; + DE55C5E6AA523AFA73EC2D83A4E177D5 /* RxTextViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift; sourceTree = ""; }; + E05745650ABE7B996F364774222E1168 /* RequestTypeWrapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTypeWrapper.swift; path = Sources/Moya/RequestTypeWrapper.swift; sourceTree = ""; }; + E0B2731182FB5F0FFA7F5D229694668A /* RxSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.release.xcconfig; sourceTree = ""; }; + E0D608D68469ACC4C3385FD091BBF95D /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + E0E8F0EF266C9F823732B3056F3ED8ED /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + E19374B974D6A632F58ABEF0553D5B2F /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftyJSON; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E2975BFFB1283CF80FB0ECC05E969690 /* SkeletonType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonType.swift; path = SkeletonViewCore/Sources/API/Models/SkeletonType.swift; sourceTree = ""; }; + E298B1AD2B044011B7A989681F2936AF /* Constraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Constraint.swift; path = Source/Constraint.swift; sourceTree = ""; }; + E2D3732B62EC18E4CB2D210C68F41BE4 /* Pods-sopt_29th_Assignment-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-sopt_29th_Assignment-acknowledgements.markdown"; sourceTree = ""; }; + E303F3D83643F01CB24EE4934852916F /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + E378619273CDCD4DFAF4A5E807226744 /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + E45508CEF09B7205462B0A96CBD68DEE /* LayoutConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraintItem.swift; path = Source/LayoutConstraintItem.swift; sourceTree = ""; }; + E459B51C1885C4A8868D872E8BBD33CD /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + E46E04ECE7C5DC3EDC3C423924255D42 /* SkeletonTransitionStyle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonTransitionStyle.swift; path = SkeletonViewCore/Sources/API/Models/SkeletonTransitionStyle.swift; sourceTree = ""; }; + E50D72CF25FF13AA891A3D3EB0801783 /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + E5466629AEF3C4F485F46A299FE40ADA /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + E599302821C7078A5576C80BE9164259 /* RxCocoa-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxCocoa-Info.plist"; sourceTree = ""; }; + E635C61C9A23D4E53936282C66E79876 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/CachedResponseHandler.swift; sourceTree = ""; }; + E64F20DBFC58C1AB19FAAA4D16B19738 /* KVORepresentable+CoreGraphics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+CoreGraphics.swift"; path = "RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift"; sourceTree = ""; }; + E65F27B5F5507A9C1200A5BA6654B668 /* lottie-ios.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "lottie-ios.release.xcconfig"; sourceTree = ""; }; + E84906E7CC87F8BCFAE71AF108F1777E /* UILabel+SKExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILabel+SKExtensions.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+SKExtensions.swift"; sourceTree = ""; }; + E86354E64FA98EDE3E66839D9D8C9689 /* ImageDownloader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloader.swift; path = Sources/Networking/ImageDownloader.swift; sourceTree = ""; }; + E86E84B8E69882F455368E223F2A0927 /* SkeletonCollectionDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonCollectionDataSource.swift; path = SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDataSource.swift; sourceTree = ""; }; + E8ABB4DA8734B11EC34DA694E8CADCB8 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + E9077F9703C9F2AF9FBCCEB58C2C8C8B /* Moya.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Moya.debug.xcconfig; sourceTree = ""; }; + E98C006640C2FDCDAD55CA9CA1801605 /* KeyframeExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeyframeExtensions.swift; path = "lottie-swift/src/Private/Utility/Interpolatable/KeyframeExtensions.swift"; sourceTree = ""; }; + EA2D17E3F21BC2BBF052D1EC33D995DF /* UITabBarController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBarController+Rx.swift"; path = "RxCocoa/iOS/UITabBarController+Rx.swift"; sourceTree = ""; }; + EA50B9E5875D7540898597072A675557 /* ProcessInfo+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ProcessInfo+Extensions.swift"; path = "SkeletonViewCore/Sources/Internal/FoundationExtensions/ProcessInfo+Extensions.swift"; sourceTree = ""; }; + EA9B22BE2DA7ABC11AB8EF2A3D7C0BE0 /* AnimationImageProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationImageProvider.swift; path = "lottie-swift/src/Public/ImageProvider/AnimationImageProvider.swift"; sourceTree = ""; }; + EB3646BC16DDD6CC7E44EABA6B58C12F /* UIButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Rx.swift"; path = "RxCocoa/iOS/UIButton+Rx.swift"; sourceTree = ""; }; + EB4D150E2481BC5A0BF7A81282C2DBD6 /* AnyValueProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyValueProvider.swift; path = "lottie-swift/src/Public/DynamicProperties/AnyValueProvider.swift"; sourceTree = ""; }; + EBA5958B85EB0C407E6F8EF90D38FD5F /* ImageDataProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDataProcessor.swift; path = Sources/Networking/ImageDataProcessor.swift; sourceTree = ""; }; + EBE2CB20E4A11173FDEFBFD41F42F39D /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = RxRelay/Utils.swift; sourceTree = ""; }; + EBFD7FB4845277FFA9666FDEF11DF965 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + EC4A56E2A6E5F31A3C5F7289B79FD61B /* ValidationType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ValidationType.swift; path = Sources/Moya/ValidationType.swift; sourceTree = ""; }; + EC6E0F0D4A9AB5A9CF292BA58D1C9B2E /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + ECAA3D71D0B3875B94B4A632D9A2654D /* UIColorExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = UIColorExtension.swift; path = "lottie-swift/src/Public/iOS/UIColorExtension.swift"; sourceTree = ""; }; + ECF872CAA95230C7E18A18B762F9204A /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + ED682ADC810B7280D3DCA0D01A11CA3E /* 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 = ""; }; + ED7660BAC6E4C3F93494EBA47017B0A4 /* RxCollectionViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift; sourceTree = ""; }; + EDC82EB5069A011CA73BE1218B6698E9 /* RxSearchControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift; sourceTree = ""; }; + EDE9FE7450171136DE2AC1641634C489 /* 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 = ""; }; + EE117BBAB45229F7D3240A99FD8D2275 /* SkeletonTextNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonTextNode.swift; path = SkeletonViewCore/Sources/Internal/SkeletonExtensions/SkeletonTextNode.swift; sourceTree = ""; }; + EE21E076DA1CB81D248C4EC102DE5C52 /* Trim.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Trim.swift; path = "lottie-swift/src/Private/Model/ShapeItems/Trim.swift"; sourceTree = ""; }; + EE3DF2FB46BC58BC124C4CB365639907 /* ImageTransition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageTransition.swift; path = Sources/Image/ImageTransition.swift; sourceTree = ""; }; + EE694AAA0AB777F54457592C110B14EE /* GIFAnimatedImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GIFAnimatedImage.swift; path = Sources/Image/GIFAnimatedImage.swift; sourceTree = ""; }; + EE884D500D9139650D8E47EB891A17F2 /* InvertedMatteLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvertedMatteLayer.swift; path = "lottie-swift/src/Private/LayerContainers/Utility/InvertedMatteLayer.swift"; sourceTree = ""; }; + EF01F6EF733E1CA24A3DB61B34B8D1F4 /* SnapKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-umbrella.h"; sourceTree = ""; }; + EF25D6E0F21F2010AED7C8FFBB456444 /* _RXDelegateProxy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXDelegateProxy.m; path = RxCocoa/Runtime/_RXDelegateProxy.m; sourceTree = ""; }; + EF430063AF43D273608BD10FF1719F05 /* ReplayRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplayRelay.swift; path = RxRelay/ReplayRelay.swift; sourceTree = ""; }; + EF5F0433C5B5A2FDCD09A81C569C081F /* Resource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resource.swift; path = Sources/General/ImageSource/Resource.swift; sourceTree = ""; }; + EFC04AD25FB1DE14357C0CD2A244FCE1 /* ObservableConvertibleType+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Driver.swift"; path = "RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift"; sourceTree = ""; }; + F066C45D5BADC84EDB0EE2E961787719 /* Enumerated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Enumerated.swift; path = RxSwift/Observables/Enumerated.swift; sourceTree = ""; }; + F0A389573E7C58DCFE123C674C78E89D /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Sources/Utility/Result.swift; sourceTree = ""; }; + F0B7F04DEBC34B16DE6AF03596E35556 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Merge.swift; sourceTree = ""; }; + F0F310186ED318969FC8006B3056F8C7 /* AnimatorNodeDebugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatorNodeDebugging.swift; path = "lottie-swift/src/Private/Utility/Debugging/AnimatorNodeDebugging.swift"; sourceTree = ""; }; + F23704FF9C44B7431AE73A27EEDDA236 /* Moya-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Moya-umbrella.h"; sourceTree = ""; }; + F2399A067CF54CE64CA10F9123F63F19 /* StrokeRenderer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StrokeRenderer.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/StrokeRenderer.swift"; sourceTree = ""; }; + F2AD080F3651EBED22DAC46B01E5DAD7 /* UIView+IBInspectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+IBInspectable.swift"; path = "SkeletonViewCore/Sources/API/UIKitExtensions/UIView+IBInspectable.swift"; sourceTree = ""; }; + F3067BD7A13A4D8688FD0E78BBA46A35 /* BehaviorRelay+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BehaviorRelay+Driver.swift"; path = "RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift"; sourceTree = ""; }; + F31EAC752A1F003ACD8F94AE101F1A58 /* KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KVORepresentable.swift; path = RxCocoa/Foundation/KVORepresentable.swift; sourceTree = ""; }; + F3582E176B7730B8D517496A78618266 /* UISegmentedControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISegmentedControl+Rx.swift"; path = "RxCocoa/iOS/UISegmentedControl+Rx.swift"; sourceTree = ""; }; + F3E6345266B4A99F5832756CE9B23BCC /* MoyaError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MoyaError.swift; path = Sources/Moya/MoyaError.swift; sourceTree = ""; }; + F422053BDBB0BDDDDD82DFAE5FDF6CFE /* TextAnimator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextAnimator.swift; path = "lottie-swift/src/Private/Model/Text/TextAnimator.swift"; sourceTree = ""; }; + F43F0A34089FF64327D57D242A57BF6C /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = Sources/Image/Filter.swift; sourceTree = ""; }; + F48EE44D15434B52A20435C8D55CC02B /* ListPlaceholder-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "ListPlaceholder-dummy.m"; sourceTree = ""; }; + F55A505B6DD9C82DC3280E5B748463C9 /* ImageDrawing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDrawing.swift; path = Sources/Image/ImageDrawing.swift; sourceTree = ""; }; + F5609126CF5995535E9EA2DC866B0E36 /* Recoverable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Recoverable.swift; path = SkeletonViewCore/Sources/Internal/SkeletonExtensions/Recoverable.swift; sourceTree = ""; }; + F5E0E1270F1DC7CA9ACC0415782C2011 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + F5FAB1F918FD5B82BD0664038EE47057 /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + F68B9B5FD094181660E4555CCE82A897 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + F75A90C2F8242F9556979A6FA039CA1D /* KeyframeInterpolator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeyframeInterpolator.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/KeyframeInterpolator.swift"; sourceTree = ""; }; + F7918CA582A9312F6A2A6C43295B7F80 /* URL+Moya.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URL+Moya.swift"; path = "Sources/Moya/URL+Moya.swift"; sourceTree = ""; }; + F8086AFD18868DE3546DA9099D9320BF /* LayerTextProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayerTextProvider.swift; path = "lottie-swift/src/Private/LayerContainers/Utility/LayerTextProvider.swift"; sourceTree = ""; }; + F8155266263D676CBE1AA5434A651904 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Error.swift; sourceTree = ""; }; + F82ADDF5EFB61F235D5A96300B18D0D3 /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Range.swift; sourceTree = ""; }; + F8E66D8E800FF87FB95483E022E5BFE3 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + F8ECFAE0BD799A0E0CF48BA1E63F906A /* SkeletonAppearance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonAppearance.swift; path = SkeletonViewCore/Sources/API/Appearance/SkeletonAppearance.swift; sourceTree = ""; }; + F908E30565F6F797BDAC18B70C873EC0 /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Window.swift; sourceTree = ""; }; + F91DBDE07A61124CA56D3DF66AC9DE34 /* LayerFontProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayerFontProvider.swift; path = "lottie-swift/src/Private/LayerContainers/Utility/LayerFontProvider.swift"; sourceTree = ""; }; + F9DA97D80CD7B83E04907CD379D46AD0 /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + FA1D48C657C7350A77938B94F6F71C48 /* SkeletonCollectionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkeletonCollectionDelegate.swift; path = SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDelegate.swift; sourceTree = ""; }; + FA3E1896A379203483554C6A1C48253B /* KVORepresentable+Swift.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+Swift.swift"; path = "RxCocoa/Foundation/KVORepresentable+Swift.swift"; sourceTree = ""; }; + FB156F61588D89617814BA094C4E1C24 /* AnimationTime.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimationTime.swift; path = "lottie-swift/src/Public/Primitives/AnimationTime.swift"; sourceTree = ""; }; + FB80662DC88930A808766D75B58B8E0F /* AVAssetImageDataProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AVAssetImageDataProvider.swift; path = Sources/General/ImageSource/AVAssetImageDataProvider.swift; sourceTree = ""; }; + FBC804AD1464BA2566282D04FC227C34 /* ShareReplayScope.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplayScope.swift; path = RxSwift/Observables/ShareReplayScope.swift; sourceTree = ""; }; + FC30D3FB284CDC3251E256458BAD5B33 /* ConstraintMakerExtendable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerExtendable.swift; path = Source/ConstraintMakerExtendable.swift; sourceTree = ""; }; + FC7535C78F2E9F180285E6E788E8B8DC /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + FC7A24FE2D50C8D81A33DAC6B009D5F6 /* ConstraintLayoutGuide.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuide.swift; path = Source/ConstraintLayoutGuide.swift; sourceTree = ""; }; + FC9C172FF95F6BCF1D316CE2E1F746C9 /* ImageCompositionLayer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageCompositionLayer.swift; path = "lottie-swift/src/Private/LayerContainers/CompLayers/ImageCompositionLayer.swift"; sourceTree = ""; }; + FCB00308A3486A03F452853D6A4B9076 /* Signal+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Signal+Subscription.swift"; path = "RxCocoa/Traits/Signal/Signal+Subscription.swift"; sourceTree = ""; }; + FD7AF050C7F66F9596DB3250B26EF760 /* 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; }; + FD902B8A405D4C1EB6494D97EC73FFE9 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + FE1ABC46825D3DC37B743CBE3C36B504 /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + FE3A4F198D553449CE8B70E24399F16C /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Do.swift; sourceTree = ""; }; + FE73DD65AC9269C15438EB353DFE71B1 /* UIBarButtonItem+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIBarButtonItem+Rx.swift"; path = "RxCocoa/iOS/UIBarButtonItem+Rx.swift"; sourceTree = ""; }; + FE837EB01476AC48BAA57CE0FE92E4BA /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Debug.swift; sourceTree = ""; }; + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxRelay; path = RxRelay.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FF9ECF5DC98A260F6CDB707618BA0859 /* ImageFormat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageFormat.swift; path = Sources/Image/ImageFormat.swift; sourceTree = ""; }; + FF9FEFFA9B7D920FE0827A598FAB6C8E /* GroupInterpolator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupInterpolator.swift; path = "lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/GroupInterpolator.swift"; sourceTree = ""; }; + FFB0D21E5795488A0BB324C98CB416AD /* RectNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RectNode.swift; path = "lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/RectNode.swift"; sourceTree = ""; }; + FFB4AB361BD8533DC4A1F3D99015F9DD /* NotificationCenter+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NotificationCenter+Rx.swift"; path = "RxCocoa/Foundation/NotificationCenter+Rx.swift"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0922C932A8B237B74FD05C0F5F34D3C8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E027CD0A35229E2E0333ACE3BFF3B20 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33B02A89A0936F35670F8497BC396EDE /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5A3D602684104FE1F41A6BF7ABAB641C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3977393A21672F0FBC6F1193739E0D15 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 325CCDB295FFA016638075B5D2CEDD5C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 39D530C2A3085A1033683EC9AE0BC313 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 33F86FAB918B148A63A1575667F9B570 /* CFNetwork.framework in Frameworks */, + 9C0BE8FA0030B2BC1DF7C159FA059389 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4A77A298FBB428EC655B61E5E2F3D300 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A3A65AC84DB2B13043BF9BB828C98F94 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4DAD51760C3A529B5ACA9477FDA8E31A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 04B2DDDF8C3C5DAE8952E85BD4ECF6CE /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 79C6F6E48501AE398E29FE88A9E18B4D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2E69464EBC0B563DF853D07B17E561EB /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 90CBA3AD7F41BA5D0202C65BCE1D4E9C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 170ACEF678D7B6AABA4CD5A396E25C70 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 95AE726CE354B76A6E5BE28655B6498D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 81D31A9220A1D5D0800757FD461F0CE1 /* CoreGraphics.framework in Frameworks */, + AA5188D20EF55F511E77DC2BEF9E7F37 /* Foundation.framework in Frameworks */, + 88B2B239168C5027BC6852A05C0F02D1 /* QuartzCore.framework in Frameworks */, + 7260A7AF7CAC80E1C485936F08BD5D75 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9B30433E568C40FCE04D5188A9715448 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + CCA22C9F421C9E8C13009947816D8C82 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A9B7DA8193E441061CF2888B58990357 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 09672BF940608C6A8A93C25441AABA14 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B110F4A89B80E9EA29019FC5CA16B326 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5E3BF2B719B3A034C173D16B3ABF682E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EED2AC90E1553CF9889DB6D723EAF5D1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 26C1F54FCAFA5BD581D973CD73E7B70C /* Accelerate.framework in Frameworks */, + 0C80F358772C9985C89D6F323EE7D8DB /* CFNetwork.framework in Frameworks */, + 7425A145B15B33A92BB41EAE2CC019CE /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 07C0F4E6ADA7F7ABED8E976831FCC4F8 /* Moya */ = { + isa = PBXGroup; + children = ( + 742CE11B6D9F4ACB3D8A3364BEC2995D /* Core */, + A30EA3DD1D2499034ABF28CB6EF90CC9 /* Support Files */, + ); + name = Moya; + path = Moya; + sourceTree = ""; + }; + 19CADEFFBF295878025EBCBF79C956D7 /* Support Files */ = { + isa = PBXGroup; + children = ( + 69F3FFEF813BEAA0DD193DA5CF47F469 /* RxSwift.modulemap */, + CFEF22F3B4602DC87F04B456C1EE28D2 /* RxSwift-dummy.m */, + 192BBFC4C994D61C5F81913AA5E31305 /* RxSwift-Info.plist */, + FE1ABC46825D3DC37B743CBE3C36B504 /* RxSwift-prefix.pch */, + 13AE6E53A98B27F06918950C3CE6FAFB /* RxSwift-umbrella.h */, + DAE8E84076D904366DAFA886774421A5 /* RxSwift.debug.xcconfig */, + E0B2731182FB5F0FFA7F5D229694668A /* RxSwift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + 1F6DE56E6941409EF1E6A7194A5B5516 /* Alamofire */ = { + isa = PBXGroup; + children = ( + E0E8F0EF266C9F823732B3056F3ED8ED /* AFError.swift */, + 4348EC0093037491BEA652EBE5DCA807 /* Alamofire.swift */, + 0A293AC4105C62BC723877D10AE638D4 /* AlamofireExtended.swift */, + B41AEA65C66E7ACEA41AD1C1F3C68F20 /* AuthenticationInterceptor.swift */, + E635C61C9A23D4E53936282C66E79876 /* CachedResponseHandler.swift */, + 7AD41A4730360AF228ACA97E7BCE4212 /* Combine.swift */, + 1691F065506461EF86886015CD5553E8 /* DispatchQueue+Alamofire.swift */, + 3284940F014301795A4E512B8488B45C /* EventMonitor.swift */, + 354FB31B9128687D8F619B708088196A /* HTTPHeaders.swift */, + 4701D61B9E8B58C7B8DE650388D62501 /* HTTPMethod.swift */, + 681C7085B058D412CDBAE81D6CC3590F /* MultipartFormData.swift */, + 6C0EC79BB2684684092112E66097E51C /* MultipartUpload.swift */, + 6E21A1D9ABB6E3BF10CF6276800D7EAF /* NetworkReachabilityManager.swift */, + 944DA138D0F8B5754B4374EDCE6E9B0D /* Notifications.swift */, + DD8BC706C48603A873CD59F14C5EF00B /* OperationQueue+Alamofire.swift */, + 456259D8BA3A3A1A953B73B998EC12B9 /* ParameterEncoder.swift */, + F5E0E1270F1DC7CA9ACC0415782C2011 /* ParameterEncoding.swift */, + 246879F9E04EAD3592150755424A7EFC /* Protected.swift */, + 071821BE495DDE9F3FADFDBCE93FA4F2 /* RedirectHandler.swift */, + 3CB211AAE9491B71A132FC342B4CE0BD /* Request.swift */, + 2AF6124992AABDBAB9B673BD68F92F65 /* RequestInterceptor.swift */, + BC4858AAE41174640ADC6C4F4EBB738A /* RequestTaskMap.swift */, + E0D608D68469ACC4C3385FD091BBF95D /* Response.swift */, + F68B9B5FD094181660E4555CCE82A897 /* ResponseSerialization.swift */, + 3B4EAA7FDBF8CFE95F3696938910D562 /* Result+Alamofire.swift */, + 446E3EB3F699A644D3549F0D2657CB69 /* RetryPolicy.swift */, + B5CE0BDCFF01EB2384FC3A771ACD4E43 /* ServerTrustEvaluation.swift */, + B77B9A720BE238A674C1DABB07F5CD46 /* Session.swift */, + 14F87B9368AD2DD04C9404B2B7C3D990 /* SessionDelegate.swift */, + D6D3C1F9E5085E3C4B32CE68E6C6D5BF /* StringEncoding+Alamofire.swift */, + 8A75C74B3699B0CDC64C7C23892A9BA1 /* URLConvertible+URLRequestConvertible.swift */, + 8C3816D0BD55363234509538304F2C98 /* URLEncodedFormEncoder.swift */, + BEE5B6721BB2351DE21380FD23EFD7C6 /* URLRequest+Alamofire.swift */, + 5CF303356DC7A4D17A311EE4B8598B16 /* URLSessionConfiguration+Alamofire.swift */, + CFBF22ADF874AFE81EF80D81FD0F1D03 /* Validation.swift */, + 292405E769784E66F5EBE23B0D383310 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + 292405E769784E66F5EBE23B0D383310 /* Support Files */ = { + isa = PBXGroup; + children = ( + 61900EC8CBFE35E647E8EFF142E70217 /* Alamofire.modulemap */, + EBFD7FB4845277FFA9666FDEF11DF965 /* Alamofire-dummy.m */, + 01E132FE01A0EF89DAC22F0090579748 /* Alamofire-Info.plist */, + 812B2824CD60068C30219DE3B73F8FB0 /* Alamofire-prefix.pch */, + 7C55FC5EF514FB4258BC99DB4703D221 /* Alamofire-umbrella.h */, + 1C7BA86113D5C716B3A12925604B3936 /* Alamofire.debug.xcconfig */, + 1C861463227BAC0BB12CACF221FA5267 /* Alamofire.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 2990164D6C0BEE58B2259648D5579F79 /* Kingfisher */ = { + isa = PBXGroup; + children = ( + D860C3EF84A85851A9FA422862D510D3 /* Core */, + 7187A339559BC1392D0768F17AB3C65D /* Support Files */, + ); + name = Kingfisher; + path = Kingfisher; + sourceTree = ""; + }; + 32428F2F00E092141F4F3B966F8DDFC9 /* RxSwift */ = { + isa = PBXGroup; + children = ( + CD80162871DEA2C720EE5B7E21D17C19 /* AddRef.swift */, + 4CD09121D5921CA90BF4362D690AF12A /* Amb.swift */, + C9015A681DA4DF2A9AF382E9A5D3BCA4 /* AnonymousDisposable.swift */, + A4C19766D6627B764323CAA1F56C4BE8 /* AnonymousObserver.swift */, + 1AEAC5C3F987A9644AD6C9C04B25B1A2 /* AnyObserver.swift */, + 08EFB0508FB59B5A9CC9C10BFBB5D669 /* AsMaybe.swift */, + 7520D72882C54D369DC3AB4761527968 /* AsSingle.swift */, + 13F92A11E3FCF33BA60FE05727A0BEDA /* AsyncLock.swift */, + 5E5F0AEB88A75A924160B8991DC64A4D /* AsyncSubject.swift */, + 20CD4FEA06271824B989A8EDE3893D39 /* AtomicInt.swift */, + 42C2D48C54A7871FC049E1A1E12314BB /* Bag.swift */, + 5AED798F345A7AB54BF82C5FD690CEEC /* Bag+Rx.swift */, + 48FAA3D40453DEB7997FAD69B09D646A /* BehaviorSubject.swift */, + E303F3D83643F01CB24EE4934852916F /* BinaryDisposable.swift */, + B833736B901BD30A23F443B52BCDE473 /* Binder.swift */, + E378619273CDCD4DFAF4A5E807226744 /* BooleanDisposable.swift */, + AD3D6EEF925607AD0B298BEE42319A52 /* Buffer.swift */, + E8ABB4DA8734B11EC34DA694E8CADCB8 /* Cancelable.swift */, + 79CCBA90D8565C6D22EFAC3E476BAD52 /* Catch.swift */, + 2D2CE551669C63D2247F730227904BC1 /* CombineLatest.swift */, + 853087100942AF514143837601F12DCC /* CombineLatest+arity.swift */, + BB6402E753D04F905BC4852F64AF7029 /* CombineLatest+Collection.swift */, + 34A05C3B6C506CC2595668766B66335C /* CompactMap.swift */, + 504F6A77D82470D4C99C670B2C9F0049 /* Completable.swift */, + 01D392B16678AA170E4995C96EB4EC87 /* Completable+AndThen.swift */, + 08DCD01DA45EC603BA3469CB31065493 /* CompositeDisposable.swift */, + 0B692AA196B6AFE8904EB2BCD1F07359 /* Concat.swift */, + 0284223C1683F0B75775EB9666EAA694 /* ConcurrentDispatchQueueScheduler.swift */, + E19374B974D6A632F58ABEF0553D5B2F /* ConcurrentMainScheduler.swift */, + ECF872CAA95230C7E18A18B762F9204A /* ConnectableObservableType.swift */, + 25E58D99D7B2769C8099EB0C018414F4 /* Create.swift */, + E50D72CF25FF13AA891A3D3EB0801783 /* CurrentThreadScheduler.swift */, + D94A28A6B8ADE4854BB40514512CBD9E /* Date+Dispatch.swift */, + 39D7CBE018675DF98D1EEFB4F7070327 /* Debounce.swift */, + FE837EB01476AC48BAA57CE0FE92E4BA /* Debug.swift */, + 808B587D23A5746A071DBE671C0B134F /* Decode.swift */, + CB3D0AD0E7F8C7B3D7C26CABDA7846D4 /* DefaultIfEmpty.swift */, + 8635C303D5A4896131561341C8493289 /* Deferred.swift */, + 778BBEE465580922EF19056B1FB95575 /* Delay.swift */, + C3B13E7ED22E76C5EF80A1F86662E19D /* DelaySubscription.swift */, + 61AC97B1CC38C9AEF119A14A5E54D5E5 /* Dematerialize.swift */, + 3409FC3583B82BE7AE393910A5C75F5E /* DispatchQueue+Extensions.swift */, + 10E0EBA8A23A9FD3551DCF70CE32FB5A /* DispatchQueueConfiguration.swift */, + 8F69100E0147D6C4D38EDDD7A1E58A5E /* Disposable.swift */, + 353F2BD4A9347C8D3533715105EC244C /* Disposables.swift */, + 66FBA686CFD090AA2B166227E4ECF81E /* DisposeBag.swift */, + 4304FC34470876F5AE58F762218D8E27 /* DisposeBase.swift */, + 949BBB5ECE7B5436603B7FC04CF44AE3 /* DistinctUntilChanged.swift */, + FE3A4F198D553449CE8B70E24399F16C /* Do.swift */, + 87587A4BCD25F7ABE2B906B50D52E516 /* ElementAt.swift */, + 1090A2E25CADE447F0E441B7F86C09C4 /* Empty.swift */, + F066C45D5BADC84EDB0EE2E961787719 /* Enumerated.swift */, + F8155266263D676CBE1AA5434A651904 /* Error.swift */, + 683A06F221EAF470EDECF217893A1459 /* Errors.swift */, + 8A5C88CC7FE36F1A405C15CDFC255FCF /* Event.swift */, + 1FD05EBA82A3ECA1279623514C916302 /* Filter.swift */, + B3D31D5552712947DD6DD4DD6D381390 /* First.swift */, + A3FD5F1676F6BE15B29D02BACF63E175 /* Generate.swift */, + 2F50F7590F13C2FEC54F3A2AF039F1DD /* GroupBy.swift */, + A9967B03CCF1284AA798AE8C3724EAEA /* GroupedObservable.swift */, + 89C3D4B031C655927020FD3C14DDFCE3 /* HistoricalScheduler.swift */, + 7B46F7D182E6FCA5635A2BEA65BCF483 /* HistoricalSchedulerTimeConverter.swift */, + AC38F5AE52B4EEB7D3604228631C5672 /* ImmediateSchedulerType.swift */, + 97725CE91BDF719A6F66531F0753AE0A /* Infallible.swift */, + ED682ADC810B7280D3DCA0D01A11CA3E /* Infallible+CombineLatest+arity.swift */, + BB73A1C3B4A7F9EE2A1685D474B50FA1 /* Infallible+Create.swift */, + 5801960901D0BADB1E4BD40CA6C67C66 /* Infallible+Operators.swift */, + EDE9FE7450171136DE2AC1641634C489 /* Infallible+Zip+arity.swift */, + 1DDD5C32EEB0C67A01C78D27F8800267 /* InfiniteSequence.swift */, + B5893E2F6BDE1656D9E2AED1E55AE57B /* InvocableScheduledItem.swift */, + 93AF1A70F61D237BFA37E52EC09B3345 /* InvocableType.swift */, + 060D5947DF2A206EBACAC4D9141BA5C2 /* Just.swift */, + 0EFC2A7CCEE7FD68946B41699013C20C /* Lock.swift */, + 7C03C324DCEC33D1BCDC0F49FEA3BF5A /* LockOwnerType.swift */, + 968326A729170F8CF833DC5AE0E14E9D /* MainScheduler.swift */, + 4DDF961CC34E9D9CEC76F2A52AEA6708 /* Map.swift */, + CC5618864BECF00765464BFADD6D457E /* Materialize.swift */, + 5F5AE1F6568B946172123A13DD26E4AC /* Maybe.swift */, + F0B7F04DEBC34B16DE6AF03596E35556 /* Merge.swift */, + 78EE67455BC257C012D56E3CF4289753 /* Multicast.swift */, + 5CB3E26C685C33AAD94DDAC2A13DD470 /* Never.swift */, + 4A8C9E61C5B107DF52BFA41FF3621A6B /* NopDisposable.swift */, + 233C706C3317D2B175739DDCCCD493FA /* Observable.swift */, + E5466629AEF3C4F485F46A299FE40ADA /* ObservableConvertibleType.swift */, + D73F4F7EAF190B3B0E9D75100191A449 /* ObservableConvertibleType+Infallible.swift */, + F9DA97D80CD7B83E04907CD379D46AD0 /* ObservableType.swift */, + C97506E3F057F8206D153A604935B805 /* ObservableType+Extensions.swift */, + B63B29F6B0F59E6DE8F568AEB205CBF1 /* ObservableType+PrimitiveSequence.swift */, + 391AC99DE47C2D48F06B251895B9C015 /* ObserveOn.swift */, + C0C51C8150CA22332D6DAC6B496EDF75 /* ObserverBase.swift */, + D2FD251C9AE8976588211B879701AFB3 /* ObserverType.swift */, + F8E66D8E800FF87FB95483E022E5BFE3 /* OperationQueueScheduler.swift */, + 5519A274A3A23AC682FF2BCC079B33DB /* Optional.swift */, + FD902B8A405D4C1EB6494D97EC73FFE9 /* Platform.Darwin.swift */, + FC7535C78F2E9F180285E6E788E8B8DC /* Platform.Linux.swift */, + 8E7ACE526EED15B718B4B164D40F7834 /* PrimitiveSequence.swift */, + 28C41248617CC832243457A5AE5A72FD /* PrimitiveSequence+Zip+arity.swift */, + 68424BAC950DB41E65054A2379D3970E /* PriorityQueue.swift */, + 45FEFE36956CF674FB10839C7EC507D3 /* Producer.swift */, + B04EFFB7E4883C11B13334C7E9B5D414 /* PublishSubject.swift */, + 1E0771F18B5F0586F32DDA90BCC27E7A /* Queue.swift */, + F82ADDF5EFB61F235D5A96300B18D0D3 /* Range.swift */, + 7251F730820CB2440AE47178A2E05925 /* Reactive.swift */, + 94144BB3737DFCA50D6CBDA921B288CB /* RecursiveLock.swift */, + F5FAB1F918FD5B82BD0664038EE47057 /* RecursiveScheduler.swift */, + B93578502709168269517790C6A933EA /* Reduce.swift */, + EC6E0F0D4A9AB5A9CF292BA58D1C9B2E /* RefCountDisposable.swift */, + 9C3783A8A3F5F65A635AF839F252AA0F /* Repeat.swift */, + 93BF6B791D497D88399007FB4AD48570 /* ReplaySubject.swift */, + BC943D97ED350208583B6BA939BB98D2 /* RetryWhen.swift */, + 788E707B4401762A4BA111312D0317F9 /* Rx.swift */, + 2F6F84E9FDFB7A1AD3349F7E93194D7C /* RxMutableBox.swift */, + B58CBA3AA57CA05996897232EC752A91 /* Sample.swift */, + 09693AC1A1B3A18F9FA52A7D51DD3971 /* Scan.swift */, + 5571BC824BE85B8DEDD7C5FB972803F1 /* ScheduledDisposable.swift */, + 4826213952103BBABC0B948C3A1540D7 /* ScheduledItem.swift */, + 7ECE50328AD6B4F70001FD7342D1AC24 /* ScheduledItemType.swift */, + 25EEA2EDD084B84C71D534C5172BA41F /* SchedulerServices+Emulation.swift */, + 4D7261008A0E169AEAF3B737D85A02AE /* SchedulerType.swift */, + BFD786257ABB39B40D70F3165D42C01F /* Sequence.swift */, + 404BCF6A27A2F02EC5B5E6585FAC3202 /* SerialDispatchQueueScheduler.swift */, + 5E30CE980C3C04353853E2AF1A39C145 /* SerialDisposable.swift */, + FBC804AD1464BA2566282D04FC227C34 /* ShareReplayScope.swift */, + 964824591CA2DE2B4FB7B566519B80FE /* Single.swift */, + A2A62ACB1FA99BED968D941C78B678FE /* SingleAssignmentDisposable.swift */, + 10C11E72EAF8B195DDB1928BD42D7ABF /* SingleAsync.swift */, + 2D758A0D185CC311BCFAF0FF0CD32C44 /* Sink.swift */, + 1D0751A1FB0F9C0431EFE99C2219FA91 /* Skip.swift */, + 72D98974480C49492DA09E6CDDE9A7FE /* SkipUntil.swift */, + 4764E8A7D0A60A2B1959E62D5EE630A8 /* SkipWhile.swift */, + 71D6937F919B2CBC07245D5F1D061843 /* StartWith.swift */, + CD891281D4AE67F534654AC87653323E /* SubjectType.swift */, + D5BEB05D94BDF212CDD826BE2A283F2E /* SubscribeOn.swift */, + 99430E20314FA52AE89A8E413268C90D /* SubscriptionDisposable.swift */, + 79CCD96014790B1C04490CC18D92C41A /* SwiftSupport.swift */, + BBE5754AAA9F6ACD8F57F8DD39D05E07 /* Switch.swift */, + 1A31C9A5DE11AFE106E3B36938178387 /* SwitchIfEmpty.swift */, + 6B6496DFF2CE2431D9089085DA8B38A8 /* SynchronizedDisposeType.swift */, + 9EE72C751257B211AA10C4EBA38EA378 /* SynchronizedOnType.swift */, + 3485652A97F1EAFC84E390F4CDAF13B3 /* SynchronizedUnsubscribeType.swift */, + 003C339CFDEA10043C899DC5C6E3B963 /* TailRecursiveSink.swift */, + C63608A86051287DCC19717603B2BF81 /* Take.swift */, + 31FD46ECE4E238AEABFE3EA76B9F6F66 /* TakeLast.swift */, + C4AA012F0B4AD6EDD134E7938E204847 /* TakeWithPredicate.swift */, + 2DB14BBD59D28FED37F0A07C663453D3 /* Throttle.swift */, + 61BCD1938C7E8E565B52A5E0BE04084C /* Timeout.swift */, + 37E494D03710E8D813D8044D134F16C7 /* Timer.swift */, + 23AD8F2A2CD08E671C3FD51565E63057 /* ToArray.swift */, + B484FCBAC5748316D28EE3BB31442683 /* Using.swift */, + 8D168476D52EFA1C2C2052BBFC538ED3 /* VirtualTimeConverterType.swift */, + 349681955FF4E7F5E8E163E05F167288 /* VirtualTimeScheduler.swift */, + F908E30565F6F797BDAC18B70C873EC0 /* Window.swift */, + 7A6BDC77EAEBCA14DA677FCC3FE310A9 /* WithLatestFrom.swift */, + 65DAAFBCF14E6735F9006742B5A0B053 /* WithUnretained.swift */, + 11DE39107577F3D7973D85C19DC2DC4F /* Zip.swift */, + 6994931C5C5549C924814ED0DECA00A0 /* Zip+arity.swift */, + 64592E246FA7D5B9EF0A591746D1F2EC /* Zip+Collection.swift */, + 19CADEFFBF295878025EBCBF79C956D7 /* Support Files */, + ); + name = RxSwift; + path = RxSwift; + sourceTree = ""; + }; + 3526E9C6D178E5274DD4589070F760C5 /* iOS */ = { + isa = PBXGroup; + children = ( + 7DCF16C57C75BF50B3F5CCB76DD8EFB5 /* Accelerate.framework */, + FD7AF050C7F66F9596DB3250B26EF760 /* CFNetwork.framework */, + 0879FB18BD6A133DD98B8EF43021FF20 /* CoreGraphics.framework */, + 6B93B89B4A289CE40673582EAB3EEABF /* Foundation.framework */, + 40D34EBDA2B1EA531EE140BE3FA0AAD9 /* QuartzCore.framework */, + 69B2B19CD8426F161013829AABAA4A64 /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 35E1C1AB9D4FF8D2C8A6A394634C24B2 /* RxCocoa */ = { + isa = PBXGroup; + children = ( + 16AFD5E477C7973D1144A718B6373568 /* _RX.h */, + B958D6DAA7CC8E707A980E42F41B9E7B /* _RX.m */, + CC949D9FB9157BF3A9C28C3CA361F44C /* _RXDelegateProxy.h */, + EF25D6E0F21F2010AED7C8FFBB456444 /* _RXDelegateProxy.m */, + 301AFE63C3AB09BD6D7E866765FB708D /* _RXKVOObserver.h */, + CAC7D9C80495BBF05241A594E6C87603 /* _RXKVOObserver.m */, + 5D0D31D7FB33943C68B067F93D7639D2 /* _RXObjCRuntime.h */, + 44F6BDD6C63042363FABEB4018BD511F /* _RXObjCRuntime.m */, + E459B51C1885C4A8868D872E8BBD33CD /* Bag.swift */, + F3067BD7A13A4D8688FD0E78BBA46A35 /* BehaviorRelay+Driver.swift */, + 822AD736BB3D75AC5047E27811EC926F /* ControlEvent.swift */, + 97F8A41D5BE85EF128CB8F2401A2E9DB /* ControlEvent+Driver.swift */, + 1A39BB18953213AFF2BE09075C24C3A2 /* ControlEvent+Signal.swift */, + 4C4579507D0921EBF1E697F281041418 /* ControlProperty.swift */, + 89D812681CA39BEB09D4C419C19E684E /* ControlProperty+Driver.swift */, + 48C7604CA62FB6215DFBB6A7C45EDB5F /* ControlTarget.swift */, + 71933B6884EC0E04F1FB08D3D531237A /* DelegateProxy.swift */, + 59479749C35D07AD73D552FEF1A3F790 /* DelegateProxyType.swift */, + 08ACDB5C9A8DBE46151E7C196E1A8991 /* DispatchQueue+Extensions.swift */, + 7C201370A855FCF81DC8E1D8DA720491 /* Driver.swift */, + 552D72B0197B86C4795FDBC92B632740 /* Driver+Subscription.swift */, + 51BCE2958D21169BE85CC73B5D398D2C /* Infallible+Bind.swift */, + 62A531319033D427E8405BE7B48DFB62 /* InfiniteSequence.swift */, + 1AFC9C1750CAEF5B9D510B41F4CE71AC /* ItemEvents.swift */, + F31EAC752A1F003ACD8F94AE101F1A58 /* KVORepresentable.swift */, + E64F20DBFC58C1AB19FAAA4D16B19738 /* KVORepresentable+CoreGraphics.swift */, + FA3E1896A379203483554C6A1C48253B /* KVORepresentable+Swift.swift */, + FFB4AB361BD8533DC4A1F3D99015F9DD /* NotificationCenter+Rx.swift */, + BAD21644D07C588A6BB916B9CE6FADD7 /* NSButton+Rx.swift */, + 7928AE6F54492F85775B5EEDC096789C /* NSControl+Rx.swift */, + 4828B93FADCCFD4794B2484CAACCC552 /* NSObject+Rx.swift */, + 12437FDC5507B09A5086FBF896237734 /* NSObject+Rx+KVORepresentable.swift */, + 9FF3A9A33C900F71DA5EF5C29BE949A4 /* NSObject+Rx+RawRepresentable.swift */, + BF0D1DC6BF577BEA4933CC9E9904D5E7 /* NSSlider+Rx.swift */, + AE2F81EE0A1DEAFA1442491D488A81D9 /* NSTextField+Rx.swift */, + 7BEF0FAAC7C86B3C907BF5962D972DC3 /* NSTextStorage+Rx.swift */, + A13C79480FE01C9508D13C16018BEADA /* NSTextView+Rx.swift */, + 9B221BB5199889A8401D51EAAC1E618E /* NSView+Rx.swift */, + DCC4D9306A4093C2303CE6A5013C8F4A /* Observable+Bind.swift */, + EFC04AD25FB1DE14357C0CD2A244FCE1 /* ObservableConvertibleType+Driver.swift */, + 208E0A59F6812B839FEACDFDF42F6B01 /* ObservableConvertibleType+SharedSequence.swift */, + 0FD6FB7BB4200891D8DB64A315EFC273 /* ObservableConvertibleType+Signal.swift */, + 207831A8AE3036D49F36C140A5487C63 /* Platform.Darwin.swift */, + 2605E5A47D5C358C87DE3D160E420E4A /* Platform.Linux.swift */, + D780C8593D2E40CC0D3C2A64F34E17E0 /* PriorityQueue.swift */, + 557A68D20A14109ADEC30EE3A1D38C45 /* PublishRelay+Signal.swift */, + 637A7B8E0568D3EF7B0A2556D5DE4A06 /* Queue.swift */, + 1A435B7B2440EB29B92A6E97E5F426E4 /* RecursiveLock.swift */, + 3F4EEAAD35116C85CB0C374EFE4E28DA /* RxCocoa.h */, + C9FB3F0C1C99CBB4ABF104F8AC950FE0 /* RxCocoa.swift */, + B15BB714A8520B79B914395B09633637 /* RxCocoaObjCRuntimeError+Extensions.swift */, + 1DDF1003EE8B21290AD02B9110DBCFAE /* RxCocoaRuntime.h */, + 9E4D3CDCE6607CA1788A973945B813DB /* RxCollectionViewDataSourcePrefetchingProxy.swift */, + 7486E5C476617A9E62DF0845B3133A84 /* RxCollectionViewDataSourceProxy.swift */, + 3C7C08ED1E8DC5B32FABE8E255A00EC6 /* RxCollectionViewDataSourceType.swift */, + A3FE18E0C1AB2C67F76AA021FEEBEE28 /* RxCollectionViewDelegateProxy.swift */, + ED7660BAC6E4C3F93494EBA47017B0A4 /* RxCollectionViewReactiveArrayDataSource.swift */, + 51AFF4C368AA3CBD436E0DC6CC0942AC /* RxNavigationControllerDelegateProxy.swift */, + D6A7F9A69B7D9163B17A60B7AA14A78C /* RxPickerViewAdapter.swift */, + 37FDD05AFD5CE6C2AA7CC7C13A0686E9 /* RxPickerViewDataSourceProxy.swift */, + 9166244941FB647F587BB858C1470031 /* RxPickerViewDataSourceType.swift */, + 526ADF5A79C2CBC82F503FA0460D8C1A /* RxPickerViewDelegateProxy.swift */, + 6E0F121593C5A360AD45CB450EF3EF36 /* RxScrollViewDelegateProxy.swift */, + 5A849DE4AA3A30A8F9BA600C8F72D0C5 /* RxSearchBarDelegateProxy.swift */, + EDC82EB5069A011CA73BE1218B6698E9 /* RxSearchControllerDelegateProxy.swift */, + 92D160F41A5F10649E32F3FD52D41D21 /* RxTabBarControllerDelegateProxy.swift */, + 2460FB307D49DA24619E67C6AC7D77D4 /* RxTabBarDelegateProxy.swift */, + 95E3F3825D907C4E21155D3E3E8F7DF0 /* RxTableViewDataSourcePrefetchingProxy.swift */, + 3D84A853B5EB7C03FF47C051BC1FAC9A /* RxTableViewDataSourceProxy.swift */, + 16CECFC90862F1ADBFB95E1D0F77C3F3 /* RxTableViewDataSourceType.swift */, + B77639677D7E536F13ADA0C3B0E12156 /* RxTableViewDelegateProxy.swift */, + 8966225B5C5536F8B019FCE27F737098 /* RxTableViewReactiveArrayDataSource.swift */, + 19D38A497544597217CC4F42869773F4 /* RxTarget.swift */, + 98A27FB74C2C193735A702F70EEAFC2D /* RxTextStorageDelegateProxy.swift */, + DE55C5E6AA523AFA73EC2D83A4E177D5 /* RxTextViewDelegateProxy.swift */, + 514A2A555C799CAE4A62B986735C1A78 /* RxWKNavigationDelegateProxy.swift */, + BE492532FB512F9B783CFB73C24D696C /* SchedulerType+SharedSequence.swift */, + D62EA072C6C22D3A5C278C866B397AD2 /* SectionedViewDataSourceType.swift */, + 77BCB87986D3BA89FAF5B76F32EF0E1F /* SharedSequence.swift */, + 1DF70B89B4E437BE1FEE3E1384564301 /* SharedSequence+Operators.swift */, + 03E82BB2AAE6AB5C51DB74536D697019 /* SharedSequence+Operators+arity.swift */, + 2E360D14592776CF6F8A12605C00C389 /* Signal.swift */, + FCB00308A3486A03F452853D6A4B9076 /* Signal+Subscription.swift */, + 876658971488280401D29AE699396A1C /* TextInput.swift */, + A0284DCEBF435B8B9683A5409873BEA7 /* UIActivityIndicatorView+Rx.swift */, + D95787CC4368F63D40C76E31152FB436 /* UIApplication+Rx.swift */, + FE73DD65AC9269C15438EB353DFE71B1 /* UIBarButtonItem+Rx.swift */, + EB3646BC16DDD6CC7E44EABA6B58C12F /* UIButton+Rx.swift */, + D36F1A384BC0E8912C9656D9E9FC32E1 /* UICollectionView+Rx.swift */, + 948610301CCEBB19AAA757417190F369 /* UIControl+Rx.swift */, + CB0164FE6305B6D92B73DFD76AB7F27E /* UIDatePicker+Rx.swift */, + 84B58261A8D6FC70BD19808D6EF5D68D /* UIGestureRecognizer+Rx.swift */, + 1EAF4EDBA81B4579F87F6B03975305E7 /* UINavigationController+Rx.swift */, + AB4DCE3C49F276788DC256A7CB221394 /* UIPickerView+Rx.swift */, + 2A4FD77D127220741C07ECC1A4DB34FB /* UIRefreshControl+Rx.swift */, + 6DD434842DAF29DF870CB0898C2BECDD /* UIScrollView+Rx.swift */, + B1466CA4D101FAE23F9D08B8B63663EE /* UISearchBar+Rx.swift */, + 71D272C276387B42DE9C3FF7D1711F7D /* UISearchController+Rx.swift */, + F3582E176B7730B8D517496A78618266 /* UISegmentedControl+Rx.swift */, + 1DCE96AB9E9FA3053AC8B0DF7E2C066F /* UISlider+Rx.swift */, + C7A8B74BEBC874E98F39F2E95F0E5A2E /* UIStepper+Rx.swift */, + A1A71FD0103010BF1034EF966A3D7D4F /* UISwitch+Rx.swift */, + 338BFDEBE7A339FAFD9573A9926A4572 /* UITabBar+Rx.swift */, + EA2D17E3F21BC2BBF052D1EC33D995DF /* UITabBarController+Rx.swift */, + 3CA7DDF91B9AB1CDDBF143E802DACD59 /* UITableView+Rx.swift */, + 26B8A4D3E4C2891D850DE42B3402AC27 /* UITextField+Rx.swift */, + 1D92F82B9D0455965CA33B58CD326D06 /* UITextView+Rx.swift */, + 7067BB1DCEE4AEFF65144415F41FD9B9 /* URLSession+Rx.swift */, + 6ADB32B034C4EC108D132E1D1886EB47 /* WKWebView+Rx.swift */, + 77C71C10A41292C5B98DC7CE96598F58 /* Support Files */, + ); + name = RxCocoa; + path = RxCocoa; + sourceTree = ""; + }; + 38C501DA8474BE2D0AD7A8B581DB7EB7 /* Support Files */ = { + isa = PBXGroup; + children = ( + 56A3C9241FB780123BA22D4870B8781F /* SwiftyJSON.modulemap */, + A04CAB33A23F87A51DD2CD941A6895F9 /* SwiftyJSON-dummy.m */, + 2EB64A1923FE3E6791208197EF53CD8A /* SwiftyJSON-Info.plist */, + 1E5E8850920985F9BB50D6B6752F9093 /* SwiftyJSON-prefix.pch */, + D6D6B51E110B6440442F78F8CA9BADC9 /* SwiftyJSON-umbrella.h */, + 4379622FBB2CEFDC5335AB006D956909 /* SwiftyJSON.debug.xcconfig */, + B74A78EF31C6F1542EAABDF86E9045D8 /* SwiftyJSON.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/SwiftyJSON"; + sourceTree = ""; + }; + 3C05DDB9DAA619A738F6D60E368B7AE8 /* Pods */ = { + isa = PBXGroup; + children = ( + 1F6DE56E6941409EF1E6A7194A5B5516 /* Alamofire */, + 2990164D6C0BEE58B2259648D5579F79 /* Kingfisher */, + D225F6E8F9E29BB0B9D3FA392E0AB834 /* ListPlaceholder */, + DF8C6936B9A68CFCCB8A4C995456F3DD /* lottie-ios */, + 07C0F4E6ADA7F7ABED8E976831FCC4F8 /* Moya */, + 35E1C1AB9D4FF8D2C8A6A394634C24B2 /* RxCocoa */, + 9511BF3600129816911455CDA366865F /* RxRelay */, + 32428F2F00E092141F4F3B966F8DDFC9 /* RxSwift */, + 807D9B36D57739B07BE05A917B6201A7 /* SkeletonView */, + 559C4EB33743253CC7B8BD023B34ED55 /* SnapKit */, + B3EC700C28E34B5CD994D3B7771B29E8 /* SwiftyJSON */, + D634D4FC4F443BB584E2AB1B64F520C8 /* Then */, + ); + name = Pods; + sourceTree = ""; + }; + 414A5883A8110ABB6774F873D47566AB /* Support Files */ = { + isa = PBXGroup; + children = ( + AC3687208B7F8431C226C956B3D8A795 /* Then.modulemap */, + BA073A17F7CF413B9B0A49B43CE73B77 /* Then-dummy.m */, + 16B574E1489524A122ED5C62813A39BB /* Then-Info.plist */, + ACB48AE1C8CD94FA8E742A31AC787215 /* Then-prefix.pch */, + CC950DA283FF7D67AD9F5BB2852CEC51 /* Then-umbrella.h */, + 3593A9C676C986ADEC9A0D44D5E2E0F5 /* Then.debug.xcconfig */, + 2A6FDF9696B2561B33425CE9CFB52EDF /* Then.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Then"; + sourceTree = ""; + }; + 559C4EB33743253CC7B8BD023B34ED55 /* SnapKit */ = { + isa = PBXGroup; + children = ( + E298B1AD2B044011B7A989681F2936AF /* Constraint.swift */, + 75D32CA634B512FB58E0DFC658CA4C36 /* ConstraintAttributes.swift */, + 12D7DDD5B9E3C6B66125EB05399AA92C /* ConstraintConfig.swift */, + 8CBA8D2D8781420D04B92B32FADC98A1 /* ConstraintConstantTarget.swift */, + 18E8574D9A7619ED4C44F466CEB9B55D /* ConstraintDescription.swift */, + 21376495DF6F8B0050143D1E33B305A3 /* ConstraintDirectionalInsets.swift */, + 85328C52C4A45C6C830C8F5D72D13AEE /* ConstraintDirectionalInsetTarget.swift */, + BB872120E955C14C936A66F79C63056E /* ConstraintDSL.swift */, + 3C2A0E95B0BA6D0627206971E21E650C /* ConstraintInsets.swift */, + 1E2F62EDA4ABF8D09B58CCF5D39C40B0 /* ConstraintInsetTarget.swift */, + 39ED72107466232296E60B188AAD4A74 /* ConstraintItem.swift */, + FC7A24FE2D50C8D81A33DAC6B009D5F6 /* ConstraintLayoutGuide.swift */, + 5988D1FB2FF114A5F12FAEA50CC10BE2 /* ConstraintLayoutGuide+Extensions.swift */, + D5D4436D14D000A1E81E60708A232A60 /* ConstraintLayoutGuideDSL.swift */, + 299F2DCA91D09BC1CD72BF3DCF3D0637 /* ConstraintLayoutSupport.swift */, + 08FBD5ED8C8FFF6DF290DCE8F8399024 /* ConstraintLayoutSupportDSL.swift */, + D50E0E8195DD834A2F4829C5EAEBA725 /* ConstraintMaker.swift */, + 05BD8CE141801C12386DB9E517293094 /* ConstraintMakerEditable.swift */, + FC30D3FB284CDC3251E256458BAD5B33 /* ConstraintMakerExtendable.swift */, + B8F067EB2F26B16397A4024118090762 /* ConstraintMakerFinalizable.swift */, + DB2079BBB30ED62D51431C9765C830CC /* ConstraintMakerPriortizable.swift */, + 17D3F5FECAC38602378868EA27A72126 /* ConstraintMakerRelatable.swift */, + 4F126DE82378F3C5075DC5D1E4F2C04B /* ConstraintMultiplierTarget.swift */, + 9FF59D35D100AB4908E8C05EA0DDBBBA /* ConstraintOffsetTarget.swift */, + BD28CA8E650A4F97AFB97973D4630A2B /* ConstraintPriority.swift */, + 79100CD5FC439F8E474A63439EF9E8A6 /* ConstraintPriorityTarget.swift */, + C5A531C42A7843B362B37D3DC18E18EC /* ConstraintRelatableTarget.swift */, + 2F3974D8B2F35F6CEC4927FAD75F25DC /* ConstraintRelation.swift */, + 67B9263F9767710808C7F9C6B017554E /* ConstraintView.swift */, + B1D3B3A052D7F825E2B4B74BC66DE801 /* ConstraintView+Extensions.swift */, + 44B994A40E780755A43AB36546BE247B /* ConstraintViewDSL.swift */, + 20E5C057F14673FADC3619F20618F5B6 /* Debugging.swift */, + 1429C1A73E6127C81B743C89411AF246 /* LayoutConstraint.swift */, + E45508CEF09B7205462B0A96CBD68DEE /* LayoutConstraintItem.swift */, + 79C9F7290555E8206ECC8A5A27A6FB84 /* Typealiases.swift */, + ACBF41845B42A62975644A4A871D0276 /* UILayoutSupport+Extensions.swift */, + 5FBA81AE0F45C04B9EE421C8BA981706 /* Support Files */, + ); + name = SnapKit; + path = SnapKit; + sourceTree = ""; + }; + 56C288716D805BCC606AB9550A53052B /* Products */ = { + isa = PBXGroup; + children = ( + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */, + C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */, + 3D9F3C8963492DF9D8C22D7704478402 /* ListPlaceholder */, + 51BA97E8B5085EFFB47BC9C0B785CEA7 /* lottie-ios */, + 3756A9BBE41ABEE8DCBF5BCA6972C4DA /* Moya */, + 77F3F1B5A07B282D5E743E607B0110B4 /* Pods-sopt_29th_Assignment */, + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */, + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */, + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */, + CDC8C1E54D1F3A8B5CAC89FFFF6A3F80 /* SkeletonView */, + 979486118B3E90C08386079D57962701 /* SnapKit */, + E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */, + 9317E4947CA2FE1B5D5999034C09CCA7 /* Then */, + ); + name = Products; + sourceTree = ""; + }; + 5FBA81AE0F45C04B9EE421C8BA981706 /* Support Files */ = { + isa = PBXGroup; + children = ( + 83A0C8E7D0862A9B6C7BD32F2EACC537 /* SnapKit.modulemap */, + A210044777925BBC8576B70CCA87AEB0 /* SnapKit-dummy.m */, + 0A3E5441FDDA08B06D2C5D3C63A55FFF /* SnapKit-Info.plist */, + 920C05BEAC13D0E9DDC0F0804DCC706D /* SnapKit-prefix.pch */, + EF01F6EF733E1CA24A3DB61B34B8D1F4 /* SnapKit-umbrella.h */, + 8EF1F2977FAC819C88157477780EA4CA /* SnapKit.debug.xcconfig */, + 34C2783C40155C5656AD80D6A1501FCB /* SnapKit.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/SnapKit"; + sourceTree = ""; + }; + 6379E2E38CAADF0BC8C8BEAD367EDBA4 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + CBC3F96D4513E414841B721928D086C6 /* Pods-sopt_29th_Assignment */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 7187A339559BC1392D0768F17AB3C65D /* Support Files */ = { + isa = PBXGroup; + children = ( + 91C6DD2377283D6623801DB391EC90AF /* Kingfisher.modulemap */, + 5B294D750DF2AE93BF7C04FF7C1D8B7B /* Kingfisher-dummy.m */, + 171E4549F78434F865BCCEE30AF03C81 /* Kingfisher-Info.plist */, + 2C0CA2D40385C76935B1D18156E588E2 /* Kingfisher-prefix.pch */, + 91BC576A34535F04F3E41BB5F4A2BE19 /* Kingfisher-umbrella.h */, + 378854640F1106F95BAEBEB96DFE30C3 /* Kingfisher.debug.xcconfig */, + DE19B39C1F7D2C6F8EA095F0F0DC429F /* Kingfisher.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Kingfisher"; + sourceTree = ""; + }; + 742CE11B6D9F4ACB3D8A3364BEC2995D /* Core */ = { + isa = PBXGroup; + children = ( + B7E83FBCF31EBBE7B947981E091EE7D6 /* AccessTokenPlugin.swift */, + 2C1EF8E89F3F9C75C30DE4DFE7934AE9 /* AnyEncodable.swift */, + 00CA608937E7087A2803C3E379738798 /* Cancellable.swift */, + 99257C69694C651E2522624CF9C224FD /* CredentialsPlugin.swift */, + 75AE3E15F1F864EB067AB303139E6202 /* Endpoint.swift */, + C8F0BE0C794A61C7EB4634CDF63FCEA4 /* Image.swift */, + 65805841B5A618A05FAAF656AE93E772 /* Moya+Alamofire.swift */, + F3E6345266B4A99F5832756CE9B23BCC /* MoyaError.swift */, + 44FEACAACB5FD6154FE9B04A8A54FEE1 /* MoyaProvider.swift */, + 21AA5FE326683C0DBF2F60E8BF8FA2EF /* MoyaProvider+Defaults.swift */, + 0A9731354A24770FBC157F0AA7ACCE9A /* MoyaProvider+Internal.swift */, + 2D30BF91E8A5992C22B85D971C167223 /* MultipartFormData.swift */, + 6BB013FF0D1B8DC50E478E8D80AED779 /* MultiTarget.swift */, + 4A03336AD1E639C291FCB24745455335 /* NetworkActivityPlugin.swift */, + 13CD233600EAFB966BBE0690A5CAD59C /* NetworkLoggerPlugin.swift */, + 8741F7E10B36E8F94F04D711CAAEFFE9 /* Plugin.swift */, + E05745650ABE7B996F364774222E1168 /* RequestTypeWrapper.swift */, + 243F6A556BC9324243FAC2BEF43E5154 /* Response.swift */, + 474C1BE238A9FD53D68B97640CA2FE74 /* TargetType.swift */, + DE387A021380A1F97903F86356357253 /* Task.swift */, + F7918CA582A9312F6A2A6C43295B7F80 /* URL+Moya.swift */, + 13D91F6A2C0E62BC0F8D907BFDFC83EE /* URLRequest+Encoding.swift */, + EC4A56E2A6E5F31A3C5F7289B79FD61B /* ValidationType.swift */, + ); + name = Core; + sourceTree = ""; + }; + 77C71C10A41292C5B98DC7CE96598F58 /* Support Files */ = { + isa = PBXGroup; + children = ( + 6F79D038FA893AD60C0B9929B99012B4 /* RxCocoa.modulemap */, + 4366C669579E73C3ADCF0EFABC667C90 /* RxCocoa-dummy.m */, + E599302821C7078A5576C80BE9164259 /* RxCocoa-Info.plist */, + 443E4EF8CB08E7C6C16C8F9A2F7019C7 /* RxCocoa-prefix.pch */, + 6CDDF1EB0C34D6D1DFAC3CB89513B98E /* RxCocoa-umbrella.h */, + C506ECDECE2EF8C2FB2CCD2D763931DB /* RxCocoa.debug.xcconfig */, + D8B0FF0EDE8D0EF1213F63DD747002C2 /* RxCocoa.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxCocoa"; + sourceTree = ""; + }; + 807D9B36D57739B07BE05A917B6201A7 /* SkeletonView */ = { + isa = PBXGroup; + children = ( + 87735C0487D6CA4F171CF8DA7CD1278B /* AssociationPolicy.swift */, + 14E3019E082D1F606648001D96C0CAE7 /* CALayer+Animations.swift */, + 668793E6F8B1D1C36659901F3D212F86 /* CALayer+Extensions.swift */, + 7DAC87840CE67D59C51D0B26BA74041A /* CollectionSkeleton.swift */, + 35497D877BD0C0976B31A79849E5852B /* Deprecated.swift */, + 4AA032F93E091953B93F1B96CC990C42 /* DispatchQueue+Extensions.swift */, + A5043540270E8CACE7C104E16E932D51 /* GradientDirection.swift */, + 66DA767E2110B9DE41D6296EB97A51AC /* GradientDirection+Animations.swift */, + AC6E4149138E959D0E81F99FB12B5708 /* Int+Extensions.swift */, + B8FDDD0C23DABA7732501CD8AF1CCE6D /* Notification+Extensions.swift */, + D7D4209C642E4A22E0B375197F2EF315 /* Notification+SkeletonFlow.swift */, + 5CC5E86D7D71B850C7D72A19A6FCD417 /* PrepareViewForSkeleton.swift */, + EA50B9E5875D7540898597072A675557 /* ProcessInfo+Extensions.swift */, + F5609126CF5995535E9EA2DC866B0E36 /* Recoverable.swift */, + 25EAC37D7B8734F5F6B503F33A1C8349 /* RecoverableViewState.swift */, + 75207E1DC5C483BB5DE0C5B790629BB4 /* Recursive.swift */, + 1C1283162259A2F47FC79EB025ED886A /* SkeletonAnimationBuilder.swift */, + F8ECFAE0BD799A0E0CF48BA1E63F906A /* SkeletonAppearance.swift */, + E86E84B8E69882F455368E223F2A0927 /* SkeletonCollectionDataSource.swift */, + FA1D48C657C7350A77938B94F6F71C48 /* SkeletonCollectionDelegate.swift */, + 4AB99139C81B8922DC500B24738C2EB9 /* SkeletonCollectionViewProtocols.swift */, + 6EB10D17D9BEBBA990AEF87BA0F42A6A /* SkeletonConfig.swift */, + B3A8E3C5F6FA0810BB8649881B922222 /* SkeletonDebug.swift */, + 45A00219A0362BFAB2AF1BE55BFACA9F /* SkeletonExtended.swift */, + 1079D87BD115E4351902A4B9A6A98EA3 /* SkeletonFlowHandler.swift */, + 7733913F39955FAD01EB941C89BD73FB /* SkeletonGradient.swift */, + 220131E8E36EBD40284FAF5AF8CE03D8 /* SkeletonLayer.swift */, + A097698ED559F253065E3FE68B41B5AE /* SkeletonLayerBuilder.swift */, + 500EA97058AF35437C7881D78F36791E /* SkeletonMultilineLayerBuilder.swift */, + 0BB56B503733457208BCD0A00863E25D /* SkeletonMultilinesLayerConfig.swift */, + 4153857072584D894C8031B00E5FE798 /* SkeletonReusableCell.swift */, + C97468661B020B68BD7AC08EAAA90D1E /* SkeletonTableViewProtocols.swift */, + EE117BBAB45229F7D3240A99FD8D2275 /* SkeletonTextNode.swift */, + E46E04ECE7C5DC3EDC3C423924255D42 /* SkeletonTransitionStyle.swift */, + 4EA480CD3DBE3432276B6BC5B8469E3E /* SkeletonTreeNode.swift */, + 6C242DB41AE52F6AFD5C52D96966223A /* SkeletonTreeNode+Extensions.swift */, + E2975BFFB1283CF80FB0ECC05E969690 /* SkeletonType.swift */, + 2546C912AE8601CF7906404427FE332D /* SkeletonView.swift */, + 60E8F31B3DA3B9958C36DA86B0A97F0E /* SubviewsSkeletonables.swift */, + CEC45818B7595FAE44DBD16AA13C3096 /* Swizzling.swift */, + 15ABA7BBE4F022312F79CD0A4E4A0EA7 /* UICollectionView+CollectionSkeleton.swift */, + 94E98DD21F3A8AA85F9AA68B8CD5AF79 /* UICollectionView+Extensions.swift */, + 375F61A82A5F40C5FD6C91FCCA9DACE9 /* UIColor+Skeleton.swift */, + 3973EEB64C9D326DF952735E56A35608 /* UILabel+Extensions.swift */, + 020972B007C5F08B995E8C1C1955D9A4 /* UILabel+IBInspectable.swift */, + E84906E7CC87F8BCFAE71AF108F1777E /* UILabel+SKExtensions.swift */, + 4D13749C1361D3E0309897785A6F01FE /* UITableView+CollectionSkeleton.swift */, + D2516CD94F1705F41F9E9975E40EA932 /* UITableView+Extensions.swift */, + C3BFC79BAF981C0610BE473F2FC97028 /* UITextView+IBInspectable.swift */, + 093C38CAA4911B48486FD7BCD4563DDD /* UITextView+SKExtensions.swift */, + 6337BB2269CC5F2DB6B494F7F76148F4 /* UIView+AppLifecycleNotifications.swift */, + 1D8FD318337131921162F3040DA3E2DE /* UIView+AssociatedObjects.swift */, + D7B6034196E136373C741FBCDB769798 /* UIView+CollectionSkeleton.swift */, + 6DE7E81B55F89A333B743EB3C1FB84E4 /* UIView+Extensions.swift */, + F2AD080F3651EBED22DAC46B01E5DAD7 /* UIView+IBInspectable.swift */, + B44E8DFF310AA7060F227B091F7A87C0 /* UIView+SkeletonView.swift */, + 2D9607F168FFEFCF17906EDB2A22DFF3 /* UIView+SKExtensions.swift */, + 8D9520E93F1C6E181AB64C6705EEDEC9 /* UIView+Swizzling.swift */, + 51057370900323FCEB104A0AFA33850C /* UIView+Transitions.swift */, + D727B9914460699CC1EE61239EE5ACE6 /* Support Files */, + ); + name = SkeletonView; + path = SkeletonView; + sourceTree = ""; + }; + 8FFB2C3629BEA507F245BCA35AEDE760 /* Support Files */ = { + isa = PBXGroup; + children = ( + 43E3AA26E37DAE4D93A957A8160603F5 /* RxRelay.modulemap */, + 7ADD9BE3E7CF0D7114194C3E5B4E20CF /* RxRelay-dummy.m */, + 1C1AE02A6F340D553BE16E88C5986BE9 /* RxRelay-Info.plist */, + 514C29EF868B36167A28F263FB084B02 /* RxRelay-prefix.pch */, + 52794C382FB8922326B2F8777018068F /* RxRelay-umbrella.h */, + 27F86901F0BC54C484DB217DFBB17E99 /* RxRelay.debug.xcconfig */, + 4392138897B7F1D2D744E42BD42A8666 /* RxRelay.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxRelay"; + sourceTree = ""; + }; + 9511BF3600129816911455CDA366865F /* RxRelay */ = { + isa = PBXGroup; + children = ( + D3018780118D223690C258E639C92C46 /* BehaviorRelay.swift */, + CD5BC5C7839120A1952E14BD41DC492A /* Observable+Bind.swift */, + 32C25D90E00FED9797258D70F1F617DE /* PublishRelay.swift */, + EF430063AF43D273608BD10FF1719F05 /* ReplayRelay.swift */, + EBE2CB20E4A11173FDEFBFD41F42F39D /* Utils.swift */, + 8FFB2C3629BEA507F245BCA35AEDE760 /* Support Files */, + ); + name = RxRelay; + path = RxRelay; + sourceTree = ""; + }; + A30EA3DD1D2499034ABF28CB6EF90CC9 /* Support Files */ = { + isa = PBXGroup; + children = ( + 7604183F01BAC07BC713363B6728A161 /* Moya.modulemap */, + 527FA930D9A852867C15A579A4F01D92 /* Moya-dummy.m */, + A978D283A5C9E40B939D66C2AE26925D /* Moya-Info.plist */, + 3BBB970F55539B321B0665BC7C850687 /* Moya-prefix.pch */, + F23704FF9C44B7431AE73A27EEDDA236 /* Moya-umbrella.h */, + E9077F9703C9F2AF9FBCCEB58C2C8C8B /* Moya.debug.xcconfig */, + 1B6FA3A0B046504259630EC69BE1968D /* Moya.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Moya"; + sourceTree = ""; + }; + B3EC700C28E34B5CD994D3B7771B29E8 /* SwiftyJSON */ = { + isa = PBXGroup; + children = ( + 393CFBCF0BDEE619F1453EC0C3FE00F2 /* SwiftyJSON.swift */, + 38C501DA8474BE2D0AD7A8B581DB7EB7 /* Support Files */, + ); + name = SwiftyJSON; + path = SwiftyJSON; + sourceTree = ""; + }; + B4BCC591BD89D6B9FFD1EB405ED7B3D8 /* Support Files */ = { + isa = PBXGroup; + children = ( + CCCF394F33FE3DF08000C2539A447036 /* ListPlaceholder.modulemap */, + F48EE44D15434B52A20435C8D55CC02B /* ListPlaceholder-dummy.m */, + A78137DC94228E968FFEC6F480F98303 /* ListPlaceholder-Info.plist */, + 6992F289EBE32043726DD989AE0E75F9 /* ListPlaceholder-prefix.pch */, + A6D1220EF0F905357EBF2ABB4C0F553D /* ListPlaceholder-umbrella.h */, + 5A6C58F1D4435C0AB86B565F53116FCA /* ListPlaceholder.debug.xcconfig */, + 482DA72C97FEBA660F16267D96D5E285 /* ListPlaceholder.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/ListPlaceholder"; + sourceTree = ""; + }; + CBC3F96D4513E414841B721928D086C6 /* Pods-sopt_29th_Assignment */ = { + isa = PBXGroup; + children = ( + B7AA4E90F7000B003BDC0E9BC7B633EB /* Pods-sopt_29th_Assignment.modulemap */, + E2D3732B62EC18E4CB2D210C68F41BE4 /* Pods-sopt_29th_Assignment-acknowledgements.markdown */, + 79890AAA4FBE26BD1D68BED9C1DBF801 /* Pods-sopt_29th_Assignment-acknowledgements.plist */, + 6353C2C95453DCBB87CC569B4A188FCC /* Pods-sopt_29th_Assignment-dummy.m */, + C2E159B34E820BB317F60272565E6888 /* Pods-sopt_29th_Assignment-frameworks.sh */, + 26F100ABE95688B8AFD9A91370832FC9 /* Pods-sopt_29th_Assignment-Info.plist */, + A351B9E7F7C039CD709E1333C4329FC3 /* Pods-sopt_29th_Assignment-umbrella.h */, + 0C8822E7100535F320D5E304F38D628F /* Pods-sopt_29th_Assignment.debug.xcconfig */, + 104ED09FCA1D2D46F9F4ADCF6D2F06DC /* Pods-sopt_29th_Assignment.release.xcconfig */, + ); + name = "Pods-sopt_29th_Assignment"; + path = "Target Support Files/Pods-sopt_29th_Assignment"; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + D68CA58901FBF589D75F5E40F1EAF5BA /* Frameworks */, + 3C05DDB9DAA619A738F6D60E368B7AE8 /* Pods */, + 56C288716D805BCC606AB9550A53052B /* Products */, + 6379E2E38CAADF0BC8C8BEAD367EDBA4 /* Targets Support Files */, + ); + sourceTree = ""; + }; + D225F6E8F9E29BB0B9D3FA392E0AB834 /* ListPlaceholder */ = { + isa = PBXGroup; + children = ( + 5874F841747FFE1D064649C299B37A77 /* ListLoader.swift */, + B4BCC591BD89D6B9FFD1EB405ED7B3D8 /* Support Files */, + ); + name = ListPlaceholder; + path = ListPlaceholder; + sourceTree = ""; + }; + D634D4FC4F443BB584E2AB1B64F520C8 /* Then */ = { + isa = PBXGroup; + children = ( + BAF26B7796406D469664118D70F8B582 /* Then.swift */, + 414A5883A8110ABB6774F873D47566AB /* Support Files */, + ); + name = Then; + path = Then; + sourceTree = ""; + }; + D68CA58901FBF589D75F5E40F1EAF5BA /* Frameworks */ = { + isa = PBXGroup; + children = ( + 3526E9C6D178E5274DD4589070F760C5 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + D727B9914460699CC1EE61239EE5ACE6 /* Support Files */ = { + isa = PBXGroup; + children = ( + C7C6AA01643D62A174BC4D0FEE7347CC /* SkeletonView.modulemap */, + CD14B52B0A8703B45487AEE16E0D0AFE /* SkeletonView-dummy.m */, + 7799020F51899D03AA1E835BF03E4F71 /* SkeletonView-Info.plist */, + 33C0F1AB46159D64DFA4C8B2970C0905 /* SkeletonView-prefix.pch */, + 98F8064E2F318C1DDD89DC1186646E74 /* SkeletonView-umbrella.h */, + 1CF228A1EEF44F4A765F24BACC877FD9 /* SkeletonView.debug.xcconfig */, + 02EFDE53819B941417FF687996AB3924 /* SkeletonView.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/SkeletonView"; + sourceTree = ""; + }; + D860C3EF84A85851A9FA422862D510D3 /* Core */ = { + isa = PBXGroup; + children = ( + 433B80DE9E0F4B1F42A3E818AE8B40DC /* AnimatedImageView.swift */, + 3BEEE5E708E847867300037A0C0D8F16 /* AuthenticationChallengeResponsable.swift */, + FB80662DC88930A808766D75B58B8E0F /* AVAssetImageDataProvider.swift */, + 779509B5AC8A026D6CCF04664FE67F0C /* Box.swift */, + 438454217A3C55CD48E9CBD2755D3F22 /* CacheSerializer.swift */, + 7E6B622ADFB980BF374CBB86D3759C0F /* CallbackQueue.swift */, + 40833CDFE3A86FC1485A6A8F67ABD5E6 /* Delegate.swift */, + 8AD24F3A7AC53743B10C3F63B5866547 /* Deprecated.swift */, + 513FD6E24419295D861763CE18D52C4D /* DiskStorage.swift */, + 23AA520C599D9905EA822AD7D599635F /* ExtensionHelpers.swift */, + F43F0A34089FF64327D57D242A57BF6C /* Filter.swift */, + 6F3CFE254D1E97B15F75B7259F27814D /* FormatIndicatedCacheSerializer.swift */, + EE694AAA0AB777F54457592C110B14EE /* GIFAnimatedImage.swift */, + 8CA31AE5F7ECFABC6C659814E6834818 /* Image.swift */, + BD8F63AEB8F29A078DB6D1994472EA53 /* ImageCache.swift */, + EBA5958B85EB0C407E6F8EF90D38FD5F /* ImageDataProcessor.swift */, + 96E774AF77CBFC641B734B852F795BF0 /* ImageDataProvider.swift */, + E86354E64FA98EDE3E66839D9D8C9689 /* ImageDownloader.swift */, + 53827C32DF6393C2BD736C97B9831F75 /* ImageDownloaderDelegate.swift */, + F55A505B6DD9C82DC3280E5B748463C9 /* ImageDrawing.swift */, + FF9ECF5DC98A260F6CDB707618BA0859 /* ImageFormat.swift */, + 8EA592B787975BD740DF85A0C27FD2A8 /* ImageModifier.swift */, + 658B3E81297F503FE6CB67E23E559099 /* ImagePrefetcher.swift */, + 51C9D42FAF78B6A8609A0BB2C9215532 /* ImageProcessor.swift */, + 4648526110FA513D5C2B2E4598FE0416 /* ImageProgressive.swift */, + EE3DF2FB46BC58BC124C4CB365639907 /* ImageTransition.swift */, + 6C8C603268BD296934CEC35FB0BC8923 /* ImageView+Kingfisher.swift */, + 8F0A8B19E1BC4E88AA8159FDE0A173A3 /* Indicator.swift */, + 8FC7A302AF558DC2FFCCDA0282CD0E63 /* Kingfisher.h */, + 67AEAD300238A4E2EB710FE822BB3A5A /* Kingfisher.swift */, + B4E560FCC7FB3037CD48F0A911A4B06D /* KingfisherError.swift */, + 89BA5964A5E5D1A71F9E5858E4620E5A /* KingfisherManager.swift */, + 09A5B581F7C28D047493EFE6DA37B80C /* KingfisherOptionsInfo.swift */, + 99D2BEA76FA15F487ADF926CB89CF093 /* MemoryStorage.swift */, + 4264469B6581B43C3A3379E6C8927360 /* NSButton+Kingfisher.swift */, + 506581462DCF2AD73F7FFB993DE007D8 /* NSTextAttachment+Kingfisher.swift */, + 8CD3719C675D6F03542CD7EFCE7B46EB /* Placeholder.swift */, + 92ABA31BDF9745B8D40F3B5E55502350 /* RedirectHandler.swift */, + 56944244C79D6B7A8CD6B1AA50E54632 /* RequestModifier.swift */, + EF5F0433C5B5A2FDCD09A81C569C081F /* Resource.swift */, + F0A389573E7C58DCFE123C674C78E89D /* Result.swift */, + 029298EC9C3BCB1FAAA6B0BF3F6B2A46 /* RetryStrategy.swift */, + 4ED733DB06AC8A291976B4A6AEED7AE0 /* Runtime.swift */, + AA353B32D4E255B5032D0EB172EC1338 /* SessionDataTask.swift */, + BA03E550D12601C16729AAADF5DD65F0 /* SessionDelegate.swift */, + 798B36F771350D6304F48AA292794702 /* SizeExtensions.swift */, + 66FBAC3E0E191ED981538DBCFFBFBD83 /* Source.swift */, + C993FA1C50C448867D6FA9026008D4B0 /* Storage.swift */, + 40FD9C80907D086CB5E915BB58C9CFFD /* String+MD5.swift */, + 881461D11DAD4B0D0627B6EFE37D1926 /* UIButton+Kingfisher.swift */, + 55CD10ADFA2358EF18B237530DD80710 /* WKInterfaceImage+Kingfisher.swift */, + ); + name = Core; + sourceTree = ""; + }; + DF8C6936B9A68CFCCB8A4C995456F3DD /* lottie-ios */ = { + isa = PBXGroup; + children = ( + 011A48617CAE79014E42ED17A15ABF48 /* AnimatedButton.swift */, + 93D42DBBE4B2B3C7F405C325CE7ED02D /* AnimatedControl.swift */, + 6E19FA12109EA2B1D8E939B3434B1332 /* AnimatedSwitch.swift */, + B640A6E4F170CB420AEF0F40319B8A78 /* Animation.swift */, + 49B32A5355B9E0D5930A79C4C83652C2 /* AnimationCacheProvider.swift */, + 67A269CCEF3E54285735630AE7BB7253 /* AnimationContainer.swift */, + 544395BC5A4545A205B84129662C3839 /* AnimationContext.swift */, + 0AB11D015902E3E50194C7855580589E /* AnimationFontProvider.swift */, + EA9B22BE2DA7ABC11AB8EF2A3D7C0BE0 /* AnimationImageProvider.swift */, + BE7F07175183E202A0AA6844976B0496 /* AnimationKeypath.swift */, + 088A593EA49F6CD6A9EB9B1445C3A5AD /* AnimationKeypathExtension.swift */, + 21345028EFC317FB2DBC1A4C9ECA08FA /* AnimationPublic.swift */, + D483C06CDB9E8C25AF3499A532E7326C /* AnimationSubview.swift */, + B0B8965EB066B4207C18FA0BB86BB3F5 /* AnimationTextProvider.swift */, + FB156F61588D89617814BA094C4E1C24 /* AnimationTime.swift */, + 015CD2874ABEA0E08CA67E1EBB1F7404 /* AnimationView.swift */, + D9896557140AD1D536F8409779DBAEFF /* AnimationViewInitializers.swift */, + DCF4EDC3F12B4511CA85D4FC7A5911E1 /* AnimatorNode.swift */, + F0F310186ED318969FC8006B3056F8C7 /* AnimatorNodeDebugging.swift */, + A178A97BCE6505C2B3FD32FCFA25A45F /* AnyNodeProperty.swift */, + 22C6807ACC5407C39AE3CFE3BEF30D50 /* AnyValueContainer.swift */, + EB4D150E2481BC5A0BF7A81282C2DBD6 /* AnyValueProvider.swift */, + 5C12F9EE80F91F13B4B83C977CD01AE8 /* Asset.swift */, + 8A7D4DA0A4088D7A5AA82C6475EFF6D5 /* AssetLibrary.swift */, + 367239DE49765930152EB321BB1AC71B /* BezierPath.swift */, + 8E56681B529C28A6E689C753AFB5C5A9 /* BundleImageProvider.swift */, + 328D4B3B5F0D35672A572ED5EC36DF34 /* CGFloatExtensions.swift */, + DA79228103DCF330C6CF010CF0F509B5 /* Color.swift */, + 5E99ED7A5B57918151A962F031DA8B2D /* ColorExtension.swift */, + 72FA3260F540C02E616019AF7AF70861 /* ColorValueProvider.swift */, + 2E471D37BD70D017261F532771D3652B /* CompatibleAnimationKeypath.swift */, + 08A274191F06572D07458949D5AD6657 /* CompatibleAnimationView.swift */, + 1FC173610BDE1E63571E4D11392019E3 /* CompositionLayer.swift */, + 8EC82515D323F64C29E236D7341AE7AE /* CompositionLayersInitializer.swift */, + D9569A95E5B6C6404B3DE7ADAC9DB01A /* CompoundBezierPath.swift */, + 69E2C711E5C8B7DB42DDBBD92A6845D1 /* CurveVertex.swift */, + 6EBADBDD2F7B15C127B92289C76915E4 /* DashPattern.swift */, + C70255F45E310C14D25E974842ACE0C9 /* Ellipse.swift */, + 0CC11B921788E101765C74857D6473EA /* EllipseNode.swift */, + 0E2C669013911C6D4FB27F8CE2B6B058 /* FilepathImageProvider.swift */, + C47E28487EDD76C42BA8438285F90A17 /* FillI.swift */, + 52B847EADB822730B47853A02A2E8F3B /* FillNode.swift */, + D220985C78D75C384CDF8B81DB6B3D91 /* FillRenderer.swift */, + 64B2FD33538D38B86472940515F0DCC5 /* FloatValueProvider.swift */, + 7ED739459C8BBA3A49BDF0C535E3D6C3 /* Font.swift */, + 78B5248C51B733A30C1C2CEFBD955431 /* Glyph.swift */, + 9DA61552627F440050A87FAB1F0F46AB /* GradientFill.swift */, + 41D5A48269E859CE9430419153128AB5 /* GradientFillNode.swift */, + C052ECF294DA36289A931FCE885FCCE2 /* GradientFillRenderer.swift */, + 05BE1DF2E2240958B65FE14B975F3128 /* GradientStroke.swift */, + 50C989774E4BEF7CC2CDCAA70573E81A /* GradientStrokeNode.swift */, + 07717BA267486AC9402D252D4961A068 /* GradientStrokeRenderer.swift */, + BCB9B7980E4C45EF00EDD72D1DAA9B70 /* GradientValueProvider.swift */, + 5E68D7FE551C4CDD777F3AAFE86821C1 /* Group.swift */, + FF9FEFFA9B7D920FE0827A598FAB6C8E /* GroupInterpolator.swift */, + A48F8F6180E6DDC72D73DC1F0F803C76 /* GroupNode.swift */, + 6DD295E670FAB94E394EA854B93616CF /* GroupOutputNode.swift */, + 61CAA5048FAA6F86DBCA93B8B7B6FB05 /* ImageAsset.swift */, + FC9C172FF95F6BCF1D316CE2E1F746C9 /* ImageCompositionLayer.swift */, + 11F741538AE9A108ABB75A5F99AF1995 /* ImageLayerModel.swift */, + 17796C91B1AF123126FC9386C010BE4F /* Interpolatable.swift */, + 601A2832945FACAC50820FDBB3B05BCF /* InterpolatableExtensions.swift */, + EE884D500D9139650D8E47EB891A17F2 /* InvertedMatteLayer.swift */, + 3ECFCAD5FD0C48632D983F15D90759CF /* ItemsExtension.swift */, + 346EFDE086B13ABF6504CE67C670CE68 /* KeyedDecodingContainerExtensions.swift */, + 5FA4E4F7F53DBC89CE7DD14EC091577B /* Keyframe.swift */, + E98C006640C2FDCDAD55CA9CA1801605 /* KeyframeExtensions.swift */, + 19C735D18D612892EEDC5F487CB5ABA7 /* KeyframeGroup.swift */, + F75A90C2F8242F9556979A6FA039CA1D /* KeyframeInterpolator.swift */, + 6BDB661C93B87F00D167E4709AD2A86C /* KeypathSearchable.swift */, + 3B9B5E120B5F7D089128B46F55F1BCAB /* LayerDebugging.swift */, + F91DBDE07A61124CA56D3DF66AC9DE34 /* LayerFontProvider.swift */, + 11A089E572305D54324465FF35B215E3 /* LayerImageProvider.swift */, + CFF0769755F5BA666BB460EFCB21376E /* LayerModel.swift */, + F8086AFD18868DE3546DA9099D9320BF /* LayerTextProvider.swift */, + 33520700E00C9FBBBB89B24FBA4EDA44 /* LayerTransformNode.swift */, + 8B6946CBE7861917F027FE6008918B0C /* LottieView.swift */, + CC6E46E41581F6F1F6C6898DD24FD7EB /* LRUAnimationCache.swift */, + 9E0E9B03955AD5C69E96676AC5F31FD5 /* Marker.swift */, + 9E963FDB21BEC3F2CBFF40253B0B1671 /* Mask.swift */, + 32C3E6FFE6086B692332E200EB3E37FE /* MaskContainerLayer.swift */, + D03B4C2B16C9EF8A9E6B858BBCE8BF5A /* MathKit.swift */, + 952BA62F6689CB4B398C16DBE3471008 /* Merge.swift */, + 36162C76DB6AF3C2B51AF1A95E380696 /* NodeProperty.swift */, + B744D0CCE9CE83FFF1F579AE0B296541 /* NodePropertyMap.swift */, + 36AB4A0D570C8199050F230FC5DD3C34 /* NullCompositionLayer.swift */, + BFD49E72672C87106DCAACF65BA77F61 /* PassThroughOutputNode.swift */, + 4DF448AB4ED97D9C8A49D8B950451DEF /* PathElement.swift */, + 8368A92C8EA09600C9E2C855F83C8C01 /* PathNode.swift */, + 444F5668DB1CCE1EEE4C56A44681A9A1 /* PathOutputNode.swift */, + 287C08308C6C979AD2AE20875F806582 /* PointValueProvider.swift */, + C8A5986178C2D57C6A6D36F0FBDA1536 /* PolygonNode.swift */, + 43CFF9BDD3A181526EF302B0229AAECC /* PrecompAsset.swift */, + 0676D52867ED3A86854134835E52F0A0 /* PreCompLayerModel.swift */, + A49FCB95D8218F9C1184EE6009A97BD2 /* PreCompositionLayer.swift */, + 20C21FA8C4DD01B44A00ACDCC06C137E /* Rectangle.swift */, + FFB0D21E5795488A0BB324C98CB416AD /* RectNode.swift */, + 0B449B85DD9D71D971051E2AC440E59E /* RenderNode.swift */, + AD54988AAEF3476D7CDFD2076F4F7D35 /* Repeater.swift */, + 1833C016AFDFA598B3C7CE1DB8E431C5 /* Shape.swift */, + DA353CE7AE8D250EFA8C4A3247EB25C1 /* ShapeCompositionLayer.swift */, + CD6F904BE916FF77393166233CC2F108 /* ShapeContainerLayer.swift */, + DD6C51736CC8C421D1FF2F68EFD04B85 /* ShapeItem.swift */, + 2D873E925CE42958A7B41F3F37920F0D /* ShapeLayerModel.swift */, + 9C156DEDEE5322CEF2B1F759D8B69489 /* ShapeNode.swift */, + 6DF67815AB2355808DE38A66A22BF832 /* ShapeRenderLayer.swift */, + 93E79E4061F7310825626A571136E52C /* ShapeTransform.swift */, + 9D49DD6592CAE4A4681462C888A5704F /* SingleValueProvider.swift */, + A3A5C82D7E3750C47DCC4D089790BBD9 /* SizeValueProvider.swift */, + D54C98DE7CEBB2D8F1131C7B50E7FD04 /* SolidCompositionLayer.swift */, + 2FBFC9C2376164147EDEEB37CE43CF48 /* SolidLayerModel.swift */, + 43DA4FB5DBD9F9E7FA2D72E5116CE1AD /* Star.swift */, + 0AB5A54E0682D80EBE2BBB6A2BCA2965 /* StarNode.swift */, + 958990AC25E732E67FE51103C087723C /* StringExtensions.swift */, + 1E353EDBF4268085799BBFFF27229504 /* Stroke.swift */, + 0E89F63380C350E98B411CE7028B16D0 /* StrokeNode.swift */, + F2399A067CF54CE64CA10F9123F63F19 /* StrokeRenderer.swift */, + F422053BDBB0BDDDDD82DFAE5FDF6CFE /* TextAnimator.swift */, + A7B7DCA28AC747E52ED2D5253ACE2EC1 /* TextAnimatorNode.swift */, + 60DAF39780BEBA99153B7A449B8B5A5A /* TextCompositionLayer.swift */, + 7B5C178ABA8010A0DEC30E331EB4DF64 /* TextDocument.swift */, + 27F720B3CAA847C7E9C1D8382F05D5A6 /* TextLayer.swift */, + A07764B25F14323CC34D8697ECD39487 /* TextLayerModel.swift */, + 1A201CE6C47D308F8A0460BF3C410204 /* Transform.swift */, + EE21E076DA1CB81D248C4EC102DE5C52 /* Trim.swift */, + 19BB2B091B613205ACE47BC3A9070BD8 /* TrimPathNode.swift */, + ECAA3D71D0B3875B94B4A632D9A2654D /* UIColorExtension.swift */, + 045B675D9753FDDDB0BFE1C846868669 /* ValueContainer.swift */, + 79BE205B7363AA5BD607C5AC7854113B /* Vectors.swift */, + 699C754CB7A4A4F2D0BBB08B976D0EFC /* VectorsExtensions.swift */, + EFCDB9FFF3C7C1F1E7E54DFAA28961EA /* Support Files */, + ); + name = "lottie-ios"; + path = "lottie-ios"; + sourceTree = ""; + }; + EFCDB9FFF3C7C1F1E7E54DFAA28961EA /* Support Files */ = { + isa = PBXGroup; + children = ( + 056FD91F542A473CC393BE5FBB5B07F9 /* lottie-ios.modulemap */, + B220CFF8BD81422281651D25D997C0F8 /* lottie-ios-dummy.m */, + 49E03A057A79F330524962695F9FFA94 /* lottie-ios-Info.plist */, + 19C712DA7B3CE570CB2D07BED0B93BB0 /* lottie-ios-prefix.pch */, + 50535740A752839EFCC7E5D87EEDC917 /* lottie-ios-umbrella.h */, + 0782047E60E7337951DBC4FB782255D1 /* lottie-ios.debug.xcconfig */, + E65F27B5F5507A9C1200A5BA6654B668 /* lottie-ios.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/lottie-ios"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 14FF1799C5ADBC71E1DB963F2AF8853D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 0B399DCF32F8FE4F09B03B6E7B65E0D1 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1636FCAD17E4800F64DBA2B1BA737C7D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1AF3BF0EDE10F429386594F787838C1B /* _RX.h in Headers */, + E6A1BF57511CE77AE62E000F61A5F48F /* _RXDelegateProxy.h in Headers */, + 0422FC5745E406CB752E9497A2F56EA9 /* _RXKVOObserver.h in Headers */, + D8A4FE44301CF797B3E9655FA9F80FA6 /* _RXObjCRuntime.h in Headers */, + 3AFEA39C21C700AAB86C4ACD9436D357 /* RxCocoa.h in Headers */, + 59691189B7A014BB0230561AC0A489A6 /* RxCocoa-umbrella.h in Headers */, + 4994F1CABB9926703D82BA0D9D66321C /* RxCocoaRuntime.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3B921547E999920F44EBD58F955423CC /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A4467357581E8345DD348683CC4111AF /* SnapKit-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 41145698F7DF35B05606D01197454CFC /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A115142039C23F91827E6961CC479F05 /* SwiftyJSON-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 419499CDF56751D2B9B98EE8D54FF1EC /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 08764DA4C847E1FB033E9EA07DB1EDCA /* Kingfisher.h in Headers */, + D2F4222D67ACD91E8139BBECFDFC381F /* Kingfisher-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 445C28CF8CCBD5F517E0AF3F62045B20 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 500F5B102872362C647C424D690CDCC4 /* ListPlaceholder-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 741BDA27CA8933A03E719B7FC62CCEB9 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DBF3771E8DE151A1D8A1692707B71501 /* SkeletonView-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 88B76612BD3E9CF4A279CC3F0547A009 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F2C47F7311D0B149A8FC0FF1B3838CB3 /* RxRelay-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9CCDD3BBCF363FF207028FA213D117DD /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ABB41236912FC1C6E7330BB3568E917C /* Pods-sopt_29th_Assignment-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C90C5FCDBD328B197A7AC3161849587D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 400964555B766D5EBA2E15AD96CB17C7 /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CCEC8E71A588B6912DDF09147E024EF4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 5162C4A6F96947FBF255F7130CE28A6D /* Moya-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D0482E511DA59C90F7DB62C353302CD0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A892A3F92A4B151AD508CFCD080082A4 /* Then-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DB239C7D24F46F65C33A88ED3E39D6E3 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 15FBDAE3DDDEBF1E36298091A8896B04 /* lottie-ios-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 0B967D7F8561D42493EE289EC8D450D1 /* lottie-ios */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6C5C9A3D61A6DEB025C9ACE0866E949F /* Build configuration list for PBXNativeTarget "lottie-ios" */; + buildPhases = ( + DB239C7D24F46F65C33A88ED3E39D6E3 /* Headers */, + 3DD73B13896A894B2FACEC8084E0B0A1 /* Sources */, + 95AE726CE354B76A6E5BE28655B6498D /* Frameworks */, + EECEA9E3ABF51BFF6168DED7DFA8E1C8 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "lottie-ios"; + productName = Lottie; + productReference = 51BA97E8B5085EFFB47BC9C0B785CEA7 /* lottie-ios */; + productType = "com.apple.product-type.framework"; + }; + 17F9141D333DA1A7BE5937F227221070 /* Moya */ = { + isa = PBXNativeTarget; + buildConfigurationList = 25737AF8107207FF823CA33914BAB276 /* Build configuration list for PBXNativeTarget "Moya" */; + buildPhases = ( + CCEC8E71A588B6912DDF09147E024EF4 /* Headers */, + D2DBC21241DC6AC2CB1405907058A8E6 /* Sources */, + A9B7DA8193E441061CF2888B58990357 /* Frameworks */, + 17532F85991F4EDEA2D6734A463F4A38 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + DD6F4F249D9787C8DE7CF5D35B0F452B /* PBXTargetDependency */, + ); + name = Moya; + productName = Moya; + productReference = 3756A9BBE41ABEE8DCBF5BCA6972C4DA /* Moya */; + productType = "com.apple.product-type.framework"; + }; + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4949A940CD53B7E293859B71C91C88F3 /* Build configuration list for PBXNativeTarget "SnapKit" */; + buildPhases = ( + 3B921547E999920F44EBD58F955423CC /* Headers */, + 06A02EF810C9B8F84BA558BBDB9E5D6E /* Sources */, + 9B30433E568C40FCE04D5188A9715448 /* Frameworks */, + DBFBC99C6F5D9B1D57CC9D1C6E9209EB /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SnapKit; + productName = SnapKit; + productReference = 979486118B3E90C08386079D57962701 /* SnapKit */; + productType = "com.apple.product-type.framework"; + }; + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */ = { + isa = PBXNativeTarget; + buildConfigurationList = FA3AEC515004CAE301291DB49AF63C10 /* Build configuration list for PBXNativeTarget "RxRelay" */; + buildPhases = ( + 88B76612BD3E9CF4A279CC3F0547A009 /* Headers */, + E11F84192A9F8312DF1916303046C64B /* Sources */, + 79C6F6E48501AE398E29FE88A9E18B4D /* Frameworks */, + F8EAECBE79CE203D38DF8FAC44844CC7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 51D0DCA4AAFEDA6BF800636E32C869FD /* PBXTargetDependency */, + ); + name = RxRelay; + productName = RxRelay; + productReference = FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */; + productType = "com.apple.product-type.framework"; + }; + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */ = { + isa = PBXNativeTarget; + buildConfigurationList = 25AE2A8304AA799A1A0A4FD6C1577310 /* Build configuration list for PBXNativeTarget "RxCocoa" */; + buildPhases = ( + 1636FCAD17E4800F64DBA2B1BA737C7D /* Headers */, + F3A28FDE156C7CAA6CA5FC5646AD34F4 /* Sources */, + 4DAD51760C3A529B5ACA9477FDA8E31A /* Frameworks */, + A8D6AD1BD6863B21A8AB1DB161659DB8 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + B9ECECD5B2D4A6DA2A5BFCA63610D08D /* PBXTargetDependency */, + 43D82A45260ED5056B43FD754FFFC49C /* PBXTargetDependency */, + ); + name = RxCocoa; + productName = RxCocoa; + productReference = BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */; + productType = "com.apple.product-type.framework"; + }; + 881D2AF3078426440580FAD64637BBE0 /* ListPlaceholder */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97D2382C0969601D44189F3B35A29F70 /* Build configuration list for PBXNativeTarget "ListPlaceholder" */; + buildPhases = ( + 445C28CF8CCBD5F517E0AF3F62045B20 /* Headers */, + C2C3D13EE11C41E2F86A52F3FDE4FA5D /* Sources */, + 0922C932A8B237B74FD05C0F5F34D3C8 /* Frameworks */, + 34930B31E26F65B986AF1F19763CC52F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ListPlaceholder; + productName = ListPlaceholder; + productReference = 3D9F3C8963492DF9D8C22D7704478402 /* ListPlaceholder */; + productType = "com.apple.product-type.framework"; + }; + 8CEEFD1CB630CA790F0396E2E24A4C8C /* SkeletonView */ = { + isa = PBXNativeTarget; + buildConfigurationList = E249F9CC1A59D4DC6ED56FE713439CBA /* Build configuration list for PBXNativeTarget "SkeletonView" */; + buildPhases = ( + 741BDA27CA8933A03E719B7FC62CCEB9 /* Headers */, + C81EB1347EFB7B8F025F46DDBF78A45B /* Sources */, + 4A77A298FBB428EC655B61E5E2F3D300 /* Frameworks */, + 345625474716F68A7180DDC9A7EAF6AD /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SkeletonView; + productName = SkeletonView; + productReference = CDC8C1E54D1F3A8B5CAC89FFFF6A3F80 /* SkeletonView */; + productType = "com.apple.product-type.framework"; + }; + C17AEFC79E770A2906EFAAB1A3757406 /* Then */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9066CF256D5B92C1B2C5053115F4AC74 /* Build configuration list for PBXNativeTarget "Then" */; + buildPhases = ( + D0482E511DA59C90F7DB62C353302CD0 /* Headers */, + D9DF5AEE1B525A8BA763D0DFA7241A71 /* Sources */, + B110F4A89B80E9EA29019FC5CA16B326 /* Frameworks */, + 08C52A0B42B9DFC342690EC119C9DFCA /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Then; + productName = Then; + productReference = 9317E4947CA2FE1B5D5999034C09CCA7 /* Then */; + productType = "com.apple.product-type.framework"; + }; + D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2490E828D479276A7E0AFBA515DD77FA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; + buildPhases = ( + 41145698F7DF35B05606D01197454CFC /* Headers */, + 7B5BEB32F210EFE38F7D58FF8A1CC2DE /* Sources */, + 3977393A21672F0FBC6F1193739E0D15 /* Frameworks */, + B05597C458D738E12F170EAC515F8483 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftyJSON; + productName = SwiftyJSON; + productReference = E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */; + productType = "com.apple.product-type.framework"; + }; + E7ABC450F3E96D5B92944827F701CB34 /* Pods-sopt_29th_Assignment */ = { + isa = PBXNativeTarget; + buildConfigurationList = BC9DCA8EC2C877618C8BADC0FCDB2B1F /* Build configuration list for PBXNativeTarget "Pods-sopt_29th_Assignment" */; + buildPhases = ( + 9CCDD3BBCF363FF207028FA213D117DD /* Headers */, + 41E6B6BBD659944B8D2BA5C9F9463E38 /* Sources */, + 90CBA3AD7F41BA5D0202C65BCE1D4E9C /* Frameworks */, + AF5CE1D2CFCA79474A58919D66CE4426 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 70D85C49374E79CF1BC882D5FAC7D01C /* PBXTargetDependency */, + 89BE329F5DFA0300F632809D1BF9A9D1 /* PBXTargetDependency */, + BDB715FCC2D2EC03F47C616167D06F4D /* PBXTargetDependency */, + 115CD258ABA61F963F643A662E38779D /* PBXTargetDependency */, + B0AB82E7FD8A5D185898ABF7430D8CF3 /* PBXTargetDependency */, + A8F079ABA8E172DD508AD330251970F2 /* PBXTargetDependency */, + 08FF32A4188794D1FB1723BB548D0DF1 /* PBXTargetDependency */, + F79B240A89BF11494C9D6366D09A4481 /* PBXTargetDependency */, + 945AF39EB604722D61DB7130CC3CD2DB /* PBXTargetDependency */, + 9A16BFFCEC24F512034D509AE6FE02AC /* PBXTargetDependency */, + 09EED8A378BD557822A56576EED5B8D3 /* PBXTargetDependency */, + B85D375F82BDFBCFDFC4891721981C0B /* PBXTargetDependency */, + ); + name = "Pods-sopt_29th_Assignment"; + productName = Pods_sopt_29th_Assignment; + productReference = 77F3F1B5A07B282D5E743E607B0110B4 /* Pods-sopt_29th_Assignment */; + productType = "com.apple.product-type.framework"; + }; + E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */ = { + isa = PBXNativeTarget; + buildConfigurationList = EAFF386EB25D481C9E1803A77104206E /* Build configuration list for PBXNativeTarget "Kingfisher" */; + buildPhases = ( + 419499CDF56751D2B9B98EE8D54FF1EC /* Headers */, + B305EAE1C6B0A6E3455ACC30A4731FA5 /* Sources */, + EED2AC90E1553CF9889DB6D723EAF5D1 /* Frameworks */, + 09BF3FBBB8391FDAB603C04F7E931568 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Kingfisher; + productName = Kingfisher; + productReference = C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */; + productType = "com.apple.product-type.framework"; + }; + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4C14BC5413148D6627CBCB3E42C63146 /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + C90C5FCDBD328B197A7AC3161849587D /* Headers */, + 11BC5CF112CA34A070EF082B94C90D1F /* Sources */, + 33B02A89A0936F35670F8497BC396EDE /* Frameworks */, + A084F08BE20500F363B625A45C9D3C52 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */; + productType = "com.apple.product-type.framework"; + }; + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9C98220D3187BF01A20E296DC128BED4 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 14FF1799C5ADBC71E1DB963F2AF8853D /* Headers */, + 5FE9836A67EA3E51CA889A1AB95BC874 /* Sources */, + 39D530C2A3085A1033683EC9AE0BC313 /* Frameworks */, + 93ECA2D9F79614966DFA76280ABFEF67 /* 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 = 1240; + LastUpgradeCheck = 1240; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 13.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 56C288716D805BCC606AB9550A53052B /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, + E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */, + 881D2AF3078426440580FAD64637BBE0 /* ListPlaceholder */, + 0B967D7F8561D42493EE289EC8D450D1 /* lottie-ios */, + 17F9141D333DA1A7BE5937F227221070 /* Moya */, + E7ABC450F3E96D5B92944827F701CB34 /* Pods-sopt_29th_Assignment */, + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */, + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */, + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */, + 8CEEFD1CB630CA790F0396E2E24A4C8C /* SkeletonView */, + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */, + D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */, + C17AEFC79E770A2906EFAAB1A3757406 /* Then */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 08C52A0B42B9DFC342690EC119C9DFCA /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 09BF3FBBB8391FDAB603C04F7E931568 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 17532F85991F4EDEA2D6734A463F4A38 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 345625474716F68A7180DDC9A7EAF6AD /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 34930B31E26F65B986AF1F19763CC52F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 93ECA2D9F79614966DFA76280ABFEF67 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A084F08BE20500F363B625A45C9D3C52 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A8D6AD1BD6863B21A8AB1DB161659DB8 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AF5CE1D2CFCA79474A58919D66CE4426 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B05597C458D738E12F170EAC515F8483 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DBFBC99C6F5D9B1D57CC9D1C6E9209EB /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EECEA9E3ABF51BFF6168DED7DFA8E1C8 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F8EAECBE79CE203D38DF8FAC44844CC7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 06A02EF810C9B8F84BA558BBDB9E5D6E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 51A4A1046676D304410544EB56732A49 /* Constraint.swift in Sources */, + 7580FAAB1BDA52F5A969E5571D1A5973 /* ConstraintAttributes.swift in Sources */, + B543FD108C1C6AF6129CB4991553218B /* ConstraintConfig.swift in Sources */, + C61D3BC32A28A405C934C00039AD2583 /* ConstraintConstantTarget.swift in Sources */, + 8FD9CD608C4EAAFDE6AC7B8B9EF0FF5E /* ConstraintDescription.swift in Sources */, + A0F754C88A64972A40A9008B0AD52109 /* ConstraintDirectionalInsets.swift in Sources */, + 7764AA5F6BBFC6ECE43959923DD007D3 /* ConstraintDirectionalInsetTarget.swift in Sources */, + 90FD5AE525E138A473723FD79AF73273 /* ConstraintDSL.swift in Sources */, + 8C6546C1EF4F153DF3795CC6FE189E5B /* ConstraintInsets.swift in Sources */, + BEBF920FEB959B46A76BAADF22E5CD15 /* ConstraintInsetTarget.swift in Sources */, + BD333CDBCF5D2FD55920336FC271DF33 /* ConstraintItem.swift in Sources */, + EE6C364198A763EBBF49237035D86439 /* ConstraintLayoutGuide.swift in Sources */, + 3DEDFA52B3A196F6D3E1F0937617628A /* ConstraintLayoutGuide+Extensions.swift in Sources */, + 8449EB1DFD43E222D687D5A8D2088D2D /* ConstraintLayoutGuideDSL.swift in Sources */, + 3B60C02F6E42FD06B128473E00A94224 /* ConstraintLayoutSupport.swift in Sources */, + 274DF0E2BF04F6F4F9F1E70CF513A4F2 /* ConstraintLayoutSupportDSL.swift in Sources */, + CB194156C900B767B0160AF72EDF354D /* ConstraintMaker.swift in Sources */, + A53D3AF15CE8D348306EF11619C5D166 /* ConstraintMakerEditable.swift in Sources */, + 825062025906CE93C5D124E1FD9A811E /* ConstraintMakerExtendable.swift in Sources */, + D13D417B236E736EEAE7217B5CE3EC5C /* ConstraintMakerFinalizable.swift in Sources */, + F2C817C166B2DE613222C41015A586C9 /* ConstraintMakerPriortizable.swift in Sources */, + CB8E4BF0D710970BE2CB4C87ED1043E4 /* ConstraintMakerRelatable.swift in Sources */, + 17BE0F4E51B0FB968125F1A520607FD8 /* ConstraintMultiplierTarget.swift in Sources */, + 62F299B4704A7C95FB5866C6CDE2E2FD /* ConstraintOffsetTarget.swift in Sources */, + F343BA4E457FFDB0165492AECAEF0BCC /* ConstraintPriority.swift in Sources */, + E36244E8BF4AC941E82DAF16DDF4BBC2 /* ConstraintPriorityTarget.swift in Sources */, + E8EAADACF3BAE33BDECBC7214EAE9CD2 /* ConstraintRelatableTarget.swift in Sources */, + D59C2826AD288ECFF576B2AFA312716C /* ConstraintRelation.swift in Sources */, + F24D06C23DAB2F52A30C886A7A8177C7 /* ConstraintView.swift in Sources */, + 1E9EEA756F2774D73347F1660EEFE3E9 /* ConstraintView+Extensions.swift in Sources */, + 5E8BA529DFB4529006967624044FEC1C /* ConstraintViewDSL.swift in Sources */, + F10586462FB54CEA169A1A7A469A926D /* Debugging.swift in Sources */, + 43863B6D6A0E47B6648BB7B469736EDD /* LayoutConstraint.swift in Sources */, + 4CA13A0527BC57DE2C54A0F3B5ED8652 /* LayoutConstraintItem.swift in Sources */, + 968B4874A9F12D67C8B901136C9C8157 /* SnapKit-dummy.m in Sources */, + 3CD5FAFC746A76D73C3F501734199DFF /* Typealiases.swift in Sources */, + 144DA93A55A598F5197F10C729FBDD69 /* UILayoutSupport+Extensions.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 11BC5CF112CA34A070EF082B94C90D1F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FFE93350F3FFCD907F5824BB097FCB52 /* AddRef.swift in Sources */, + 074F2C0B76CB8E6B2469BC38CBF3AD72 /* Amb.swift in Sources */, + 2E134F2B82EF1A0A8E98A461DC9BA631 /* AnonymousDisposable.swift in Sources */, + 043F83AC76D2FB2268B91C06651F1A8C /* AnonymousObserver.swift in Sources */, + 0DF5F8B4A94FA40A38EF4765E918BA42 /* AnyObserver.swift in Sources */, + A392A4AB1CDBE4F4BF1E6451074E1EDE /* AsMaybe.swift in Sources */, + C1C0E2AB487C2D515DAFD58B382293BB /* AsSingle.swift in Sources */, + BACBE6C091D4012095FB22981B3C2616 /* AsyncLock.swift in Sources */, + 2D54A6F4D7229B917C6BF41E6C5DCB58 /* AsyncSubject.swift in Sources */, + F84729EDCA858AF15F83257741352872 /* AtomicInt.swift in Sources */, + 70917925E9105D38F63D920C592E5240 /* Bag.swift in Sources */, + 73BA2DACFAECAD7153E206434CCA1CAF /* Bag+Rx.swift in Sources */, + F069E274658024F75333D4E423C4D050 /* BehaviorSubject.swift in Sources */, + 6F45F1B2F2A1654AC02DECC42FA02A58 /* BinaryDisposable.swift in Sources */, + 3038C2E2B7542B3AB8131B81424CDCDC /* Binder.swift in Sources */, + 6DB650B92A505AC2F62BD77615A1D2FD /* BooleanDisposable.swift in Sources */, + 047028E10E1DFF0233C919FB1148AE03 /* Buffer.swift in Sources */, + 674AEC9F05744B4C977CDA7A8967CABE /* Cancelable.swift in Sources */, + 6E702FE34E6DD5A6B6C57C50C8F0783B /* Catch.swift in Sources */, + 05E90BD45B7BBD7DC82A14074FDB0751 /* CombineLatest.swift in Sources */, + 3532586AA98F718BB4D475E26B8279F5 /* CombineLatest+arity.swift in Sources */, + BEC47341045E090EAA1817BC4E7B190D /* CombineLatest+Collection.swift in Sources */, + D84EC8CED594C059B08D47DEF08CF8E7 /* CompactMap.swift in Sources */, + 482527EC3E623021997866C1ACCA1343 /* Completable.swift in Sources */, + D291B7FED40C98F386A898A6E1DB37DD /* Completable+AndThen.swift in Sources */, + 945C6DC7FEF1B06D689E3FECB099F652 /* CompositeDisposable.swift in Sources */, + 36C83ECB5C07B2A6F9432D78CA5EDA28 /* Concat.swift in Sources */, + F8D855D58CB3938A6A6781E73B53C411 /* ConcurrentDispatchQueueScheduler.swift in Sources */, + FB5B8FF848673973A8AA577926781DF1 /* ConcurrentMainScheduler.swift in Sources */, + 74C08C8EA83869938C7A25C9A88D22F8 /* ConnectableObservableType.swift in Sources */, + 34737FCF80EB891F68EF7449985DE544 /* Create.swift in Sources */, + F3E9D2D841ED90799F0B52286BDAF937 /* CurrentThreadScheduler.swift in Sources */, + 653B61D0B8A3004974DBE0AFC9B37AF2 /* Date+Dispatch.swift in Sources */, + 98F985B972592091D033FB84ADC7CAC1 /* Debounce.swift in Sources */, + 7B36C7B7BAAC6A742AE38C98484D9AE6 /* Debug.swift in Sources */, + BA4DB50479A93EAD2BD1381CAB7D926E /* Decode.swift in Sources */, + 595B1FB5D2B65054035261346DC105AF /* DefaultIfEmpty.swift in Sources */, + D26EB44DE97B01F75A7BD1238EECF902 /* Deferred.swift in Sources */, + ADDC43CFB0D46CACFE765C2A708F8D28 /* Delay.swift in Sources */, + C403D56540C5E9371AD79B1C07976DE3 /* DelaySubscription.swift in Sources */, + D14A5AB813E4DFF35A3B00A99BCA52A6 /* Dematerialize.swift in Sources */, + ADC248F460EF445A0D5B67450A01839B /* DispatchQueue+Extensions.swift in Sources */, + A3CE32243E84303A2D146EEE78044EB9 /* DispatchQueueConfiguration.swift in Sources */, + BC458D8EEF99A5C7FB5BBCC345FF5BB5 /* Disposable.swift in Sources */, + 743E4C01D4872CA7723D9BF9F6A5D59C /* Disposables.swift in Sources */, + A1B89609AB49417FB424FAF9B2310F72 /* DisposeBag.swift in Sources */, + 05BC0D78A16CBD4355700DE7E7ABC1BD /* DisposeBase.swift in Sources */, + 9CC74656D849D327FB463AE05CDBCFBC /* DistinctUntilChanged.swift in Sources */, + 7D7E665800950F8B498A956A385639BB /* Do.swift in Sources */, + 2E6B9D42DCB19234F4D78BD2414DA3CB /* ElementAt.swift in Sources */, + 4ABE13EFC755B386D82CE75AB8BB9BDA /* Empty.swift in Sources */, + 73FDC454634CE5926EAAB69DE8944A32 /* Enumerated.swift in Sources */, + 4147793AD077CAF6648567B479AB387A /* Error.swift in Sources */, + 3DF3AD9CC46A68BC88BDA42594F73911 /* Errors.swift in Sources */, + AE2FEB2F12262748259016973292183D /* Event.swift in Sources */, + EEAD705E4BB647E0BCEF532836557078 /* Filter.swift in Sources */, + EF72D9648FAF9510F9F45DB54FD70918 /* First.swift in Sources */, + BDA7A156A12164C755BB71EF2118CB66 /* Generate.swift in Sources */, + AB7A0A676C7772470D72188B526C5160 /* GroupBy.swift in Sources */, + 1383568E0420C3831A67240BFDC73BE1 /* GroupedObservable.swift in Sources */, + E3EAE8A06C546BF367E779589458015D /* HistoricalScheduler.swift in Sources */, + 6ACA51DA70224B785DA1F9C9071CAA76 /* HistoricalSchedulerTimeConverter.swift in Sources */, + F0AF301D8EF09CFE16C2145591BACE04 /* ImmediateSchedulerType.swift in Sources */, + F2F8CDBFCE1889794E7A9F01B32AB9B5 /* Infallible.swift in Sources */, + 23A5EB716BC87C36228E9E9CEF96F1DB /* Infallible+CombineLatest+arity.swift in Sources */, + 4475AC7E1DABCB3149A11BDA941FC30B /* Infallible+Create.swift in Sources */, + A3868E3FB80103D4EC40A361B74B92B4 /* Infallible+Operators.swift in Sources */, + EBCA74E902BE99A736AEA573BEA5B6CD /* Infallible+Zip+arity.swift in Sources */, + BC9B08914E282476538AF6506ECE6A2E /* InfiniteSequence.swift in Sources */, + DCC85644FAA3FD3043D980859424A912 /* InvocableScheduledItem.swift in Sources */, + 39C14E278AD856E7549BD6FE3B4A0557 /* InvocableType.swift in Sources */, + AC9AE764EAB1C65078F0D3926C4C9FD9 /* Just.swift in Sources */, + 24F623776AD8527B08372983A2A71778 /* Lock.swift in Sources */, + 82FBD2B7C1EF83494D5AE1C328212488 /* LockOwnerType.swift in Sources */, + 8A41383549AED0DE41709306C7D63DFC /* MainScheduler.swift in Sources */, + 247D0F213507F51B66F9EEFDEC262250 /* Map.swift in Sources */, + B8C99CF3DE63D713A71F79B20D42C7DD /* Materialize.swift in Sources */, + 3CE45B10C39699F9A3F92F64B599215C /* Maybe.swift in Sources */, + 98A6AF2289B5C85BEFC492099F4AAB2C /* Merge.swift in Sources */, + 8670DF35FF314F88247A38208C5A376A /* Multicast.swift in Sources */, + 2DD8AF8A98A4072A1F5447E0FFD55B09 /* Never.swift in Sources */, + 45E4B0E2D63AB3C1763DEA7393891463 /* NopDisposable.swift in Sources */, + E9A6248F48B7EB642F3418875A5A9556 /* Observable.swift in Sources */, + 62815773AA8209068D20C2BDB0879223 /* ObservableConvertibleType.swift in Sources */, + 327AAE190E95AA55FCC8BE533639DD56 /* ObservableConvertibleType+Infallible.swift in Sources */, + 7D277A69B12123C0120607B1EF392E87 /* ObservableType.swift in Sources */, + 016D4D3888A5AC8A1D3B85B3B84F5630 /* ObservableType+Extensions.swift in Sources */, + 8C93569C689ACD00E456B23E73D80BFE /* ObservableType+PrimitiveSequence.swift in Sources */, + 787514B3319DAFFBAEAF87B259006805 /* ObserveOn.swift in Sources */, + 890CC10F66302B68299B534848CB8B85 /* ObserverBase.swift in Sources */, + 508783CD55FA16BDB4019BEE545BE0D3 /* ObserverType.swift in Sources */, + AC5EB10C38F324E227F38EBDC929F864 /* OperationQueueScheduler.swift in Sources */, + DEB672EBC82C938FBA8595464B0761FF /* Optional.swift in Sources */, + 2C25912842315A22E31DA59BFEADE101 /* Platform.Darwin.swift in Sources */, + E8A1BCC9FD45BBCB48F8201286F65D82 /* Platform.Linux.swift in Sources */, + 024E8F7B20ADD67F41221E857D45CB4B /* PrimitiveSequence.swift in Sources */, + 06AE486D6684BB4675A6FAE0EF7BDD10 /* PrimitiveSequence+Zip+arity.swift in Sources */, + 2F66150D2FD47CA8479EDC4B3FE14BF4 /* PriorityQueue.swift in Sources */, + 995F464575B20E78B0C124B9459E702E /* Producer.swift in Sources */, + 17E19EA54D755CE77F1583420314128D /* PublishSubject.swift in Sources */, + 670BD4A21A32FB96FA076DC9BB475A33 /* Queue.swift in Sources */, + 078FBD69F399F3B3CBF722F3D10379A4 /* Range.swift in Sources */, + D51F43300FBBF9F3642F4852BEB2D957 /* Reactive.swift in Sources */, + 2657F78072FBBC8525C416CBB9D4FB14 /* RecursiveLock.swift in Sources */, + 9CC401020A54F5F9E9C3D91D7B4AE77B /* RecursiveScheduler.swift in Sources */, + 38A40573B5727C618A65FA918FED55A2 /* Reduce.swift in Sources */, + 855C1CF730DC09A4545491BFF611B823 /* RefCountDisposable.swift in Sources */, + 34570F3C31C86DEFE70F58BD94BEF595 /* Repeat.swift in Sources */, + E5AB59421B29F44BCDE1F2A7D01A6801 /* ReplaySubject.swift in Sources */, + 15038A10A82131B5D91E94668F3043E0 /* RetryWhen.swift in Sources */, + 26CA566E8D825C806717F2877A152D92 /* Rx.swift in Sources */, + BAABF3FC2F7E7E34A91A2D2274163E98 /* RxMutableBox.swift in Sources */, + 3B3D152A81491E1C8377FDAD7D37E720 /* RxSwift-dummy.m in Sources */, + 26319EDD7F4262FDFE348EDB3888DF72 /* Sample.swift in Sources */, + 9E9547A1D2F5A629C392D6EB55B2CE7C /* Scan.swift in Sources */, + 938E3D465A86F41C64F2E1774A2D14CA /* ScheduledDisposable.swift in Sources */, + C89FF9E911A1F953A96A9542C6AAAA1A /* ScheduledItem.swift in Sources */, + 19249139AD95AE769B08AEF313AB6F69 /* ScheduledItemType.swift in Sources */, + 7F19ABB4D0B4EA343EE7C8266A80A92F /* SchedulerServices+Emulation.swift in Sources */, + FC5FF4D5AE997DA8547B55E6DB0AF411 /* SchedulerType.swift in Sources */, + B87486D885CFEFFD0C365B4742BB013C /* Sequence.swift in Sources */, + D74A1E17E125AFD63C56EB745F364878 /* SerialDispatchQueueScheduler.swift in Sources */, + F2F6C65105BEF1168B87AF43B08DC062 /* SerialDisposable.swift in Sources */, + AAF660F2B3CE8E2BF423D0F97B20B16C /* ShareReplayScope.swift in Sources */, + 3A07899E85E6FB676A43189205C325DF /* Single.swift in Sources */, + 84648F04C89B3344A503049AE2344D36 /* SingleAssignmentDisposable.swift in Sources */, + 2356D3F4002DA73FFF29532A6E46B81C /* SingleAsync.swift in Sources */, + 11C61D1C07842BA31AC919BBE8C945C2 /* Sink.swift in Sources */, + 9EDE0E2AC392A11A8048310C760DB0F3 /* Skip.swift in Sources */, + 61F68C272EDB42E7B8AFB512A11E819C /* SkipUntil.swift in Sources */, + 669420900229BD5DE7A7B7EEACB2C5CA /* SkipWhile.swift in Sources */, + F4EF5556C5D4CB38C03FC3322A768AB1 /* StartWith.swift in Sources */, + BDA9D77308041B5E3BE5AE89565B37F4 /* SubjectType.swift in Sources */, + 28C6F8CA00102B3388800AEE0FEC9B36 /* SubscribeOn.swift in Sources */, + 96CFE0501DE851C5C7E1E23BEB5BE259 /* SubscriptionDisposable.swift in Sources */, + 25DAE084C22F018D4FD26A0CDC1EB3D5 /* SwiftSupport.swift in Sources */, + 660E283AF231972CD7165B566CAA487F /* Switch.swift in Sources */, + AF62255D606B96D175C1896E131EA3AC /* SwitchIfEmpty.swift in Sources */, + EE32D902912DDE67C15A0ABF1CE19B00 /* SynchronizedDisposeType.swift in Sources */, + C051416713CFE621121265BD3553C9D2 /* SynchronizedOnType.swift in Sources */, + 2D4559869409A3351874F5370868033C /* SynchronizedUnsubscribeType.swift in Sources */, + D2A16148E1694719950E0A748086B3AF /* TailRecursiveSink.swift in Sources */, + ACA8DA6F28979DD495524BE7B918F18C /* Take.swift in Sources */, + 7618FCC1078531135C1CDFEE2611F91D /* TakeLast.swift in Sources */, + 5E443AA3466CCBDA19C7B16C421269E5 /* TakeWithPredicate.swift in Sources */, + DA65C3BA8B9C3048D8810BE53FEB6117 /* Throttle.swift in Sources */, + 3D54F55B562E67C4AB35ED725E04108D /* Timeout.swift in Sources */, + 092AFD0D15EA0C5A23AC8E37E65239FE /* Timer.swift in Sources */, + 7CA1733A94C18DB9B7B68FDF965C1DC3 /* ToArray.swift in Sources */, + B95F86F591566A619E54D0CCAFBF9AF0 /* Using.swift in Sources */, + 4810CB587998CA2D2813FED0F8F3DFF6 /* VirtualTimeConverterType.swift in Sources */, + 83B47C9B322E517D85EFFBDB6A9C536A /* VirtualTimeScheduler.swift in Sources */, + 5EAB4643D7EE612FF0DD0F7D11288863 /* Window.swift in Sources */, + 998C56F6835B30FF5071B39480B5C8F5 /* WithLatestFrom.swift in Sources */, + F74B9496C841CAABC6F753FFDEAD7022 /* WithUnretained.swift in Sources */, + 06F4F2CD428BB536AA64F1830DDF41D9 /* Zip.swift in Sources */, + A3D8A9114B5767604A49DA50827F19E1 /* Zip+arity.swift in Sources */, + 37268A5E666EAD38A8E412B2626DEFAF /* Zip+Collection.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3DD73B13896A894B2FACEC8084E0B0A1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BD6E20E0209D4B01ABF7642506F583F5 /* AnimatedButton.swift in Sources */, + 3610F2C29CECD76224B45F870A20BD42 /* AnimatedControl.swift in Sources */, + 22546F34DC8AFFD4787B3C3770C21F01 /* AnimatedSwitch.swift in Sources */, + 047BE588B6EEEFD95C74C64CA1C0BD81 /* Animation.swift in Sources */, + 49BF03182077B22857C2855EEC0798C2 /* AnimationCacheProvider.swift in Sources */, + C92946ADA88B4CAD47524ACA731441BF /* AnimationContainer.swift in Sources */, + B547F42465BDC15F134837E6B555F924 /* AnimationContext.swift in Sources */, + 4C6F321163D29CD3DABAEB08A178601D /* AnimationFontProvider.swift in Sources */, + CF38C7EAE9C54B2000BE23D8549E6CDB /* AnimationImageProvider.swift in Sources */, + CEDCE669E51F7B8B8EBAF1583B8D4CD0 /* AnimationKeypath.swift in Sources */, + C3F495518D47871CA7BACD476A4D426A /* AnimationKeypathExtension.swift in Sources */, + 7B2C37E4FDCA29C551A6C9DCE0505137 /* AnimationPublic.swift in Sources */, + 843588510847505E149784E74D2CB687 /* AnimationSubview.swift in Sources */, + 505A0698D846ABF6E2A2413789B89D3A /* AnimationTextProvider.swift in Sources */, + 967C1562F78380A677F3539A185DCEDA /* AnimationTime.swift in Sources */, + C1CF4AC823B7E034DB6CB5DB0EA08CA3 /* AnimationView.swift in Sources */, + 861C9EB0C760A8D446C3A4F1320E2C06 /* AnimationViewInitializers.swift in Sources */, + 3AF28B4E2467590CC9C9AC65BBCD71E2 /* AnimatorNode.swift in Sources */, + 4B7F8E0C244B08EDCAAD9AF99193CBFA /* AnimatorNodeDebugging.swift in Sources */, + 459F2B9F92966946BA75A00EF1903803 /* AnyNodeProperty.swift in Sources */, + 08CF585A5947964954E7ACB70910985F /* AnyValueContainer.swift in Sources */, + 4BCB6E64B090ECA7E41B5C26E6E05D9C /* AnyValueProvider.swift in Sources */, + 0618111154400B212A90E0755CE2346E /* Asset.swift in Sources */, + E1EF2C933B2B790C8D72E7914B36C8E8 /* AssetLibrary.swift in Sources */, + EB7BC796352967DC142B4D17BB21AE0C /* BezierPath.swift in Sources */, + 84CD1A3D6E57178F901C732FE0B61C95 /* BundleImageProvider.swift in Sources */, + C2DB5CB595C2BE3D8C5E24758F8F1ACF /* CGFloatExtensions.swift in Sources */, + 6AEDF3D1798888D99C3C7C6BD2F3779F /* Color.swift in Sources */, + EA0E379F526BD011CD5ED39FCB01E877 /* ColorExtension.swift in Sources */, + 12EC6D92F5D1612E2293F1B808D0A27E /* ColorValueProvider.swift in Sources */, + A9D6ED2A2795D2257153EDA170AEE556 /* CompatibleAnimationKeypath.swift in Sources */, + 59B555B51F6C00939F675E74B00EA92F /* CompatibleAnimationView.swift in Sources */, + 53A5C4AC5D469408BA8EBB350596C5F4 /* CompositionLayer.swift in Sources */, + 7F101E76AA506DB15D2D392E9FFBE11F /* CompositionLayersInitializer.swift in Sources */, + 2D038D93CEE0C88E51E744FB034F76BB /* CompoundBezierPath.swift in Sources */, + 876BEAC75F36A8BE7DC6FFE1CCED3136 /* CurveVertex.swift in Sources */, + 4700CB6BDC06861FB8675B3E9481F6CB /* DashPattern.swift in Sources */, + B06B474BA6F82DC1EBFF2B199724522E /* Ellipse.swift in Sources */, + 7D63A41230675587C871B7DC59D0CAC5 /* EllipseNode.swift in Sources */, + D17D6E8C80189277F66FF2EFD403BBE9 /* FilepathImageProvider.swift in Sources */, + A9A47BC5110048309D88B3A183994EC5 /* FillI.swift in Sources */, + FF753AA4B09998C58D092BAC010486F1 /* FillNode.swift in Sources */, + B9A197B0BAB8CA9F17A46D4440AC712E /* FillRenderer.swift in Sources */, + 41AEBE3D7FA634427F4C61A01A9B5B3B /* FloatValueProvider.swift in Sources */, + 3D674DAEAD9EEEAF023B6EE96C984C5B /* Font.swift in Sources */, + 55100F4BEC29276C7C6BCCF1C73F213A /* Glyph.swift in Sources */, + D27EDBD7FE5BC261F1B8BADD6AA9892B /* GradientFill.swift in Sources */, + D1FE79A7F36545B8CB44D97A93E74909 /* GradientFillNode.swift in Sources */, + 0DB08820C29F9A3AD174E05C1159C78C /* GradientFillRenderer.swift in Sources */, + DF20FA3D69BC752B01D65651AF876198 /* GradientStroke.swift in Sources */, + F9F9EEDDDE7B9C9DB5D0AE5A5F07BA21 /* GradientStrokeNode.swift in Sources */, + 4A2672188800EA69DF8496907162697E /* GradientStrokeRenderer.swift in Sources */, + A1CF368CE7252F8B8961C47586C178F2 /* GradientValueProvider.swift in Sources */, + D552C4D405D459DF6E986C8F1BAC6C3F /* Group.swift in Sources */, + DB77444F78DE46BE31E894569DA13580 /* GroupInterpolator.swift in Sources */, + F8EA1161304015542DB2F9F4F5AE000F /* GroupNode.swift in Sources */, + 44FA570548F4A7ECA029A49106D0D959 /* GroupOutputNode.swift in Sources */, + 3BB830496EA62C8CF3D95D868A0C9D5D /* ImageAsset.swift in Sources */, + 4680B52D35120A71C11ECBA5314E2187 /* ImageCompositionLayer.swift in Sources */, + F586BFBF4CCD51FE05A441FB76C9645D /* ImageLayerModel.swift in Sources */, + E82CCB58C2D28ECA230EF4E18C60FD1B /* Interpolatable.swift in Sources */, + AEFFE0F8CC99EAFD362E53DC63970243 /* InterpolatableExtensions.swift in Sources */, + 9208290CA7980F567B71D2D74DC0DEFE /* InvertedMatteLayer.swift in Sources */, + D13F75C1987BC40A12DA262771EB8178 /* ItemsExtension.swift in Sources */, + B6C30F158F113B17E8D8156D78540A95 /* KeyedDecodingContainerExtensions.swift in Sources */, + 67C58CFFF7E94C6235B1A857EA921F3C /* Keyframe.swift in Sources */, + BEACA23AAFFCDF4B7D9F82C9A04FA345 /* KeyframeExtensions.swift in Sources */, + A515A3A3B2CF6958FAA17D86A579DDFB /* KeyframeGroup.swift in Sources */, + 03C184B386BC437000BA957FAB24DE26 /* KeyframeInterpolator.swift in Sources */, + 03DD607FF2E024C83F3CA482FC681E52 /* KeypathSearchable.swift in Sources */, + 09A29DDA49E800244859F5DDC4307C13 /* LayerDebugging.swift in Sources */, + AA49099C1F3D0549158D3A9B2DD3D6E6 /* LayerFontProvider.swift in Sources */, + 661778AC0812FF0081A94E899B339F77 /* LayerImageProvider.swift in Sources */, + BC9A4262101924828199108EA8965486 /* LayerModel.swift in Sources */, + 08B5EF23E86D67EECADDE2D39B03C557 /* LayerTextProvider.swift in Sources */, + 283651FE159A0D98ECE27527A434469F /* LayerTransformNode.swift in Sources */, + EABAFC404B8375289AC500B725D8175B /* lottie-ios-dummy.m in Sources */, + 9CF94CAFCC98DE4F72B77E40AA760370 /* LottieView.swift in Sources */, + EA3850F7CA7A937EDAD766899110D730 /* LRUAnimationCache.swift in Sources */, + 61BBED7470DC5C4419884780188079EC /* Marker.swift in Sources */, + 19BFB80D74F610E326B28161F07CE38A /* Mask.swift in Sources */, + EE253C86DD49455C9A9EDDFF5170FCDA /* MaskContainerLayer.swift in Sources */, + 478E6877D343FB3036F1ACB05BC9715A /* MathKit.swift in Sources */, + 0216178994AB68CF35038568D738DE92 /* Merge.swift in Sources */, + 79A3FB163FD740818AF7C0FCB1772DF4 /* NodeProperty.swift in Sources */, + B2D2DF2EC4B3DD3FDC5A81B1BF0E5F66 /* NodePropertyMap.swift in Sources */, + 1D91FD32BEADDD9796BF802700FEE968 /* NullCompositionLayer.swift in Sources */, + 8D3213017B92C533EB9E127BA5563BBD /* PassThroughOutputNode.swift in Sources */, + 05D207C109285670CC665E49B55AD485 /* PathElement.swift in Sources */, + 4EE7583081DD2A762FA35A2A7C54FC56 /* PathNode.swift in Sources */, + 0757D2C17526F2CAEBD6D7BC0D399EA8 /* PathOutputNode.swift in Sources */, + 75D86DA3C2D36884965F757171B628E3 /* PointValueProvider.swift in Sources */, + 7B98805FF1F385B8B4387D57BA0A9090 /* PolygonNode.swift in Sources */, + 16625D9331228E7A690819C60A2991A3 /* PrecompAsset.swift in Sources */, + 26EF0B340EFE29CD9278F2237085A86C /* PreCompLayerModel.swift in Sources */, + E509D9386E5FD1690581CFA40DF43410 /* PreCompositionLayer.swift in Sources */, + 944C78C2EABCD498AB74F5CCBB17D2AE /* Rectangle.swift in Sources */, + A748A04163F32EA3AF9B2E4516D78DDD /* RectNode.swift in Sources */, + D23BB4F9F4104BFA265E4E241C634BFD /* RenderNode.swift in Sources */, + A5AE75455F58AFA8091A87C1539A0E37 /* Repeater.swift in Sources */, + 476B533C5822CF0D778A6BB5EA1E7916 /* Shape.swift in Sources */, + 1EBEC0DBDAC11B78976FDA5BA5188FC5 /* ShapeCompositionLayer.swift in Sources */, + E3C44D0364C9A3BDE105BC752FA90CBA /* ShapeContainerLayer.swift in Sources */, + E3CEBFA597BF0016EADDC35EF6C783BC /* ShapeItem.swift in Sources */, + 6587B749518669C9950777734423A245 /* ShapeLayerModel.swift in Sources */, + 9067F373822D84F800203D89278E08E0 /* ShapeNode.swift in Sources */, + F9BC5623C245EAA0B9B811C9680C314F /* ShapeRenderLayer.swift in Sources */, + C8413231EA7E3A9AF268C845AA0FC32A /* ShapeTransform.swift in Sources */, + DC5E4DB7351FDA603E65BFED8D6178C3 /* SingleValueProvider.swift in Sources */, + DA168E5E480E2F57B0BE8FD0A1FD64BD /* SizeValueProvider.swift in Sources */, + 9A12C0A11CC604DDD9ABD6C279E6CE9B /* SolidCompositionLayer.swift in Sources */, + 50F7404C67D49C3F124905E263893947 /* SolidLayerModel.swift in Sources */, + 9F20B18821E54566E6D16F393240B096 /* Star.swift in Sources */, + A960856B5EF2892D980158CCEC24A512 /* StarNode.swift in Sources */, + 4127F4FF9046879314D9DA3CB7D8C439 /* StringExtensions.swift in Sources */, + A69EC4C58ACCC0039D025DD4E3BBAC58 /* Stroke.swift in Sources */, + EE373836B715015237B9B2CC381A6D44 /* StrokeNode.swift in Sources */, + 76C6317D31C85D988550BB479703A02E /* StrokeRenderer.swift in Sources */, + 7CC6F389A6BAA882FD6D138EA0552095 /* TextAnimator.swift in Sources */, + EA40F22688E0DBF490B5160C3A347970 /* TextAnimatorNode.swift in Sources */, + 4C1D2F33A32937F016D0C68D5EE1AE0B /* TextCompositionLayer.swift in Sources */, + 16C8FC256C4CE275407038E626C430B1 /* TextDocument.swift in Sources */, + 8B25121213F37B3FD5A37ADB0A780CB6 /* TextLayer.swift in Sources */, + 14B051AB5008329CAD63246CCBD78F5B /* TextLayerModel.swift in Sources */, + 4A18A6CB333D9CB3A52BF554B77A570B /* Transform.swift in Sources */, + 753C2663E1979F0B2F76CE467FA19F59 /* Trim.swift in Sources */, + E4A9C89EF8D2F5C2D78205B4BFA7623E /* TrimPathNode.swift in Sources */, + 4EB8DC557500857899B36623C09000D5 /* UIColorExtension.swift in Sources */, + AB83BB2166917FF3675B1F3B8A08C919 /* ValueContainer.swift in Sources */, + DE05924421F7CB823B4766BC14DBF066 /* Vectors.swift in Sources */, + 0CA04306449F28C86466A60DB7E7E973 /* VectorsExtensions.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 41E6B6BBD659944B8D2BA5C9F9463E38 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 89559315BEB73C84E776677C8EBF01EB /* Pods-sopt_29th_Assignment-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FE9836A67EA3E51CA889A1AB95BC874 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A664924D6CCE2922A3F81EC932F4D476 /* AFError.swift in Sources */, + FEDBAD32E2EDA85AD6E362B82892A74A /* Alamofire.swift in Sources */, + 1773084DECF68CADD45567FBEC56036D /* Alamofire-dummy.m in Sources */, + A3153333FC136836B0028E6AB2A56BEE /* AlamofireExtended.swift in Sources */, + F36D96A4346C90A2D11CB3B6A2ECF4CF /* AuthenticationInterceptor.swift in Sources */, + 13E62623092B680C6A5C349D48B8A4FD /* CachedResponseHandler.swift in Sources */, + 97584BC08D2B494417BDEE268CFF38C9 /* Combine.swift in Sources */, + DCD0C33A2B50811D53CF68F021284B47 /* DispatchQueue+Alamofire.swift in Sources */, + 9CFDA7C92E0EEA31F709663B0E727ABA /* EventMonitor.swift in Sources */, + 52BE6F747C26DF2A24532458E55DC10F /* HTTPHeaders.swift in Sources */, + 02621C4B82398D0657F474E21493A3A2 /* HTTPMethod.swift in Sources */, + C16A047C4E8D856309A486182A490993 /* MultipartFormData.swift in Sources */, + 30A331CD9286145E92DB11D671664C63 /* MultipartUpload.swift in Sources */, + B6473B8E8353317F75D6800D4F7054CB /* NetworkReachabilityManager.swift in Sources */, + 471611F482CDC15BF464E3BA9CB83968 /* Notifications.swift in Sources */, + 2550F0D474DE846FEC5C76CBE85F927E /* OperationQueue+Alamofire.swift in Sources */, + 8B9CDBE3FFD712120CD66DD8B06C44E4 /* ParameterEncoder.swift in Sources */, + 4634BA717BFCE522E5B42304C6A78B5D /* ParameterEncoding.swift in Sources */, + 02DB462B121245593CE653B9B377F970 /* Protected.swift in Sources */, + DD58A00EACBEE274C381B491519C6B8C /* RedirectHandler.swift in Sources */, + E0C65E16219718869CD2AFCA2C5465CB /* Request.swift in Sources */, + F63BE0585331CAA3482EF736803F8243 /* RequestInterceptor.swift in Sources */, + 1D17B83410DC98911D539F2BD5254C05 /* RequestTaskMap.swift in Sources */, + C7F66519CE6148F21D7DB11423F1D34D /* Response.swift in Sources */, + 941822CDF68EB8F4D49F150457A82616 /* ResponseSerialization.swift in Sources */, + A4F1202CE5BBE79F3BBCAE3D2B16BC03 /* Result+Alamofire.swift in Sources */, + 512FAFBD71830F126224C033B6C45F4E /* RetryPolicy.swift in Sources */, + 8F9E1EEF2FE52E3231A769722D5C4148 /* ServerTrustEvaluation.swift in Sources */, + EC11B17DA78F7EEBEBC3EFAF68C6DF9F /* Session.swift in Sources */, + 688337B18659C4BF722F87AFC4FEEF81 /* SessionDelegate.swift in Sources */, + E1769C267E82B0C24FE0FFBF949F0A6E /* StringEncoding+Alamofire.swift in Sources */, + 5E594FA3290D3D70F500572D0AC100DB /* URLConvertible+URLRequestConvertible.swift in Sources */, + F5D2A31C7EB1DE010771140B6E7ABAD8 /* URLEncodedFormEncoder.swift in Sources */, + B89D1C69742F61878115334A1D2DFFE7 /* URLRequest+Alamofire.swift in Sources */, + E857ADCAD7B647883D5B2AEC3F16D1D5 /* URLSessionConfiguration+Alamofire.swift in Sources */, + D15FEA31AA9625BBF041FB91E48A9995 /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7B5BEB32F210EFE38F7D58FF8A1CC2DE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A3CEE8324948497036C4E123B21CBC59 /* SwiftyJSON.swift in Sources */, + 5FA526557719FDBE81B1974B113CF600 /* SwiftyJSON-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B305EAE1C6B0A6E3455ACC30A4731FA5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5615FDB610CE9BA1D0BFF89B9A5257A3 /* AnimatedImageView.swift in Sources */, + 1D75EBE5A8334EA0052EB286BD51AE32 /* AuthenticationChallengeResponsable.swift in Sources */, + E9BE1F32D0DA678D8593C665678862D3 /* AVAssetImageDataProvider.swift in Sources */, + 787BA6BBC90B8F6A78707BF992CD8B7D /* Box.swift in Sources */, + 5880747D56EA9504CFCB91A27102570A /* CacheSerializer.swift in Sources */, + EA96920B163965469397F346A65043DF /* CallbackQueue.swift in Sources */, + 4512E08421FABF56C88254012381979B /* Delegate.swift in Sources */, + 38CBD5B47484781EBD8CCE722F8D89AF /* Deprecated.swift in Sources */, + B7892F7510C7BAE53B1FB1504850740D /* DiskStorage.swift in Sources */, + 6C1352E8D74AC09B9A62E498BEB521B6 /* ExtensionHelpers.swift in Sources */, + 8AB17FA6B8EB58971DF433547FC6E923 /* Filter.swift in Sources */, + E969760912A8B3C7F8DA19AA0111000E /* FormatIndicatedCacheSerializer.swift in Sources */, + 01D943FA6C3498798643565DB390A395 /* GIFAnimatedImage.swift in Sources */, + 87F5E9DA1ECD4A4BBCF2A509BCA14947 /* Image.swift in Sources */, + B1BE54560B0DE6A294086544880A8D4C /* ImageCache.swift in Sources */, + 6DCB85FA3A3AAB40FE841711B901EAA6 /* ImageDataProcessor.swift in Sources */, + E41E3A6F3FAE1B76B9AB22687BC50CB5 /* ImageDataProvider.swift in Sources */, + BA1B763BE8CAE9799D6C650C0B07F7DA /* ImageDownloader.swift in Sources */, + 6C5BC6342C03A7D2F1BFDBB5D087CB08 /* ImageDownloaderDelegate.swift in Sources */, + ADF8DFE7C4E5E25FF75A84C3756577B2 /* ImageDrawing.swift in Sources */, + 47188F85260A6C84881F9E5C01496DC6 /* ImageFormat.swift in Sources */, + 2592D36AAC2594BE8E75A8F5141040A2 /* ImageModifier.swift in Sources */, + F098338BE9A17E97B04340DAA5A0B660 /* ImagePrefetcher.swift in Sources */, + 447744AABA6D0172810EC3B34236824B /* ImageProcessor.swift in Sources */, + B305BB4271B22CAD1C31181780A36754 /* ImageProgressive.swift in Sources */, + F6841C92A142C8F3680D83089B820CC4 /* ImageTransition.swift in Sources */, + B8BB86CD7B7CB7E27FFF043629798EA8 /* ImageView+Kingfisher.swift in Sources */, + 7347C527A87F0CDC12F50B3855B5F48D /* Indicator.swift in Sources */, + 88B8AC6029632517A72F63AFC12C5B3E /* Kingfisher.swift in Sources */, + 9B0C4E404F30F1AEAEE1FBE3A027FA5D /* Kingfisher-dummy.m in Sources */, + 7E4ACDCC3CC0F6A1B7EC8ECD64B83D62 /* KingfisherError.swift in Sources */, + DA47CB05965638DFE5B2A7062169534D /* KingfisherManager.swift in Sources */, + E4B2D5E0EF54A37DB3BCAE7328B5FD4F /* KingfisherOptionsInfo.swift in Sources */, + CA21B1B110FD066CC661B98E85D96729 /* MemoryStorage.swift in Sources */, + 6440487903AE496B5B0CE78022D7C4E2 /* NSButton+Kingfisher.swift in Sources */, + 40E76B8F9326C19C56089EA163D25949 /* NSTextAttachment+Kingfisher.swift in Sources */, + 5D4CC81D40F9408E73C5E4BAA5514270 /* Placeholder.swift in Sources */, + 91C2A156C0264EEFBB1C83787451AFE7 /* RedirectHandler.swift in Sources */, + 507044595704E8B86462582ABB193472 /* RequestModifier.swift in Sources */, + B5A92E0243CBB6CD7BABCAB2E2C4D256 /* Resource.swift in Sources */, + 6EB45229225932A7BE48AB1B9A54D569 /* Result.swift in Sources */, + 98241E64DA05272FA80194F03AF3199C /* RetryStrategy.swift in Sources */, + 093181D89BFA8C8FBE5FADCE51AC4E85 /* Runtime.swift in Sources */, + 9D18851445B1EFD750837CB21592295F /* SessionDataTask.swift in Sources */, + 5DEA5E130127037F3F7BD7D2B12E1E7C /* SessionDelegate.swift in Sources */, + F6919FE2F22301022F55ED6333F63FAA /* SizeExtensions.swift in Sources */, + 5B56F1C7F0598A78E720E4D0F888851B /* Source.swift in Sources */, + 1765A958437BF3E2C1A15B6DB68B975B /* Storage.swift in Sources */, + 73D036F6EAE83FED494970377AE0C12D /* String+MD5.swift in Sources */, + 923B375805761A521F28D04DDD84B504 /* UIButton+Kingfisher.swift in Sources */, + E86216CD124BC804B02B0158BA303990 /* WKInterfaceImage+Kingfisher.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C2C3D13EE11C41E2F86A52F3FDE4FA5D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2845BA44FED1A376014962A6C193A66B /* ListLoader.swift in Sources */, + F7A0AA8EA77891D0408D8CD9638D78A0 /* ListPlaceholder-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C81EB1347EFB7B8F025F46DDBF78A45B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 98CB55A8029728CCCE26047A5036E4CE /* AssociationPolicy.swift in Sources */, + E32900C8E0BAEA6DED9E37EBC806809B /* CALayer+Animations.swift in Sources */, + 3FC5414EC9FC6F6CBFCFDAE20563BAB0 /* CALayer+Extensions.swift in Sources */, + 21F7BA5FF2769F5E50BFEA68348A939E /* CollectionSkeleton.swift in Sources */, + 42CD03543D2E6551D6BFAA58199AEB63 /* Deprecated.swift in Sources */, + D7CF7E80F7E4FB130EAC466BF410DD7E /* DispatchQueue+Extensions.swift in Sources */, + CF28AE0CF7599B011DAD5E485E1D0DB2 /* GradientDirection.swift in Sources */, + D276053C0849D80F7ADA470D657D14C1 /* GradientDirection+Animations.swift in Sources */, + 4C4807533D9C80FA1A41206498B712C2 /* Int+Extensions.swift in Sources */, + 1F6A7438F6FDF9A30AA037DADD767814 /* Notification+Extensions.swift in Sources */, + D0BA9ACEAB82794C851AE801199598C0 /* Notification+SkeletonFlow.swift in Sources */, + 2E6550EDA354A83B07382CE344AEABE7 /* PrepareViewForSkeleton.swift in Sources */, + 71390993914649DEE98167EE490F4AEE /* ProcessInfo+Extensions.swift in Sources */, + 1C4EC804E8F498F823B68DB526FF3D36 /* Recoverable.swift in Sources */, + 9B692301E1D52EE349613955FA014E68 /* RecoverableViewState.swift in Sources */, + 2EDB25C9CD31B9B025ABD2E1D693A15F /* Recursive.swift in Sources */, + 34019564C5C98A565672FFC27018BDF9 /* SkeletonAnimationBuilder.swift in Sources */, + 802604F6837A93FE6722E5C5AEF91A41 /* SkeletonAppearance.swift in Sources */, + A612AD876F2009B32288E53A9C3EF222 /* SkeletonCollectionDataSource.swift in Sources */, + 38D1F9945A20E48EE0E501720A888CDB /* SkeletonCollectionDelegate.swift in Sources */, + E576A5317D9F3164C11702BAB11C464F /* SkeletonCollectionViewProtocols.swift in Sources */, + 2C540DCFDC6F8E190FA83880DE7BBFF7 /* SkeletonConfig.swift in Sources */, + F30082074D26D27A95FE9F3D82EBCAA5 /* SkeletonDebug.swift in Sources */, + 090D7FB5904E0FC4C50F8536764D6D3B /* SkeletonExtended.swift in Sources */, + 628059AB7BA3EF69BEDD42689D4CCE23 /* SkeletonFlowHandler.swift in Sources */, + A550954F1A2F8855F1CBB0C518AE8C0E /* SkeletonGradient.swift in Sources */, + 15F220C3618C1E3F720475FEAF78661F /* SkeletonLayer.swift in Sources */, + 6329167CA0A6D5885EA63ECDF0D29FF9 /* SkeletonLayerBuilder.swift in Sources */, + C0A070E7EE584BEFC55190BB1B978697 /* SkeletonMultilineLayerBuilder.swift in Sources */, + FE9014A2371F738944ED0FDD3B2CFFB1 /* SkeletonMultilinesLayerConfig.swift in Sources */, + 84D5EFC338A8F4982B55D6B06BA03F48 /* SkeletonReusableCell.swift in Sources */, + 67975D9D65BC7E2F5C007BA1E086DC06 /* SkeletonTableViewProtocols.swift in Sources */, + 4EE1F030245C299E2BB2375CB14B0241 /* SkeletonTextNode.swift in Sources */, + 3CEEDAD8F50DB77D1BDBBD2ADA78CF17 /* SkeletonTransitionStyle.swift in Sources */, + 7A0553AB2F1A53F7B21579734AA6EB87 /* SkeletonTreeNode.swift in Sources */, + 98CAEDFDBFAC617AFDCA5452B790C283 /* SkeletonTreeNode+Extensions.swift in Sources */, + C5805A0100B5CA98C19A7D02813D01B8 /* SkeletonType.swift in Sources */, + E9C20CBEEA6B0F9C92E21B336DA24112 /* SkeletonView.swift in Sources */, + 3927997BB85A4DD42717797E025E8826 /* SkeletonView-dummy.m in Sources */, + 528FC1CA236EFA61CA43894D0A2C5B96 /* SubviewsSkeletonables.swift in Sources */, + C174156410407591E73348E291BAC330 /* Swizzling.swift in Sources */, + FA61B2655653E75EABEE2F65E3A55048 /* UICollectionView+CollectionSkeleton.swift in Sources */, + D49F135F9B911D7E1AE35870E8C7ADFA /* UICollectionView+Extensions.swift in Sources */, + 4EEDB45F2DDBCD0D0D213A801A7B09EE /* UIColor+Skeleton.swift in Sources */, + A7D4105D2351D2F90AB88CBFB147E170 /* UILabel+Extensions.swift in Sources */, + 2F0C9F44FD3AD47DDFC47E0D447EDD81 /* UILabel+IBInspectable.swift in Sources */, + 610E8FA6DBC3690E8DB7616E0389CF4B /* UILabel+SKExtensions.swift in Sources */, + 09F2ED0DDE23A30CABF4B9C36C722096 /* UITableView+CollectionSkeleton.swift in Sources */, + 4153B903876D19347BAB9596EB94707C /* UITableView+Extensions.swift in Sources */, + 7FFF6A07CE06086379767B9A4462B223 /* UITextView+IBInspectable.swift in Sources */, + EB1DAE03A8C61696A29D130CA7BBD2DC /* UITextView+SKExtensions.swift in Sources */, + 287CC3349411453BC71DFD4DEDA52BC9 /* UIView+AppLifecycleNotifications.swift in Sources */, + 1A0BFCD16FAD69F17736551A5D27262C /* UIView+AssociatedObjects.swift in Sources */, + 7AA2D1AFEF137A1CDE9014885BF7E7EA /* UIView+CollectionSkeleton.swift in Sources */, + C109CE5E629F211619D0AA184E406122 /* UIView+Extensions.swift in Sources */, + 7EDF4A4786BF27B10D07275427BBA4CD /* UIView+IBInspectable.swift in Sources */, + 77F9AE6FF8AA6303492F6E37D57218ED /* UIView+SkeletonView.swift in Sources */, + 591FC15E43DF0201FD978AAED60812E8 /* UIView+SKExtensions.swift in Sources */, + 8588448262230A0643BE8EB3BBD8FE36 /* UIView+Swizzling.swift in Sources */, + 415C5905FFE8D629B9A11EAEBBF780A6 /* UIView+Transitions.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D2DBC21241DC6AC2CB1405907058A8E6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4805CB07760ACB4F6CD9AD2DDA6A3198 /* AccessTokenPlugin.swift in Sources */, + BFA1536E972A7E8266BD74C2771FBFAF /* AnyEncodable.swift in Sources */, + 743B669698434D7300922601465DCE62 /* Cancellable.swift in Sources */, + 3D94CFF2A5A7C85B6A85B662327B67C0 /* CredentialsPlugin.swift in Sources */, + 8B649F531E6ABDDB4008CFA8F6F670DD /* Endpoint.swift in Sources */, + AD1B944836523F2827AC7F43A79D0FEB /* Image.swift in Sources */, + 65029D089337A48EC4D0055E29E30A97 /* Moya+Alamofire.swift in Sources */, + 926B261B45D4C5FD5ED5733C313838F1 /* Moya-dummy.m in Sources */, + 59B56C56C55B8AE7FF142CAD2B59FD51 /* MoyaError.swift in Sources */, + 8FD03CB2DC0FDA1E9636D373909DDDE6 /* MoyaProvider.swift in Sources */, + E824EBD8A2671CC76B497F4F5B65DB25 /* MoyaProvider+Defaults.swift in Sources */, + D109B412294FE281603BF403C33C6EEB /* MoyaProvider+Internal.swift in Sources */, + 190810DE6417E143E4FCFC4835706638 /* MultipartFormData.swift in Sources */, + 7121DEA57978B70F6973FE651AB88561 /* MultiTarget.swift in Sources */, + BAE6F428F0027E5AC5115E2AF060E0E7 /* NetworkActivityPlugin.swift in Sources */, + BBB7A1F02BE6A68A27F610816B89D62E /* NetworkLoggerPlugin.swift in Sources */, + A673B8FA85DAAA5F0E1E6C111479D0AE /* Plugin.swift in Sources */, + 5BA4B59005579BF090EB06953A0DEFEF /* RequestTypeWrapper.swift in Sources */, + 9E7129BF4046FAF7D85245489EE29B5C /* Response.swift in Sources */, + B73DE72E42CF89C320EAC875E47D61BA /* TargetType.swift in Sources */, + 3578D665C9C31F719E06D9D9DAF96C48 /* Task.swift in Sources */, + 3B074EF87B82EC659717ED824DAB6A41 /* URL+Moya.swift in Sources */, + 85B4ED0D6B1B81D8100C84E4C559DA14 /* URLRequest+Encoding.swift in Sources */, + 1844F9B8011F32E1455386DC5E870E80 /* ValidationType.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D9DF5AEE1B525A8BA763D0DFA7241A71 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3091F1A82E0FD6ABA766EBC91D4E5DE6 /* Then.swift in Sources */, + D936EF159A167C7E4C5E5764C22F458F /* Then-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E11F84192A9F8312DF1916303046C64B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FAFB4D51449BA3500DED875A79120781 /* BehaviorRelay.swift in Sources */, + EC741535DD70102DEE8FB9D57984AC0E /* Observable+Bind.swift in Sources */, + 8DAB16DE913A7BE02FA4F6E98731044F /* PublishRelay.swift in Sources */, + C5F4366AF47030DD66F19914E67B5FAB /* ReplayRelay.swift in Sources */, + CD8F79531679DC41E33E8FC3CB487EED /* RxRelay-dummy.m in Sources */, + 381A02F6ED67B17114AD8E6508EF9EF3 /* Utils.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F3A28FDE156C7CAA6CA5FC5646AD34F4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B8E27E8D24CBE6DB22F38E06FFBDB710 /* _RX.m in Sources */, + 4878A6C8BDEF6FCC155719CA93BA9586 /* _RXDelegateProxy.m in Sources */, + 894BF76C4272C38C9E17385110BF4A41 /* _RXKVOObserver.m in Sources */, + 529BDA5E8CE104C4B384017447D0DC60 /* _RXObjCRuntime.m in Sources */, + D709A58FF6A694878122F7D24B4A9913 /* Bag.swift in Sources */, + 9850A80051F5259DF4BD9060DEFE783F /* BehaviorRelay+Driver.swift in Sources */, + 71D5BDF4D210C1DC54AB197B1D2E9D13 /* ControlEvent.swift in Sources */, + 7C0DC741562A17F09F60EB9329DDA7CD /* ControlEvent+Driver.swift in Sources */, + 4F744303AF9B5E7CEF8C3A9327E852B9 /* ControlEvent+Signal.swift in Sources */, + 47B48B7531CE161773DEF0B851D08037 /* ControlProperty.swift in Sources */, + A1985C2CC5030AB984FFA33B94E1E39D /* ControlProperty+Driver.swift in Sources */, + 238C4A1EC8BA1D3A575ADA67F68CD09C /* ControlTarget.swift in Sources */, + 2722C9B25CF57D3AE89825729DEA9BED /* DelegateProxy.swift in Sources */, + 03D894819ECA3CA8F42C578E42D08960 /* DelegateProxyType.swift in Sources */, + 9B6D684A7CCF9470B92E10267E3987CA /* DispatchQueue+Extensions.swift in Sources */, + 5291A92FB6C7E3FB265DC22EDD908884 /* Driver.swift in Sources */, + 09997FDBE8364411FFB6F495729608D2 /* Driver+Subscription.swift in Sources */, + 155D953401DF644E75F2ACE729D00DF2 /* Infallible+Bind.swift in Sources */, + 1B402AACD54B2064A7BC86857F2769DD /* InfiniteSequence.swift in Sources */, + F6F9C34492E47A611E31D2D63F476F13 /* ItemEvents.swift in Sources */, + 28DDBE36EE067086F4925C830D668FBA /* KVORepresentable.swift in Sources */, + 50681D70D26BA315A5DDC1365B4CF0BB /* KVORepresentable+CoreGraphics.swift in Sources */, + A435E4B3FF0B326E880502C6FD3FC987 /* KVORepresentable+Swift.swift in Sources */, + 69537EEBAEE542798C9630CB8F96DF8D /* NotificationCenter+Rx.swift in Sources */, + 171A21B0155EA10267C1DE165A6E1500 /* NSButton+Rx.swift in Sources */, + 3B82FB00AD02652E1801233E5684DB1D /* NSControl+Rx.swift in Sources */, + 7EEED39CE5F3611AB4D7205FD038021E /* NSObject+Rx.swift in Sources */, + 945DBBCB62542CD24B29F83FAFEF13B1 /* NSObject+Rx+KVORepresentable.swift in Sources */, + A2F7FF2AEFF21D78671543FA8CB6A8B3 /* NSObject+Rx+RawRepresentable.swift in Sources */, + AB4875CA5028C3C32274EC2CCDFE9066 /* NSSlider+Rx.swift in Sources */, + 4B745396FD1223BA8532DFE2216E043C /* NSTextField+Rx.swift in Sources */, + 7E3402342205B2DC03468A7FD95F61A9 /* NSTextStorage+Rx.swift in Sources */, + 68623BC382EACE93D53213D1D5AAAD3C /* NSTextView+Rx.swift in Sources */, + 6D8CDC66C950346874056F3F45FAB0FC /* NSView+Rx.swift in Sources */, + 38D0534EDDC37793282AD797DF3CF4B0 /* Observable+Bind.swift in Sources */, + F059BB2BD4F7B156353739A55AEBE2A3 /* ObservableConvertibleType+Driver.swift in Sources */, + B283E0B7BB5A5910188B1B4C7B15FF53 /* ObservableConvertibleType+SharedSequence.swift in Sources */, + 04B641288248D3ACC28E7F707058073B /* ObservableConvertibleType+Signal.swift in Sources */, + 95181366D610146E29AD34636DB9EFB7 /* Platform.Darwin.swift in Sources */, + 0F75B8C82523266A3DF606A5974073AA /* Platform.Linux.swift in Sources */, + CF9DAAEC618DE435A7DF19579DE30AA2 /* PriorityQueue.swift in Sources */, + 210E6BE763C894C38888F5B166A2EA64 /* PublishRelay+Signal.swift in Sources */, + 3D42C9D3EEBE1EAD7E365276753FE99E /* Queue.swift in Sources */, + 14D2C2DC6532CC4AAD73F205B9211DB8 /* RecursiveLock.swift in Sources */, + 022DFEBF3DD3B5B1627278F189254A25 /* RxCocoa.swift in Sources */, + 70527867C4C4C965053E4283F3778986 /* RxCocoa-dummy.m in Sources */, + F387475B1EC3C098254F62698129B612 /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */, + 938B46EF411204D0BEE0A56A7D584D51 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */, + 16EB1EAEF9D5FF0D6E4B221ECB397D63 /* RxCollectionViewDataSourceProxy.swift in Sources */, + F89C351693522F78C6E85B6AAF7B76C4 /* RxCollectionViewDataSourceType.swift in Sources */, + 28D5D9EEAE845C76C8079BD1C77BFE82 /* RxCollectionViewDelegateProxy.swift in Sources */, + 3DD9694A6D1F5035C6C400C6912B9E36 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */, + 44AEBB2D29B9FB87530556A0CEC170F7 /* RxNavigationControllerDelegateProxy.swift in Sources */, + 15D5D77E68C8B6AF20B7056602F7AEBF /* RxPickerViewAdapter.swift in Sources */, + A1194BE78FCE2929CDA65C95CA310EAF /* RxPickerViewDataSourceProxy.swift in Sources */, + 1E9033562EACB851BBAB74F033194B48 /* RxPickerViewDataSourceType.swift in Sources */, + F1DA873728D70AB358E831F18AF284ED /* RxPickerViewDelegateProxy.swift in Sources */, + AA7BBD3390AF2ECAFA1AD576BB69CE15 /* RxScrollViewDelegateProxy.swift in Sources */, + DD724165EF3D8F209BD6EA6EEAA7EA0A /* RxSearchBarDelegateProxy.swift in Sources */, + F219C2A0B49D73B93CEC939FEF1E7AB2 /* RxSearchControllerDelegateProxy.swift in Sources */, + 548B9145185925F281D9B1951379E6D1 /* RxTabBarControllerDelegateProxy.swift in Sources */, + 4838B3C8759DACF738F61BF91100379A /* RxTabBarDelegateProxy.swift in Sources */, + FDB6B50F3AF189818D8962D74E37D552 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */, + D583F8FC3BFE7CE7368F5FE75679F388 /* RxTableViewDataSourceProxy.swift in Sources */, + C4D350D569A2B6567E087ED515A93EE2 /* RxTableViewDataSourceType.swift in Sources */, + 31F0D187BC76DAB3C2DEE8B2CABB0535 /* RxTableViewDelegateProxy.swift in Sources */, + F6E1B45243EF2546837B9099C53770E2 /* RxTableViewReactiveArrayDataSource.swift in Sources */, + D1DE14077A54174F00E887101A48AE8A /* RxTarget.swift in Sources */, + 4FC27FF6DF0328A134393A57E735977B /* RxTextStorageDelegateProxy.swift in Sources */, + C66C4E3E67C26B960FABBC8F1B0C056A /* RxTextViewDelegateProxy.swift in Sources */, + 7BEF420E8F9099C5079845A9BE4DCA63 /* RxWKNavigationDelegateProxy.swift in Sources */, + BB75BCF76F22254E3302085A5A6A4B48 /* SchedulerType+SharedSequence.swift in Sources */, + C56A14C84CF05A1A96D8B92E16E0CBFB /* SectionedViewDataSourceType.swift in Sources */, + DFD30F96D602E6476B57BB16FF1785D2 /* SharedSequence.swift in Sources */, + 9DB4A288E7875E7346EAB537875222D8 /* SharedSequence+Operators.swift in Sources */, + 841FBD1EB10F9112D309BB28BD10CF1D /* SharedSequence+Operators+arity.swift in Sources */, + 3D445FD9D8FFBDD79E0D04BDFE96B0BB /* Signal.swift in Sources */, + 1AD93376D403A851F152D1B804F7BFC0 /* Signal+Subscription.swift in Sources */, + BEFE617EABAE8B434A580CCD4179C04E /* TextInput.swift in Sources */, + A37D3661369446F3AA978C8FD342A83A /* UIActivityIndicatorView+Rx.swift in Sources */, + 4EFD31D7DB8D26D9D031A2225A0C6AEC /* UIApplication+Rx.swift in Sources */, + 09E4A424C9A4B6AF425B42861E50E5F0 /* UIBarButtonItem+Rx.swift in Sources */, + 24C44D889CCC3570C277EB1C3CE505F4 /* UIButton+Rx.swift in Sources */, + A3423ADEDFB20D72E2C608221A26D3C6 /* UICollectionView+Rx.swift in Sources */, + 4EE0F2D2112CE993AEA24549F5DB19BF /* UIControl+Rx.swift in Sources */, + 8FE0BD68EA39B931E49D9C038BE80B65 /* UIDatePicker+Rx.swift in Sources */, + 51C984425C777CF8B613C230DCE2DB65 /* UIGestureRecognizer+Rx.swift in Sources */, + 4EB4328C78B36211BF7D50529327FD7C /* UINavigationController+Rx.swift in Sources */, + DDEF2B45CC47E733C9FCCD38F0BF6857 /* UIPickerView+Rx.swift in Sources */, + 8B7686A732E13434E997809196B15955 /* UIRefreshControl+Rx.swift in Sources */, + 70A41125865DDF878FC4CBD646349805 /* UIScrollView+Rx.swift in Sources */, + EB276B66D2562F17B084C0D83B9D8F27 /* UISearchBar+Rx.swift in Sources */, + 0D7B6FF8C492D77C003609B68CFABA1E /* UISearchController+Rx.swift in Sources */, + 0B2165491D9E7087D8C78C7A8128A9F0 /* UISegmentedControl+Rx.swift in Sources */, + 2C64E385669A619F264F7556914DF205 /* UISlider+Rx.swift in Sources */, + 8AEF0775CDF920AC2DBE0C725B59EC96 /* UIStepper+Rx.swift in Sources */, + D05116642C20C568B926B4025B6EF995 /* UISwitch+Rx.swift in Sources */, + EE80E1376D7F9E22682AE05EE3054388 /* UITabBar+Rx.swift in Sources */, + 08155F3F6D55A38A07F00F85763290E7 /* UITabBarController+Rx.swift in Sources */, + 161856AC63FAA2C3D8164A7500E14CB8 /* UITableView+Rx.swift in Sources */, + 81A394201D240F032A6108ED479B427A /* UITextField+Rx.swift in Sources */, + 000702A76DD1A018D9B45DEB79FB505D /* UITextView+Rx.swift in Sources */, + 7F60B371FE78073E7DFDD621FFC482CE /* URLSession+Rx.swift in Sources */, + 8EA5CC7EF28B004A8A813925E4F17F93 /* WKWebView+Rx.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 08FF32A4188794D1FB1723BB548D0DF1 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 71E2315CBD1C572415F98045F62C3A87 /* PBXContainerItemProxy */; + }; + 09EED8A378BD557822A56576EED5B8D3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Then; + target = C17AEFC79E770A2906EFAAB1A3757406 /* Then */; + targetProxy = D57F664D714513B525D72AECD7500DD6 /* PBXContainerItemProxy */; + }; + 115CD258ABA61F963F643A662E38779D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Moya; + target = 17F9141D333DA1A7BE5937F227221070 /* Moya */; + targetProxy = AB0BAD6E58CC53A075ADF02F9047C8AB /* PBXContainerItemProxy */; + }; + 43D82A45260ED5056B43FD754FFFC49C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 6F772535556CB2FC9C6C1669AB0A4482 /* PBXContainerItemProxy */; + }; + 51D0DCA4AAFEDA6BF800636E32C869FD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 77E57AFEA5397D1E7654B3A9604A0E5F /* PBXContainerItemProxy */; + }; + 70D85C49374E79CF1BC882D5FAC7D01C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 833BD7AEDC7EA73809738EA6FF1E57A1 /* PBXContainerItemProxy */; + }; + 89BE329F5DFA0300F632809D1BF9A9D1 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Kingfisher; + target = E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */; + targetProxy = 1A642608849B947A198C41683C87B7FF /* PBXContainerItemProxy */; + }; + 945AF39EB604722D61DB7130CC3CD2DB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SnapKit; + target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; + targetProxy = 011CB0D0957212DB0175C9E6CF7B71B8 /* PBXContainerItemProxy */; + }; + 9A16BFFCEC24F512034D509AE6FE02AC /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftyJSON; + target = D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */; + targetProxy = 3B0D29B425BC83DF1E83C2E073EBCD27 /* PBXContainerItemProxy */; + }; + A8F079ABA8E172DD508AD330251970F2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 472834846DC97B551721422BFC9384A1 /* PBXContainerItemProxy */; + }; + B0AB82E7FD8A5D185898ABF7430D8CF3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxCocoa; + target = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */; + targetProxy = 895A0CE95B38109B3072E60362355E34 /* PBXContainerItemProxy */; + }; + B85D375F82BDFBCFDFC4891721981C0B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "lottie-ios"; + target = 0B967D7F8561D42493EE289EC8D450D1 /* lottie-ios */; + targetProxy = B4C22C549EE0010614ED89E0F8A93A10 /* PBXContainerItemProxy */; + }; + B9ECECD5B2D4A6DA2A5BFCA63610D08D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 64AD9C22DCB9A294714602AC1A105581 /* PBXContainerItemProxy */; + }; + BDB715FCC2D2EC03F47C616167D06F4D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = ListPlaceholder; + target = 881D2AF3078426440580FAD64637BBE0 /* ListPlaceholder */; + targetProxy = B665499182DF664C7CA6F3BCF43A3EC5 /* PBXContainerItemProxy */; + }; + DD6F4F249D9787C8DE7CF5D35B0F452B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 037FAA74DD47808B08A1C08B0EAF422B /* PBXContainerItemProxy */; + }; + F79B240A89BF11494C9D6366D09A4481 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SkeletonView; + target = 8CEEFD1CB630CA790F0396E2E24A4C8C /* SkeletonView */; + targetProxy = 6D3BDF59251D134C6345E851B8FCB97B /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 02F68D45448E80F3C1911FA967E77AE2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0C8822E7100535F320D5E304F38D628F /* Pods-sopt_29th_Assignment.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-sopt_29th_Assignment/Pods-sopt_29th_Assignment-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.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; + }; + 1D29D503CCE920A4C73257C85EF64EF5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5A6C58F1D4435C0AB86B565F53116FCA /* ListPlaceholder.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/ListPlaceholder/ListPlaceholder-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/ListPlaceholder/ListPlaceholder-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/ListPlaceholder/ListPlaceholder.modulemap"; + PRODUCT_MODULE_NAME = ListPlaceholder; + PRODUCT_NAME = ListPlaceholder; + 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; + }; + 1ED19DD549C2CB30C3392872231B0B10 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E9077F9703C9F2AF9FBCCEB58C2C8C8B /* 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.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 24CB875D5B25BF16969BE395662EAFD0 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B74A78EF31C6F1542EAABDF86E9045D8 /* SwiftyJSON.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/SwiftyJSON/SwiftyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; + PRODUCT_MODULE_NAME = SwiftyJSON; + PRODUCT_NAME = SwiftyJSON; + 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; + }; + 36A1DEDA9746F903201273F902B227BB /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 27F86901F0BC54C484DB217DFBB17E99 /* 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; + }; + 3914DEBBEEAB8A4B9DD4367F2704D034 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2A6FDF9696B2561B33425CE9CFB52EDF /* Then.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/Then/Then-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Then/Then-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Then/Then.modulemap"; + PRODUCT_MODULE_NAME = Then; + PRODUCT_NAME = Then; + 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; + }; + 3AEFF7C1028DA68CA272C2503162CCD9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DE19B39C1F7D2C6F8EA095F0F0DC429F /* 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 = 10.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; + }; + 48C1A4797FB8B168B97AFA459CD2E837 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 378854640F1106F95BAEBEB96DFE30C3 /* 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 = 10.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; + }; + 4F52EE3110BD9250A83CBAFFB15D7C60 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 482DA72C97FEBA660F16267D96D5E285 /* ListPlaceholder.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/ListPlaceholder/ListPlaceholder-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/ListPlaceholder/ListPlaceholder-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/ListPlaceholder/ListPlaceholder.modulemap"; + PRODUCT_MODULE_NAME = ListPlaceholder; + PRODUCT_NAME = ListPlaceholder; + 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; + }; + 593F10BFFA94DAC7D6E17FB8A7F32D72 /* 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 = 14.1; + 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; + }; + 62DFC0E3E199DF0F8274895CF919FB89 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E0B2731182FB5F0FFA7F5D229694668A /* 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; + }; + 63537810D99802C18D01F724354CAA3D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1B6FA3A0B046504259630EC69BE1968D /* 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.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 77EC3FA404363838052F96B825B44868 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0782047E60E7337951DBC4FB782255D1 /* lottie-ios.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/lottie-ios/lottie-ios-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/lottie-ios/lottie-ios-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/lottie-ios/lottie-ios.modulemap"; + PRODUCT_MODULE_NAME = Lottie; + PRODUCT_NAME = Lottie; + 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; + }; + 79FDB89F6CA57D6734D528EAF266BD7B /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1C861463227BAC0BB12CACF221FA5267 /* 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.5; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7D34C1F5EEAF808252A41D4904D30039 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C506ECDECE2EF8C2FB2CCD2D763931DB /* 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; + }; + 8183B62A3E2BF9E96DDB8E646F4CAD26 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 02EFDE53819B941417FF687996AB3924 /* SkeletonView.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/SkeletonView/SkeletonView-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SkeletonView/SkeletonView-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/SkeletonView/SkeletonView.modulemap"; + PRODUCT_MODULE_NAME = SkeletonView; + PRODUCT_NAME = SkeletonView; + 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; + }; + 881BB1072E73FB94D39AFD4218077A7A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 104ED09FCA1D2D46F9F4ADCF6D2F06DC /* Pods-sopt_29th_Assignment.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-sopt_29th_Assignment/Pods-sopt_29th_Assignment-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.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; + }; + 96859D0CBA06C4EA7691E92BBFBE3F95 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D8B0FF0EDE8D0EF1213F63DD747002C2 /* 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; + }; + A0374B8CF9A7D6A45F6D116D698D1C19 /* 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 = 14.1; + 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; + }; + A63F7687448C668B406F5C24FAB3100D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1CF228A1EEF44F4A765F24BACC877FD9 /* SkeletonView.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/SkeletonView/SkeletonView-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SkeletonView/SkeletonView-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/SkeletonView/SkeletonView.modulemap"; + PRODUCT_MODULE_NAME = SkeletonView; + PRODUCT_NAME = SkeletonView; + 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; + }; + A6C06F26F3D6739F2C6E9775A4465B64 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4379622FBB2CEFDC5335AB006D956909 /* SwiftyJSON.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/SwiftyJSON/SwiftyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; + PRODUCT_MODULE_NAME = SwiftyJSON; + PRODUCT_NAME = SwiftyJSON; + 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; + }; + BD56FE5DA8DE765EC0B3C5976EAE795F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3593A9C676C986ADEC9A0D44D5E2E0F5 /* Then.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/Then/Then-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Then/Then-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Then/Then.modulemap"; + PRODUCT_MODULE_NAME = Then; + PRODUCT_NAME = Then; + 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; + }; + BD5901932236E735C71A328C391DAAF3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E65F27B5F5507A9C1200A5BA6654B668 /* lottie-ios.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/lottie-ios/lottie-ios-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/lottie-ios/lottie-ios-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/lottie-ios/lottie-ios.modulemap"; + PRODUCT_MODULE_NAME = Lottie; + PRODUCT_NAME = Lottie; + 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; + }; + BF77650F934F82F058DA9DF4251C0DEE /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4392138897B7F1D2D744E42BD42A8666 /* 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; + }; + CB8A79F7382B0A1227C38D59E7968EEA /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 8EF1F2977FAC819C88157477780EA4CA /* 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; + }; + D6AAF67D143BF267477C89ACA6A4F5DE /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DAE8E84076D904366DAFA886774421A5 /* 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; + }; + DDE66E9EF2650949C1F28ED6BFEEEFED /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1C7BA86113D5C716B3A12925604B3936 /* 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.5; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + DFFD31690F9CC8449FD1F803388E1D46 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 34C2783C40155C5656AD80D6A1501FCB /* 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; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2490E828D479276A7E0AFBA515DD77FA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A6C06F26F3D6739F2C6E9775A4465B64 /* Debug */, + 24CB875D5B25BF16969BE395662EAFD0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 25737AF8107207FF823CA33914BAB276 /* Build configuration list for PBXNativeTarget "Moya" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1ED19DD549C2CB30C3392872231B0B10 /* Debug */, + 63537810D99802C18D01F724354CAA3D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 25AE2A8304AA799A1A0A4FD6C1577310 /* Build configuration list for PBXNativeTarget "RxCocoa" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7D34C1F5EEAF808252A41D4904D30039 /* Debug */, + 96859D0CBA06C4EA7691E92BBFBE3F95 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A0374B8CF9A7D6A45F6D116D698D1C19 /* Debug */, + 593F10BFFA94DAC7D6E17FB8A7F32D72 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4949A940CD53B7E293859B71C91C88F3 /* Build configuration list for PBXNativeTarget "SnapKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CB8A79F7382B0A1227C38D59E7968EEA /* Debug */, + DFFD31690F9CC8449FD1F803388E1D46 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4C14BC5413148D6627CBCB3E42C63146 /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D6AAF67D143BF267477C89ACA6A4F5DE /* Debug */, + 62DFC0E3E199DF0F8274895CF919FB89 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6C5C9A3D61A6DEB025C9ACE0866E949F /* Build configuration list for PBXNativeTarget "lottie-ios" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 77EC3FA404363838052F96B825B44868 /* Debug */, + BD5901932236E735C71A328C391DAAF3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9066CF256D5B92C1B2C5053115F4AC74 /* Build configuration list for PBXNativeTarget "Then" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BD56FE5DA8DE765EC0B3C5976EAE795F /* Debug */, + 3914DEBBEEAB8A4B9DD4367F2704D034 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97D2382C0969601D44189F3B35A29F70 /* Build configuration list for PBXNativeTarget "ListPlaceholder" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1D29D503CCE920A4C73257C85EF64EF5 /* Debug */, + 4F52EE3110BD9250A83CBAFFB15D7C60 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9C98220D3187BF01A20E296DC128BED4 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DDE66E9EF2650949C1F28ED6BFEEEFED /* Debug */, + 79FDB89F6CA57D6734D528EAF266BD7B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BC9DCA8EC2C877618C8BADC0FCDB2B1F /* Build configuration list for PBXNativeTarget "Pods-sopt_29th_Assignment" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 02F68D45448E80F3C1911FA967E77AE2 /* Debug */, + 881BB1072E73FB94D39AFD4218077A7A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E249F9CC1A59D4DC6ED56FE713439CBA /* Build configuration list for PBXNativeTarget "SkeletonView" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A63F7687448C668B406F5C24FAB3100D /* Debug */, + 8183B62A3E2BF9E96DDB8E646F4CAD26 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + EAFF386EB25D481C9E1803A77104206E /* Build configuration list for PBXNativeTarget "Kingfisher" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 48C1A4797FB8B168B97AFA459CD2E837 /* Debug */, + 3AEFF7C1028DA68CA272C2503162CCD9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA3AEC515004CAE301291DB49AF63C10 /* Build configuration list for PBXNativeTarget "RxRelay" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 36A1DEDA9746F903201273F902B227BB /* Debug */, + BF77650F934F82F058DA9DF4251C0DEE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Alamofire.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 0000000..120775c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Kingfisher.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Kingfisher.xcscheme new file mode 100644 index 0000000..0074170 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Kingfisher.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/ListPlaceholder.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/ListPlaceholder.xcscheme new file mode 100644 index 0000000..ad8ce94 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/ListPlaceholder.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Moya.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Moya.xcscheme new file mode 100644 index 0000000..2b9669b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Moya.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Pods-sopt_29th_Assignment.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Pods-sopt_29th_Assignment.xcscheme new file mode 100644 index 0000000..f23fdf6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Pods-sopt_29th_Assignment.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxCocoa.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxCocoa.xcscheme new file mode 100644 index 0000000..3b88af8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxCocoa.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxRelay.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxRelay.xcscheme new file mode 100644 index 0000000..d69a445 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxRelay.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxSwift.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxSwift.xcscheme new file mode 100644 index 0000000..47e329b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/RxSwift.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SkeletonView.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SkeletonView.xcscheme new file mode 100644 index 0000000..60cba39 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SkeletonView.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SnapKit.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SnapKit.xcscheme new file mode 100644 index 0000000..ee0a410 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SnapKit.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SwiftyJSON.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SwiftyJSON.xcscheme new file mode 100644 index 0000000..dd4cd7c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/SwiftyJSON.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Then.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Then.xcscheme new file mode 100644 index 0000000..2a8d374 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/Then.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/lottie-ios.xcscheme b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/lottie-ios.xcscheme new file mode 100644 index 0000000..e4e6875 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/lottie-ios.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/xcschememanagement.plist b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..2ebc167 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Pods.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,102 @@ + + + + + SchemeUserState + + Alamofire.xcscheme + + isShown + + orderHint + 0 + + Kingfisher.xcscheme + + isShown + + orderHint + 1 + + ListPlaceholder.xcscheme + + isShown + + orderHint + 2 + + Moya.xcscheme + + isShown + + orderHint + 4 + + Pods-sopt_29th_Assignment.xcscheme + + isShown + + orderHint + 5 + + RxCocoa.xcscheme + + isShown + + orderHint + 6 + + RxRelay.xcscheme + + isShown + + orderHint + 7 + + RxSwift.xcscheme + + isShown + + orderHint + 8 + + SkeletonView.xcscheme + + isShown + + orderHint + 9 + + SnapKit.xcscheme + + isShown + + orderHint + 10 + + SwiftyJSON.xcscheme + + isShown + + orderHint + 11 + + Then.xcscheme + + isShown + + orderHint + 12 + + lottie-ios.xcscheme + + isShown + + orderHint + 3 + + + SuppressBuildableAutocreation + + + diff --git a/sopt_29th_Assignment/Pods/RxCocoa/LICENSE.md b/sopt_29th_Assignment/Pods/RxCocoa/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/Bag.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000..5720a3b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000..75d7bea --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000..9ed856b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/Queue.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000..625d473 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..aaf24ca --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/Platform.Darwin.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/Platform.Darwin.swift new file mode 100644 index 0000000..eacc194 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/Platform.Linux.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/Platform.Linux.swift new file mode 100644 index 0000000..52a3e3a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/Platform/RecursiveLock.swift b/sopt_29th_Assignment/Pods/RxCocoa/Platform/RecursiveLock.swift new file mode 100644 index 0000000..10b9bbb --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/README.md b/sopt_29th_Assignment/Pods/RxCocoa/README.md new file mode 100644 index 0000000..2033016 --- /dev/null +++ b/sopt_29th_Assignment/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.2.0' + pod 'RxCocoa', '6.2.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.2.0' + pod 'RxTest', '6.2.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.2.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.2.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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift new file mode 100644 index 0000000..231c3fe --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift new file mode 100644 index 0000000..4ef8de7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift @@ -0,0 +1,293 @@ +// +// 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 forwardToDelegate: 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 { + 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift new file mode 100644 index 0000000..42fa50d --- /dev/null +++ b/sopt_29th_Assignment/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 Proxys 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 toObject: Object that has delegate property. + /// - parameter delegate: Delegate value. + 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 heirarchy + 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift new file mode 100644 index 0000000..82c2922 --- /dev/null +++ b/sopt_29th_Assignment/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 to: 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 to: 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 to: 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 to: 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 relay: 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 relay: 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 relay: 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 relay: 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 relay: 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 relay: 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift new file mode 100644 index 0000000..edded6b --- /dev/null +++ b/sopt_29th_Assignment/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 to: 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 to: 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 to: 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 to: 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift new file mode 100644 index 0000000..4abf880 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift new file mode 100644 index 0000000..5a2c464 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift new file mode 100644 index 0000000..5c3cf3c --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/TextInput.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Common/TextInput.swift new file mode 100644 index 0000000..2268882 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift new file mode 100644 index 0000000..30026bf --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift new file mode 100644 index 0000000..00d53dd --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift new file mode 100644 index 0000000..be12b33 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift new file mode 100644 index 0000000..1be5a21 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift new file mode 100644 index 0000000..6e47cb2 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift new file mode 100644 index 0000000..68affa7 --- /dev/null +++ b/sopt_29th_Assignment/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 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 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift new file mode 100644 index 0000000..30ffa2b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift new file mode 100644 index 0000000..93e65cc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RX.m b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RX.m new file mode 100644 index 0000000..cffbfbc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m new file mode 100644 index 0000000..36338a5 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m new file mode 100644 index 0000000..fc8fb75 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m new file mode 100644 index 0000000..2e685aa --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h new file mode 100644 index 0000000..8cf762e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h new file mode 100644 index 0000000..b868ac9 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h new file mode 100644 index 0000000..e1cc207 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h new file mode 100644 index 0000000..adcfd0a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h new file mode 100644 index 0000000..bc6a76a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/RxCocoa.h b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/RxCocoa.h new file mode 100644 index 0000000..0bca1bc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/RxCocoa.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/RxCocoa.swift new file mode 100644 index 0000000..5e569fc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift new file mode 100644 index 0000000..bea1d83 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift new file mode 100644 index 0000000..3068afb --- /dev/null +++ b/sopt_29th_Assignment/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 buids 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift new file mode 100644 index 0000000..76d960f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift new file mode 100644 index 0000000..b59c753 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift new file mode 100644 index 0000000..7904529 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift new file mode 100644 index 0000000..da9659c --- /dev/null +++ b/sopt_29th_Assignment/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 with: 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift new file mode 100644 index 0000000..5de8b3a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift new file mode 100644 index 0000000..bcac66b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift new file mode 100644 index 0000000..20ddf86 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift new file mode 100644 index 0000000..5111e06 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift new file mode 100644 index 0000000..4cc967c --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift new file mode 100644 index 0000000..45383ef --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift @@ -0,0 +1,585 @@ +// +// 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 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(_ 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 seqeunce 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 seqeunce 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. + - 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) + -> SharedSequence { + let source = self.asObservable() + .delay(dueTime, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } +} diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift new file mode 100644 index 0000000..4db2ee4 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift new file mode 100644 index 0000000..bec4723 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift new file mode 100644 index 0000000..b962d4e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift new file mode 100644 index 0000000..79b975d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift new file mode 100644 index 0000000..ce3f94b --- /dev/null +++ b/sopt_29th_Assignment/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 to: 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 to: 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 to: 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 to: 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 to: 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 to: 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 to: 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 to: 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift new file mode 100644 index 0000000..e066b7e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift new file mode 100644 index 0000000..1acc998 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift new file mode 100644 index 0000000..53b8475 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift new file mode 100644 index 0000000..6d612f3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift new file mode 100644 index 0000000..aadf749 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift new file mode 100644 index 0000000..ba30547 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift new file mode 100644 index 0000000..b098a9e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift new file mode 100644 index 0000000..1f390bf --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift new file mode 100644 index 0000000..d59af9e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift new file mode 100644 index 0000000..efb7554 --- /dev/null +++ b/sopt_29th_Assignment/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 + , UICollectionViewDataSourcePrefetching { + + /// 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 + + // MARK: delegate + + /// 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) + } + + /// 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) + } + } + +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift new file mode 100644 index 0000000..793e544 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift @@ -0,0 +1,76 @@ +// +// 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 + , UICollectionViewDataSource { + + /// 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 + + // MARK: delegate + + /// 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) + } + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? collectionViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift new file mode 100644 index 0000000..dd8f4b4 --- /dev/null +++ b/sopt_29th_Assignment/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 + , UICollectionViewDelegate + , UICollectionViewDelegateFlowLayout { + + /// 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) + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift new file mode 100644 index 0000000..372bf79 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift @@ -0,0 +1,38 @@ +// +// 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 + , UINavigationControllerDelegate { + + /// 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) } + } + } +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift new file mode 100644 index 0000000..f9c65d1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift @@ -0,0 +1,71 @@ +// +// 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 + , UIPickerViewDataSource { + + /// 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 + + // MARK: 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) + } + + /// For more information take a look at `DelegateProxyType`. + public override func setForwardToDelegate(_ forwardToDelegate: UIPickerViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? pickerViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift new file mode 100644 index 0000000..922126f --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift @@ -0,0 +1,37 @@ +// +// 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 + , UIPickerViewDelegate { + + /// 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 implementationss + public static func registerKnownImplementations() { + self.register { RxPickerViewDelegateProxy(pickerView: $0) } + } + } +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift new file mode 100644 index 0000000..59608d3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift @@ -0,0 +1,92 @@ +// +// 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 + , UIScrollViewDelegate { + + /// 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 + } + + // MARK: delegate methods + + /// 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) + } + + deinit { + if let subject = _contentOffsetBehaviorSubject { + subject.on(.completed) + } + + if let subject = _contentOffsetPublishSubject { + subject.on(.completed) + } + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift new file mode 100644 index 0000000..532ab68 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// 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 + , UISearchBarDelegate { + + /// 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) } + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift new file mode 100644 index 0000000..04e0de0 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// 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 + , UISearchControllerDelegate { + + /// 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) } + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift new file mode 100644 index 0000000..585894c --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// 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 + , UITabBarControllerDelegate { + + /// 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) } + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift new file mode 100644 index 0000000..6205730 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift @@ -0,0 +1,49 @@ +// +// 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 + , UITabBarDelegate { + + /// 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 + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift new file mode 100644 index 0000000..4345312 --- /dev/null +++ b/sopt_29th_Assignment/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 + , UITableViewDataSourcePrefetching { + + /// 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 + + // MARK: delegate + + /// 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) + } + + /// 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) + } + } + +} + +#endif + diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift new file mode 100644 index 0000000..42d9386 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift @@ -0,0 +1,75 @@ +// +// 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 + , UITableViewDataSource { + + /// 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 + + // MARK: delegate + + /// 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) + } + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UITableViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? tableViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift new file mode 100644 index 0000000..86a8758 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift @@ -0,0 +1,30 @@ +// +// 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 + , UITableViewDelegate { + + /// 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) + } + +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift new file mode 100644 index 0000000..12669f9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift @@ -0,0 +1,37 @@ +// +// 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 + , NSTextStorageDelegate { + + /// 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) } + } + } +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift new file mode 100644 index 0000000..c8a1dfd --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift @@ -0,0 +1,43 @@ +// +// 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 + , UITextViewDelegate { + + /// 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) + } + + // MARK: delegate methods + + /// 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift new file mode 100644 index 0000000..c758c02 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift @@ -0,0 +1,43 @@ +// +// 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 +, WKNavigationDelegate { + + /// 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 + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift new file mode 100644 index 0000000..ca2d4f1 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift new file mode 100644 index 0000000..d776105 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift new file mode 100644 index 0000000..0bcaa99 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift new file mode 100644 index 0000000..4d0f4c3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift new file mode 100644 index 0000000..7f3de00 --- /dev/null +++ b/sopt_29th_Assignment/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 sideeffects 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift new file mode 100644 index 0000000..6698cf2 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift new file mode 100644 index 0000000..e10c1ec --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift new file mode 100644 index 0000000..5512900 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift new file mode 100644 index 0000000..94796b6 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift new file mode 100644 index 0000000..317dc13 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift new file mode 100644 index 0000000..cdb10be --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift new file mode 100644 index 0000000..f90e1c2 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift new file mode 100644 index 0000000..3892b1c --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift new file mode 100644 index 0000000..4f524a5 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift new file mode 100644 index 0000000..1a62662 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift new file mode 100644 index 0000000..07d4adb --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift new file mode 100644 index 0000000..29f6386 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift new file mode 100644 index 0000000..6e116b3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift new file mode 100644 index 0000000..e989667 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift new file mode 100644 index 0000000..4b48e8e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift new file mode 100644 index 0000000..b217133 --- /dev/null +++ b/sopt_29th_Assignment/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 sideeffects 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift new file mode 100644 index 0000000..614fecc --- /dev/null +++ b/sopt_29th_Assignment/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 imporant 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 imporant for proper input + // when IME input method is used. + if textField.attributedText != value { + textField.attributedText = value + } + } + ) + } +} + +#endif diff --git a/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift new file mode 100644 index 0000000..497ab66 --- /dev/null +++ b/sopt_29th_Assignment/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 imporant 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 imporant 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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift new file mode 100644 index 0000000..b3b4d84 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift new file mode 100644 index 0000000..7c22361 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift new file mode 100644 index 0000000..534f40c --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift new file mode 100644 index 0000000..2e5b19a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift new file mode 100644 index 0000000..ce69f9e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift new file mode 100644 index 0000000..c3134e4 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift b/sopt_29th_Assignment/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift new file mode 100644 index 0000000..f4256d1 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxRelay/LICENSE.md b/sopt_29th_Assignment/Pods/RxRelay/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxRelay/README.md b/sopt_29th_Assignment/Pods/RxRelay/README.md new file mode 100644 index 0000000..2033016 --- /dev/null +++ b/sopt_29th_Assignment/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.2.0' + pod 'RxCocoa', '6.2.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.2.0' + pod 'RxTest', '6.2.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.2.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.2.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/sopt_29th_Assignment/Pods/RxRelay/RxRelay/BehaviorRelay.swift b/sopt_29th_Assignment/Pods/RxRelay/RxRelay/BehaviorRelay.swift new file mode 100644 index 0000000..e02fc8f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxRelay/RxRelay/Observable+Bind.swift b/sopt_29th_Assignment/Pods/RxRelay/RxRelay/Observable+Bind.swift new file mode 100644 index 0000000..7a2efc7 --- /dev/null +++ b/sopt_29th_Assignment/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 to: 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 to: 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 to: 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 to: 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 to: 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 to: 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 to: 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 to: 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 to: 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/sopt_29th_Assignment/Pods/RxRelay/RxRelay/PublishRelay.swift b/sopt_29th_Assignment/Pods/RxRelay/RxRelay/PublishRelay.swift new file mode 100644 index 0000000..a9c8ac4 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxRelay/RxRelay/ReplayRelay.swift b/sopt_29th_Assignment/Pods/RxRelay/RxRelay/ReplayRelay.swift new file mode 100644 index 0000000..3cc87cd --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxRelay/RxRelay/Utils.swift b/sopt_29th_Assignment/Pods/RxRelay/RxRelay/Utils.swift new file mode 100644 index 0000000..5954fb9 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/LICENSE.md b/sopt_29th_Assignment/Pods/RxSwift/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/AtomicInt.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/AtomicInt.swift new file mode 100644 index 0000000..98479fd --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/Bag.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000..5720a3b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000..75d7bea --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000..9ed856b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/Queue.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000..625d473 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..aaf24ca --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/Platform.Darwin.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 0000000..eacc194 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/Platform.Linux.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 0000000..52a3e3a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/Platform/RecursiveLock.swift b/sopt_29th_Assignment/Pods/RxSwift/Platform/RecursiveLock.swift new file mode 100644 index 0000000..10b9bbb --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/README.md b/sopt_29th_Assignment/Pods/RxSwift/README.md new file mode 100644 index 0000000..2033016 --- /dev/null +++ b/sopt_29th_Assignment/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.2.0' + pod 'RxCocoa', '6.2.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.2.0' + pod 'RxTest', '6.2.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.2.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.2.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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/AnyObserver.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 0000000..e92cc81 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Binder.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Binder.swift new file mode 100644 index 0000000..1aae095 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Cancelable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 0000000..1fa7a67 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 0000000..502597e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 0000000..7232f23 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 0000000..8a98007 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 0000000..527a2fb --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 0000000..19168d7 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 0000000..988b86f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 0000000..52bf93c --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Date+Dispatch.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Date+Dispatch.swift new file mode 100644 index 0000000..90f70c5 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 0000000..b79c77a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 0000000..591aafa --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 0000000..a3d4937 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 0000000..c7d73e9 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 0000000..bb4efe6 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/Disposables.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/Disposables.swift new file mode 100644 index 0000000..8cd6e28 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 0000000..1a673bc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 0000000..0d4b2fb --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 0000000..dd436ba --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 0000000..a59f778 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 0000000..2cf997b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 0000000..ef4690d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 0000000..d7307d6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,70 @@ +// +// 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 enum DisposeState: Int32 { + case disposed = 1 + case disposableSet = 2 + } + + // 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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 0000000..a406c84 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Errors.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 0000000..d2d2917 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Event.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 0000000..01861a8 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift new file mode 100644 index 0000000..9794683 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/GroupedObservable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/GroupedObservable.swift new file mode 100644 index 0000000..189a8c4 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 0000000..954fbf0 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observable.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 0000000..93a3ed7 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 0000000..0f56a81 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift new file mode 100644 index 0000000..ac850c3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObservableType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 0000000..279bf7f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/AddRef.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/AddRef.swift new file mode 100644 index 0000000..a96dfcb --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Amb.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Amb.swift new file mode 100644 index 0000000..efc17a8 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift new file mode 100644 index 0000000..6fa6257 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/AsSingle.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/AsSingle.swift new file mode 100644 index 0000000..b39932f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Buffer.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Buffer.swift new file mode 100644 index 0000000..087c4cf --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Catch.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Catch.swift new file mode 100644 index 0000000..2efd660 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift new file mode 100644 index 0000000..4350851 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift new file mode 100644 index 0000000..e69bbab --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift new file mode 100644 index 0000000..caa0256 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CompactMap.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/CompactMap.swift new file mode 100644 index 0000000..7dbcdfb --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Concat.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Concat.swift new file mode 100644 index 0000000..b2fb1a2 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Create.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Create.swift new file mode 100644 index 0000000..ca81442 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Debounce.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Debounce.swift new file mode 100644 index 0000000..dfab004 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Debug.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Debug.swift new file mode 100644 index 0000000..762e394 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Decode.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Decode.swift new file mode 100644 index 0000000..8bc7342 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift new file mode 100644 index 0000000..8d133d8 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Deferred.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Deferred.swift new file mode 100644 index 0000000..b81cb16 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Delay.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Delay.swift new file mode 100644 index 0000000..9f71c32 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift new file mode 100644 index 0000000..fd8c495 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift new file mode 100644 index 0000000..2ccd546 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift new file mode 100644 index 0000000..c127b5a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Do.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Do.swift new file mode 100644 index 0000000..3c8c68b --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ElementAt.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ElementAt.swift new file mode 100644 index 0000000..3f09c70 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Empty.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Empty.swift new file mode 100644 index 0000000..9ca5965 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Enumerated.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Enumerated.swift new file mode 100644 index 0000000..ef8a0ff --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Error.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Error.swift new file mode 100644 index 0000000..2e722d6 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Filter.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Filter.swift new file mode 100644 index 0000000..61d3ce7 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/First.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/First.swift new file mode 100644 index 0000000..0014114 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Generate.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Generate.swift new file mode 100644 index 0000000..7b924b3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/GroupBy.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/GroupBy.swift new file mode 100644 index 0000000..88cbda7 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Just.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Just.swift new file mode 100644 index 0000000..9349083 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Map.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Map.swift new file mode 100644 index 0000000..0691273 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Materialize.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Materialize.swift new file mode 100644 index 0000000..e2577be --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Merge.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Merge.swift new file mode 100644 index 0000000..51a6462 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Multicast.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Multicast.swift new file mode 100644 index 0000000..1ebcf02 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Never.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Never.swift new file mode 100644 index 0000000..7b456ee --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift new file mode 100644 index 0000000..6b8689e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Optional.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Optional.swift new file mode 100644 index 0000000..64f8f1f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Producer.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Producer.swift new file mode 100644 index 0000000..e611930 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Range.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Range.swift new file mode 100644 index 0000000..2453532 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Reduce.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Reduce.swift new file mode 100644 index 0000000..d5fab34 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Repeat.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Repeat.swift new file mode 100644 index 0000000..69a3ba0 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift new file mode 100644 index 0000000..52a2709 --- /dev/null +++ b/sopt_29th_Assignment/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 sideffects 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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Sample.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Sample.swift new file mode 100644 index 0000000..9301c9a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Scan.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Scan.swift new file mode 100644 index 0000000..ecf69c8 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Sequence.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Sequence.swift new file mode 100644 index 0000000..c6d1089 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift new file mode 100644 index 0000000..59d440d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift new file mode 100644 index 0000000..04e2217 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Sink.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Sink.swift new file mode 100644 index 0000000..ed4fec0 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Skip.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Skip.swift new file mode 100644 index 0000000..5856f37 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift new file mode 100644 index 0000000..c8fe193 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift new file mode 100644 index 0000000..a62f88d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/StartWith.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/StartWith.swift new file mode 100644 index 0000000..13fb31d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift new file mode 100644 index 0000000..e8e41d9 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Switch.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Switch.swift new file mode 100644 index 0000000..5aa60b9 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift new file mode 100644 index 0000000..a8827c4 --- /dev/null +++ b/sopt_29th_Assignment/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 switchTo: 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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Take.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Take.swift new file mode 100644 index 0000000..e574688 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/TakeLast.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/TakeLast.swift new file mode 100644 index 0000000..9183387 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift new file mode 100644 index 0000000..6c28d19 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Throttle.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Throttle.swift new file mode 100644 index 0000000..86152a8 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Timeout.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Timeout.swift new file mode 100644 index 0000000..efcc791 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Timer.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Timer.swift new file mode 100644 index 0000000..30bbdf6 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ToArray.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/ToArray.swift new file mode 100644 index 0000000..76c7370 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Using.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Using.swift new file mode 100644 index 0000000..ca48d2f --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Window.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Window.swift new file mode 100644 index 0000000..b2a37a5 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift new file mode 100644 index 0000000..d286812 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift new file mode 100644 index 0000000..4dc2ead --- /dev/null +++ b/sopt_29th_Assignment/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 seqeunce 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 seqeunce 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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift new file mode 100644 index 0000000..2d7f887 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift new file mode 100644 index 0000000..b6d876d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Zip.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observables/Zip.swift new file mode 100644 index 0000000..328a40e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObserverType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 0000000..b7a6648 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 0000000..cbb42dc --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 0000000..48e0986 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 0000000..fd52700 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Reactive.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Reactive.swift new file mode 100644 index 0000000..1bf390d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Rx.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 0000000..bcdd279 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/RxMutableBox.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 0000000..73476c3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/SchedulerType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 0000000..6c8fe4a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 0000000..02c47c9 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 0000000..c438d7d --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 0000000..16a7dd3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 0000000..fede60e --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 0000000..a8fae8a --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift new file mode 100644 index 0000000..f313c0b --- /dev/null +++ b/sopt_29th_Assignment/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 conceputal 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 conceputal 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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 0000000..0e15056 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 0000000..0dba433 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 0000000..3d790d7 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 0000000..d2b16ca --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 0000000..703ab44 --- /dev/null +++ b/sopt_29th_Assignment/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 class 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 class 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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 0000000..f0ad3d3 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 0000000..0ee78cd --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 0000000..cab2bc8 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 0000000..bb0013c --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 0000000..34151f7 --- /dev/null +++ b/sopt_29th_Assignment/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/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/sopt_29th_Assignment/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 0000000..e74d5be --- /dev/null +++ b/sopt_29th_Assignment/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

+ + + + codebeat badge + + + + + SkeletonView Playground +

+ +

+ Features + • Guides + • Installation + • Usage + • Miscellaneous + • Contributing +

+ +**🌎 README is available in other languages: [🇪🇸](Translations/README_es.md) . [🇨🇳](Translations/README_zh.md) . [🇧🇷](Translations/README_pt-br.md) . [🇰🇷](Translations/README_ko.md) . [🇫🇷](Translations/README_fr.md)** + +Today almost all apps have async processes, such as API requests, long running processes, etc. While the processes are working, usually developers place a loading view to show users that something is going on. + +**SkeletonView** has been conceived to address this need, an elegant way to show users that something is happening and also prepare them for which contents are waiting. + +Enjoy it! 🙂 + + +## +- [🌟 Features](#-features) +- [🎬 Guides](#-guides) +- [📲 Installation](#-installation) +- [🐒 Usage](#-usage) + - [🌿 Collections](#-collections) + - [🔠 Texts](#-texts) + - [🦋 Appearance](#-appearance) + - [🎨 Custom colors](#-custom-colors) + - [🏃‍♀️ Animations](#️-animations) + - [🏄 Transitions](#-transitions) +- [✨ Miscellaneous](#-miscellaneous) +- [❤️ Contributing](#️-contributing) +- [📢 Mentions](#-mentions) +- [🏆 Sponsors](#-sponsors) +- [👨🏻‍💻 Author](#-author) +- [👮🏻 License](#-license) + + + +## 🌟 Features + +* Easy to use +* All UIViews are skeletonables +* Fully customizable +* Universal (iPhone & iPad) +* Interface Builder friendly +* Simple Swift syntax +* Lightweight readable codebase + + +## 🎬 Guides + +| [![](https://img.youtube.com/vi/75kgOhWsPNA/maxresdefault.jpg)](https://youtu.be/75kgOhWsPNA)|[![](https://img.youtube.com/vi/MVCiM_VdxVA/maxresdefault.jpg)](https://youtu.be/MVCiM_VdxVA)|[![](https://img.youtube.com/vi/Qq3Evspeea8/maxresdefault.jpg)](https://youtu.be/Qq3Evspeea8)|[![](https://img.youtube.com/vi/ZOoPtBwDRT0/maxresdefault.jpg)](https://youtu.be/ZOoPtBwDRT0)|[![](https://img.youtube.com/vi/Zx1Pg1gPfxA/maxresdefault.jpg)](https://www.youtube.com/watch?v=Zx1Pg1gPfxA) +|:---: | :---: |:---: | :---: | :---: +|[**SkeletonView Guides - Getting started**](https://youtu.be/75kgOhWsPNA)|[**How to Create Loading View with Skeleton View in Swift 5.2**](https://youtu.be/MVCiM_VdxVA) by iKh4ever Studio|[**Create Skeleton Loading View in App (Swift 5) - Xcode 11, 2020**](https://youtu.be/Qq3Evspeea8) by iOS Academy| [**Add An Elegant Loading Animation in Swift***](https://youtu.be/ZOoPtBwDRT0) by Gary Tokman| [**Cómo crear una ANIMACIÓN de CARGA de DATOS en iOS**](https://www.youtube.com/watch?v=Zx1Pg1gPfxA) by MoureDev + + +## 📲 Installation + +* [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html): + +```ruby +pod 'SkeletonView' +``` + +* [Carthage](https://github.com/Carthage/Carthage): + +```ruby +github "Juanpe/SkeletonView" +``` + +* [Swift Package Manager](https://swift.org/package-manager/): + +```swift +dependencies: [ + .package(url: "https://github.com/Juanpe/SkeletonView.git", from: "1.7.0") +] +``` + + +## 🐒 Usage + +Only **3** steps needed to use `SkeletonView`: + +1️⃣ Import SkeletonView in proper place. +```swift +import SkeletonView +``` + +2️⃣ Now, set which views will be `skeletonables`. You achieve this in two ways: + +**Using code:** +```swift +avatarImageView.isSkeletonable = true +``` +**Using IB/Storyboards:** + +![](Assets/storyboard.png) + +3️⃣ Once you've set the views, you can show the **skeleton**. To do so, you have **4** choices: + +```swift +(1) view.showSkeleton() // Solid +(2) view.showGradientSkeleton() // Gradient +(3) view.showAnimatedSkeleton() // Solid animated +(4) view.showAnimatedGradientSkeleton() // Gradient animated +``` + +**Preview** + + + + + + + + + + + + + + +
+
Solid
+
+
Gradient
+
+
Solid Animated
+
+
Gradient Animated
+
+ + + + + + + +
+ + +> 📣 **IMPORTANT!** +> +> `SkeletonView` is recursive, so if you want show the skeleton in all skeletonable views, you only need to call the show method in the main container view. For example, with `UIViewControllers`. + + + + +### 🌿 Collections + +```SkeletonView``` is compatible with ```UITableView``` and ```UICollectionView```. + + +**UITableView** + +If you want to show the skeleton in a ```UITableView```, you need to conform to ```SkeletonTableViewDataSource``` protocol. + +``` swift +public protocol SkeletonTableViewDataSource: UITableViewDataSource { + func numSections(in collectionSkeletonView: UITableView) -> Int // Default: 1 + func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int + func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier + func collectionSkeletonView(_ skeletonView: UITableView, skeletonCellForRowAt indexPath: IndexPath) -> UITableViewCell? // Default: nil + func collectionSkeletonView(_ skeletonView: UITableView, prepareCellForSkeleton cell: UITableViewCell, at indexPath: IndexPath) +} +``` +As you can see, this protocol inherits from ```UITableViewDataSource```, so you can replace this protocol with the skeleton protocol. + +This protocol has a default implementation for some methods. For example, the number of rows for each section is calculated in runtime: + +``` swift +func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int +// Default: +// It calculates how many cells need to populate whole tableview +``` + +> 📣 **IMPORTANT!** +> +> If you return `UITableView.automaticNumberOfSkeletonRows` in the above method, it acts like the default behavior (i.e. it calculates how many cells needed to populate the whole tableview). + +There is only one method you need to implement to let Skeleton know the cell identifier. This method doesn't have default implementation: + ``` swift + func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier { + return "CellIdentifier" +} + ``` + + By default, the library dequeues the cells from each indexPath, but you can also do this if you want to make some changes before the skeleton appears: + ``` swift + func collectionSkeletonView(_ skeletonView: UITableView, skeletonCellForRowAt indexPath: IndexPath) -> UITableViewCell? { + let cell = skeletonView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath) as? Cell + cell?.textField.isHidden = indexPath.row == 0 + return cell + } + ``` + +If you prefer to leave the deque part to the library you can configure the cell using this method: + ``` swift + func collectionSkeletonView(_ skeletonView: UITableView, prepareCellForSkeleton cell: UITableViewCell, at indexPath: IndexPath) { + let cell = cell as? Cell + cell?.textField.isHidden = indexPath.row == 0 + } + ``` + + +Besides, you can skeletonize both the headers and footers. You need to conform to `SkeletonTableViewDelegate` protocol. + +```swift +public protocol SkeletonTableViewDelegate: UITableViewDelegate { + func collectionSkeletonView(_ skeletonView: UITableView, identifierForHeaderInSection section: Int) -> ReusableHeaderFooterIdentifier? // default: nil + func collectionSkeletonView(_ skeletonView: UITableView, identifierForFooterInSection section: Int) -> ReusableHeaderFooterIdentifier? // default: nil +} +``` + +> 📣 **IMPORTANT!** +> +> 1️⃣ If you are using resizable cells (**`tableView.rowHeight = UITableViewAutomaticDimension`**), it's mandatory define the **`estimatedRowHeight`**. +> +> 2️⃣ When you add elements in a **`UITableViewCell`** you should add it to **`contentView`** and not to the cell directly. +> ```swift +> self.contentView.addSubview(titleLabel) ✅ +> self.addSubview(titleLabel) ❌ +> ``` + + + +**UICollectionView** + +For `UICollectionView`, you need to conform to `SkeletonCollectionViewDataSource` protocol. + +``` swift +public protocol SkeletonCollectionViewDataSource: UICollectionViewDataSource { + func numSections(in collectionSkeletonView: UICollectionView) -> Int // default: 1 + func collectionSkeletonView(_ skeletonView: UICollectionView, numberOfItemsInSection section: Int) -> Int + func collectionSkeletonView(_ skeletonView: UICollectionView, cellIdentifierForItemAt indexPath: IndexPath) -> ReusableCellIdentifier + func collectionSkeletonView(_ skeletonView: UICollectionView, supplementaryViewIdentifierOfKind: String, at indexPath: IndexPath) -> ReusableCellIdentifier? // default: nil + func collectionSkeletonView(_ skeletonView: UICollectionView, skeletonCellForItemAt indexPath: IndexPath) -> UICollectionViewCell? // default: nil + func collectionSkeletonView(_ skeletonView: UICollectionView, prepareCellForSkeleton cell: UICollectionViewCell, at indexPath: IndexPath) +} +``` + +The rest of the process is the same as ```UITableView``` + + +### 🔠 Texts + +![](Assets/multilines2.png) + +When using elements with text, ```SkeletonView``` draws lines to simulate text. +Besides, you can decide how many lines you want. If ```numberOfLines``` is set to zero, it will calculate how many lines needed to populate the whole skeleton and it will be drawn. Instead, if you set it to one, two or any number greater than zero, it will only draw this number of lines. + +You can set some properties for multilines elements. + + +| Property | Values | Default | Preview +| ------- | ------- |------- | ------- +| **Filling percent** of the last line.
Please note that for views without multiple lines, the single line will be considered as the last line and **lastLineFillPercent** will be applied to that single line. | `0...100` | `70%`| ![](Assets/multiline_lastline.png) +| **Corner radius** of lines. (**NEW**) | `0...10` | `0` | ![](Assets/multiline_corner.png) + + + +To modify the percent or radius **using code**, set the properties: +```swift +descriptionTextView.lastLineFillPercent = 50 +descriptionTextView.linesCornerRadius = 5 +``` + +Or, if you prefer use **IB/Storyboard**: + +![](Assets/multiline_customize.png) + + +### 🦋 Appearance + +The skeletons have a default appearance. So, when you don't specify the color, gradient or multilines properties, `SkeletonView` uses the default values. + +Default values: +- **tintColor**: UIColor + - *default: `.skeletonDefault` (same as `.clouds` but adaptive to dark mode)* +- **gradient**: SkeletonGradient + - *default: `SkeletonGradient(baseColor: .skeletonDefault)`* +- **multilineHeight**: CGFloat + - *default: 15* +- **useFontLineHeight**: Bool + - *default: true* +- **multilineSpacing**: CGFloat + - *default: 10* +- **multilineLastLineFillPercent**: Int + - *default: 70* +- **multilineCornerRadius**: Int + - *default: 0* +- **skeletonCornerRadius**: CGFloat (IBInspectable) (Make your skeleton view with corner) + - *default: 0* + +To get these default values you can use `SkeletonAppearance.default`. Using this property you can set the values as well: +```swift +SkeletonAppearance.default.multilineHeight = 20 +SkeletonAppearance.default.tintColor = .green +``` + +You can also specifiy these line appearance properties on a per-label basis: +- **lastLineFillPercent**: Int +- **linesCornerRadius**: Int +- **skeletonLineSpacing**: CGFloat +- **skeletonPaddingInsets**: UIEdgeInsets +- **useFontLineHeight**: Bool + + +### 🎨 Custom colors + +You can decide which color the skeleton is tinted with. You only need to pass as a parameter the color or gradient you want. + +**Using solid colors** +```swift +view.showSkeleton(usingColor: UIColor.gray) // Solid +// or +view.showSkeleton(usingColor: UIColor(red: 25.0, green: 30.0, blue: 255.0, alpha: 1.0)) +``` +**Using gradients** +``` swift +let gradient = SkeletonGradient(baseColor: UIColor.midnightBlue) +view.showGradientSkeleton(usingGradient: gradient) // Gradient +``` + +Besides, **SkeletonView** features 20 flat colors 🤙🏼 + +```UIColor.turquoise, UIColor.greenSea, UIColor.sunFlower, UIColor.flatOrange ...``` + +![](Assets/flatcolors.png) +###### Image captured from website [https://flatuicolors.com](https://flatuicolors.com) + + +### 🏃‍♀️ Animations + +**SkeletonView** has two built-in animations, *pulse* for solid skeletons and *sliding* for gradients. + +Besides, if you want to do your own skeleton animation, it's really easy. + + +Skeleton provides the `showAnimatedSkeleton` function which has a ```SkeletonLayerAnimation``` closure where you can define your custom animation. + +```swift +public typealias SkeletonLayerAnimation = (CALayer) -> CAAnimation +``` + +You can call the function like this: + +```swift +view.showAnimatedSkeleton { (layer) -> CAAnimation in + let animation = CAAnimation() + // Customize here your animation + + return animation +} +``` + +It's available ```SkeletonAnimationBuilder```. It's a builder to make ```SkeletonLayerAnimation```. + +Today, you can create **sliding animations** for gradients, deciding the **direction** and setting the **duration** of the animation (default = 1.5s). + +```swift +// func makeSlidingAnimation(withDirection direction: GradientDirection, duration: CFTimeInterval = 1.5) -> SkeletonLayerAnimation + +let animation = SkeletonAnimationBuilder().makeSlidingAnimation(withDirection: .leftToRight) +view.showAnimatedGradientSkeleton(usingGradient: gradient, animation: animation) + +``` + +```GradientDirection``` is an enum, with theses cases: + +| Direction | Preview +|------- | ------- +| .leftRight | ![](Assets/sliding_left_to_right.gif) +| .rightLeft | ![](Assets/sliding_right_to_left.gif) +| .topBottom | ![](Assets/sliding_top_to_bottom.gif) +| .bottomTop | ![](Assets/sliding_bottom_to_top.gif) +| .topLeftBottomRight | ![](Assets/sliding_topLeft_to_bottomRight.gif) +| .bottomRightTopLeft | ![](Assets/sliding_bottomRight_to_topLeft.gif) + +> **😉 TRICK!** +> +> Exist another way to create sliding animations, just using this shortcut: +> ```swift +> let animation = GradientDirection.leftToRight.slidingAnimation() +> ``` + + + +### 🏄 Transitions + +**SkeletonView** has built-in transitions to **show** or **hide** the skeletons in a *smoother* way 🤙 + +To use the transition, simply add the ```transition``` parameter to your ```showSkeleton()``` or ```hideSkeleton()``` function with the transition time, like this: + +```swift +view.showSkeleton(transition: .crossDissolve(0.25)) //Show skeleton cross dissolve transition with 0.25 seconds fade time +view.hideSkeleton(transition: .crossDissolve(0.25)) //Hide skeleton cross dissolve transition with 0.25 seconds fade time + +``` + +The default value is `crossDissolve(0.25)` + +**Preview** + + + + + + + + + + +
+
None
+
+
Cross dissolve
+
+ + + +
+ + +## ✨ Miscellaneous + + + +**Hierarchy** + +Since ```SkeletonView``` is recursive, and we want skeleton to be very efficient, we want to stop recursion as soon as possible. For this reason, you must set the container view as `Skeletonable`, because Skeleton will stop looking for `skeletonable` subviews as soon as a view is not Skeletonable, breaking then the recursion. + +Because an image is worth a thousand words: + +In this example we have a `UIViewController` with a `ContainerView` and a `UITableView`. When the view is ready, we show the skeleton using this method: +``` +view.showSkeleton() +``` + +> ```isSkeletonable```= ☠️ + +| Configuration | Result| +|:-------:|:-------:| +| | | +| | | +| | | +|| | +| | | +| | | + + + +**Hierarchy in collections** + +Here is an illustration that shows how you should specify which elements are skeletonables when you are using an `UITableView`: + + + +As you can see, we have to make skeletonable the tableview, the cell and the UI elements, but we don't need to set as skeletonable the `contentView` + + + +**Skeleton views layout** + +Sometimes skeleton layout may not fit your layout because the parent view bounds have changed. ~For example, rotating the device.~ + +You can relayout the skeleton views like so: + +```swift +override func viewDidLayoutSubviews() { + view.layoutSkeletonIfNeeded() +} +``` + +> 📣 **IMPORTANT!** +> +> You shouldn't call this method. From **version 1.8.1** you don't need to call this method, the library does automatically. So, you can use this method **ONLY** in the cases when you need to update the layout of the skeleton manually. + + + + +**Update skeleton** + +You can change the skeleton configuration at any time like its colour, animation, etc. with the following methods: + +```swift +(1) view.updateSkeleton() // Solid +(2) view.updateGradientSkeleton() // Gradient +(3) view.updateAnimatedSkeleton() // Solid animated +(4) view.updateAnimatedGradientSkeleton() // Gradient animated +``` + +**Hiding views when the animation starts** + +Sometimes you wanna hide some view when the animation starts, so there is a quick property that you can use to make this happen: + +```swift +view.isHiddenWhenSkeletonIsActive = true // This works only when isSkeletonable = true +``` + +**Don't modify user interaction when the skeleton is active** + + +By default, the user interaction is disabled for skeletonized items, but if you don't want to modify the user interaction indicator when skeleton is active, you can use the `isUserInteractionDisabledWhenSkeletonIsActive` property: + +```swift +view.isUserInteractionDisabledWhenSkeletonIsActive = false // The view will be active when the skeleton will be active. +``` + +**Don't use the font line height for the skeleton lines in labels** + +False to disable skeleton to auto-adjust to font height for a `UILabel` or `UITextView`. By default, the skeleton lines height is auto-adjusted to font height to more accurately reflect the text in the label rect rather than using the bounding box. + +```swift +label.useFontLineHeight = false +``` + +**Delayed show skeleton** + +You can delay the presentation of the skeleton if the views update quickly. + +```swift +func showSkeleton(usingColor: UIColor, + animated: Bool, + delay: TimeInterval, + transition: SkeletonTransitionStyle) +``` + +```swift +func showGradientSkeleton(usingGradient: SkeletonGradient, + animated: Bool, + delay: TimeInterval, + transition: SkeletonTransitionStyle) +``` + +**Debug** + +To facilitate the debug tasks when something is not working fine. **`SkeletonView`** has some new tools. + +First, `UIView` has available a property with his skeleton info: +```swift +var sk.skeletonTreeDescription: String + +``` + +Besides, you can activate the new **debug mode**. You just add the environment variable `SKELETON_DEBUG` and activate it. + +![](Assets/debug_mode.png) + +Then, when the skeleton appears, you can see the view hierarchy in the Xcode console. + +``` +{ + "type" : "UIView", // UITableView, UILabel... + "isSkeletonable" : true, + "reference" : "0x000000014751ce30", + "children" : [ + { + "type" : "UIView", + "isSkeletonable" : true, + "children" : [ ... ], + "reference" : "0x000000014751cfa0" + } + ] +} +``` + +**Supported OS & SDK Versions** + +* iOS 9.0+ +* tvOS 9.0+ +* Swift 5.3 + +## ❤️ Contributing +This is an open source project, so feel free to contribute. How? + +- Open an [issue](https://github.com/Juanpe/SkeletonView/issues/new). +- Send feedback via [email](mailto://juanpecatalan.com). +- Propose your own fixes, suggestions and open a pull request with the changes. + +See [all contributors](https://github.com/Juanpe/SkeletonView/graphs/contributors) + +For more information, please read the [contributing guidelines](https://github.com/Juanpe/SkeletonView/blob/main/CONTRIBUTING.md). + + +## 📢 Mentions + +- [iOS Dev Weekly #327](https://iosdevweekly.com/issues/327#start) +- [Hacking with Swift Articles](https://www.hackingwithswift.com/articles/40/skeletonview-makes-loading-content-beautiful) +- [Top 10 Swift Articles November](https://medium.mybridge.co/swift-top-10-articles-for-the-past-month-v-nov-2017-dfed7861cd65) +- [30 Amazing iOS Swift Libraries (v2018)](https://medium.mybridge.co/30-amazing-ios-swift-libraries-for-the-past-year-v-2018-7cf15027eee9) +- [AppCoda Weekly #44](http://digest.appcoda.com/issues/appcoda-weekly-issue-44-81899) +- [iOS Cookies Newsletter #103](https://us11.campaign-archive.com/?u=cd1f3ed33c6527331d82107ba&id=48131a516d) +- [Swift Developments Newsletter #113](https://andybargh.com/swiftdevelopments-113/) +- [iOS Goodies #204](http://ios-goodies.com/post/167557280951/week-204) +- [Swift Weekly #96](http://digest.swiftweekly.com/issues/swift-weekly-issue-96-81759) +- [CocoaControls](https://www.cocoacontrols.com/controls/skeletonview) +- [Awesome iOS Newsletter #74](https://ios.libhunt.com/newsletter/74) +- [Swift News #36](https://www.youtube.com/watch?v=mAGpsQiy6so) +- [Best iOS articles, new tools & more](https://medium.com/flawless-app-stories/best-ios-articles-new-tools-more-fcbe673e10d) + +## 🏆 Sponsors + +Open-source projects cannot live long without your help. If you find **SkeletonView** is useful, please consider supporting this +project by becoming a sponsor. + +Become a sponsor through [GitHub Sponsors](https://github.com/sponsors/Juanpe) :heart: + +## 👨🏻‍💻 Author + +[Juanpe Catalán](http://www.twitter.com/JuanpeCatalan) + +Buy me a coffee + + +## 👮🏻 License + +``` +MIT License + +Copyright (c) 2017 Juanpe Catalán + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/AnimationBuilder/SkeletonAnimationBuilder.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/AnimationBuilder/SkeletonAnimationBuilder.swift new file mode 100644 index 0000000..321c9b1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/AnimationBuilder/SkeletonAnimationBuilder.swift @@ -0,0 +1,39 @@ +// +// SkeletonAnimationBuilder.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 17/11/2017. +// Copyright © 2017 SkeletonView. All rights reserved. +// + +import UIKit + +public typealias SkeletonLayerAnimation = (CALayer) -> CAAnimation + +public class SkeletonAnimationBuilder { + + public init() { } + + public func makeSlidingAnimation(withDirection direction: GradientDirection, duration: CFTimeInterval = 1.5, autoreverses: Bool = false) -> SkeletonLayerAnimation { + { _ in + let startPointAnim = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.startPoint)) + startPointAnim.fromValue = direction.startPoint.from + startPointAnim.toValue = direction.startPoint.to + + let endPointAnim = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.endPoint)) + endPointAnim.fromValue = direction.endPoint.from + endPointAnim.toValue = direction.endPoint.to + + let animGroup = CAAnimationGroup() + animGroup.animations = [startPointAnim, endPointAnim] + animGroup.duration = duration + animGroup.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) + animGroup.repeatCount = .infinity + animGroup.autoreverses = autoreverses + animGroup.isRemovedOnCompletion = false + + return animGroup + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Appearance/SkeletonAppearance.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Appearance/SkeletonAppearance.swift new file mode 100644 index 0000000..9990344 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Appearance/SkeletonAppearance.swift @@ -0,0 +1,41 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonAppearance.swift +// + +import UIKit + +public enum SkeletonAppearance { + public static var `default` = SkeletonViewAppearance.shared +} + +// codebeat:disable[TOO_MANY_IVARS] +public class SkeletonViewAppearance { + + static var shared = SkeletonViewAppearance() + + public var tintColor: UIColor = .skeletonDefault + + public var gradient = SkeletonGradient(baseColor: .skeletonDefault) + + public var multilineHeight: CGFloat = 15 + + public var useFontLineHeight: Bool = true + + public var multilineSpacing: CGFloat = 10 + + public var multilineLastLineFillPercent: Int = 70 + + public var multilineCornerRadius: Int = 0 + + public var renderSingleLineAsView: Bool = false + +} +// codebeat:enable[TOO_MANY_IVARS] diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Collections/CollectionViews/SkeletonCollectionViewProtocols.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Collections/CollectionViews/SkeletonCollectionViewProtocols.swift new file mode 100644 index 0000000..a8953eb --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Collections/CollectionViews/SkeletonCollectionViewProtocols.swift @@ -0,0 +1,40 @@ +// +// SkeletonCollectionViewProtocols.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 06/11/2017. +// Copyright © 2017 SkeletonView. All rights reserved. +// + +import UIKit + +public protocol SkeletonCollectionViewDataSource: UICollectionViewDataSource { + func numSections(in collectionSkeletonView: UICollectionView) -> Int + func collectionSkeletonView(_ skeletonView: UICollectionView, numberOfItemsInSection section: Int) -> Int + func collectionSkeletonView(_ skeletonView: UICollectionView, cellIdentifierForItemAt indexPath: IndexPath) -> ReusableCellIdentifier + func collectionSkeletonView(_ skeletonView: UICollectionView, supplementaryViewIdentifierOfKind: String, at indexPath: IndexPath) -> ReusableCellIdentifier? + func collectionSkeletonView(_ skeletonView: UICollectionView, skeletonCellForItemAt indexPath: IndexPath) -> UICollectionViewCell? + func collectionSkeletonView(_ skeletonView: UICollectionView, prepareCellForSkeleton cell: UICollectionViewCell, at indexPath: IndexPath) +} + +public extension SkeletonCollectionViewDataSource { + func collectionSkeletonView(_ skeletonView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + UICollectionView.automaticNumberOfSkeletonItems + } + + func collectionSkeletonView(_ skeletonView: UICollectionView, supplementaryViewIdentifierOfKind: String, at indexPath: IndexPath) -> ReusableCellIdentifier? { + nil + } + + func numSections(in collectionSkeletonView: UICollectionView) -> Int { + 1 + } + + func collectionSkeletonView(_ skeletonView: UICollectionView, skeletonCellForItemAt indexPath: IndexPath) -> UICollectionViewCell? { + nil + } + + func collectionSkeletonView(_ skeletonView: UICollectionView, prepareCellForSkeleton cell: UICollectionViewCell, at indexPath: IndexPath) { } +} + +public protocol SkeletonCollectionViewDelegate: UICollectionViewDelegate { } diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Collections/TableViews/SkeletonTableViewProtocols.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Collections/TableViews/SkeletonTableViewProtocols.swift new file mode 100644 index 0000000..fa1f7fa --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Collections/TableViews/SkeletonTableViewProtocols.swift @@ -0,0 +1,59 @@ +// +// SkeletonTableViewProtocols.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 06/11/2017. +// Copyright © 2017 SkeletonView. All rights reserved. +// + +import UIKit + +extension UITableView { + public static let automaticNumberOfSkeletonRows = -1 +} + +public typealias ReusableHeaderFooterIdentifier = String + +public protocol SkeletonTableViewDataSource: UITableViewDataSource { + func numSections(in collectionSkeletonView: UITableView) -> Int + func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int + func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier + func collectionSkeletonView(_ skeletonView: UITableView, skeletonCellForRowAt indexPath: IndexPath) -> UITableViewCell? + func collectionSkeletonView(_ skeletonView: UITableView, prepareCellForSkeleton cell: UITableViewCell, at indexPath: IndexPath) +} + +public extension SkeletonTableViewDataSource { + func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int { + return UITableView.automaticNumberOfSkeletonRows + } + + func numSections(in collectionSkeletonView: UITableView) -> Int { return 1 } + + /// Keeping the misspelled version around until it can be deprecated + /// Right now, it just calls the new correctly spelled method and returns its result + @available(*, deprecated, renamed: "collectionSkeletonView(_:cellIdentifierForRowAt:)") + func collectionSkeletonView(_ skeletonView: UITableView, cellIdenfierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier { + return collectionSkeletonView(skeletonView, cellIdentifierForRowAt: indexPath) + } + + func collectionSkeletonView(_ skeletonView: UITableView, skeletonCellForRowAt indexPath: IndexPath) -> UITableViewCell? { + nil + } + + func collectionSkeletonView(_ skeletonView: UITableView, prepareCellForSkeleton cell: UITableViewCell, at indexPath: IndexPath) { } +} + +public protocol SkeletonTableViewDelegate: UITableViewDelegate { + func collectionSkeletonView(_ skeletonView: UITableView, identifierForHeaderInSection section: Int) -> ReusableHeaderFooterIdentifier? + func collectionSkeletonView(_ skeletonView: UITableView, identifierForFooterInSection section: Int) -> ReusableHeaderFooterIdentifier? +} + +public extension SkeletonTableViewDelegate { + func collectionSkeletonView(_ skeletonView: UITableView, identifierForHeaderInSection section: Int) -> ReusableHeaderFooterIdentifier? { + return nil + } + + func collectionSkeletonView(_ skeletonView: UITableView, identifierForFooterInSection section: Int) -> ReusableHeaderFooterIdentifier? { + return nil + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Deprecated.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Deprecated.swift new file mode 100644 index 0000000..fbacf20 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Deprecated.swift @@ -0,0 +1,50 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Deprecated.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +public extension Notification.Name { + + @available(*, deprecated, renamed: "skeletonWillAppear") + static let willBeginShowingSkeletons = Notification.Name.skeletonWillAppearNotification + + @available(*, deprecated, renamed: "skeletonDidAppear") + static let didShowSkeletons = Notification.Name.skeletonDidAppearNotification + + @available(*, deprecated, renamed: "skeletonWillUpdate") + static let willBeginUpdatingSkeletons = Notification.Name.skeletonWillUpdateNotification + + @available(*, deprecated, renamed: "skeletonDidUpdate") + static let didUpdateSkeletons = Notification.Name.skeletonDidUpdateNotification + + @available(*, deprecated, renamed: "skeletonWillDisappear") + static let willBeginHidingSkeletons = Notification.Name.skeletonWillDisappearNotification + + @available(*, deprecated, renamed: "skeletonDidDisappear") + static let didHideSkeletons = Notification.Name.skeletonDidDisappearNotification + +} + +public extension UIView { + + @available(*, deprecated, renamed: "sk.treeNodesDescription") + var skeletonDescription: String { + sk.skeletonTreeDescription + } + + @available(*, deprecated, renamed: "sk.isSkeletonActive") + var isSkeletonActive: Bool { + sk.isSkeletonActive + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/FoundationExtensions/Notification+SkeletonFlow.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/FoundationExtensions/Notification+SkeletonFlow.swift new file mode 100644 index 0000000..51f8274 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/FoundationExtensions/Notification+SkeletonFlow.swift @@ -0,0 +1,25 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Notification+SkeletonFlow.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import Foundation + +public extension Notification.Name { + + static let skeletonWillAppearNotification = Notification.Name("skeletonWillAppear") + static let skeletonDidAppearNotification = Notification.Name("skeletonDidAppear") + static let skeletonWillUpdateNotification = Notification.Name("skeletonWillUpdate") + static let skeletonDidUpdateNotification = Notification.Name("skeletonDidUpdate") + static let skeletonWillDisappearNotification = Notification.Name("skeletonWillDisappear") + static let skeletonDidDisappearNotification = Notification.Name("skeletonDidDisappear") + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/GradientDirection.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/GradientDirection.swift new file mode 100644 index 0000000..0cd6011 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/GradientDirection.swift @@ -0,0 +1,29 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// GradientDirection.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +public enum GradientDirection { + + case leftRight + case rightLeft + case topBottom + case bottomTop + case topLeftBottomRight + case bottomRightTopLeft + + public func slidingAnimation(duration: CFTimeInterval = 1.5, autoreverses: Bool = false) -> SkeletonLayerAnimation { + return SkeletonAnimationBuilder().makeSlidingAnimation(withDirection: self, duration: duration, autoreverses: autoreverses) + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonGradient.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonGradient.swift new file mode 100644 index 0000000..189de74 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonGradient.swift @@ -0,0 +1,32 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonGradient.swift +// +// Created by Juanpe Catalán on 05/11/2017. + +import UIKit + +public struct SkeletonGradient { + + private let gradientColors: [UIColor] + + public var colors: [UIColor] { + return gradientColors + } + + public init(baseColor: UIColor, secondaryColor: UIColor? = nil) { + if let secondary = secondaryColor { + self.gradientColors = [baseColor, secondary, baseColor] + } else { + self.gradientColors = baseColor.makeGradient() + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonTransitionStyle.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonTransitionStyle.swift new file mode 100644 index 0000000..bca1687 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonTransitionStyle.swift @@ -0,0 +1,8 @@ +// Copyright © 2019 SkeletonView. All rights reserved. + +import UIKit + +public enum SkeletonTransitionStyle: Equatable { + case none + case crossDissolve(TimeInterval) +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonType.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonType.swift new file mode 100644 index 0000000..0d97d5d --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/Models/SkeletonType.swift @@ -0,0 +1,39 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonType.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +public enum SkeletonType { + + case solid + case gradient + + var layer: CALayer { + switch self { + case .solid: + return CALayer() + case .gradient: + return CAGradientLayer() + } + } + + func defaultLayerAnimation(isRTL: Bool) -> SkeletonLayerAnimation { + switch self { + case .solid: + return { $0.pulse } + case .gradient: + return { SkeletonAnimationBuilder().makeSlidingAnimation(withDirection: isRTL ? .rightLeft : .leftRight) }() + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/SkeletonExtended.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/SkeletonExtended.swift new file mode 100644 index 0000000..483633b --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/SkeletonExtended.swift @@ -0,0 +1,45 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonExtended.swift +// +// Created by Juanpe Catalán on 23/8/21. + +import Foundation + +/// Type that acts as a generic extension point for all `SkeletonViewExtended` types. +public struct SkeletonViewExtension { + /// 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 `sk` extension points for SkeletonView extended types. +public protocol SkeletonViewExtended { + /// Type being extended. + associatedtype ExtendedType + + /// Instance SkeletonView extension point. + var sk: SkeletonViewExtension { get set } +} + +extension SkeletonViewExtended { + /// Instance SkeletonView extension point. + public var sk: SkeletonViewExtension { + get { SkeletonViewExtension(self) } + // swiftlint:disable:next unused_setter_value + set {} + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/SkeletonView.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/SkeletonView.swift new file mode 100644 index 0000000..8f4f5f7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/SkeletonView.swift @@ -0,0 +1,150 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// PublicSkeletonView.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +public extension UIView { + /// Shows the skeleton without animation using the view that calls this method as root view. + /// + /// - Parameters: + /// - color: The color of the skeleton. Defaults to `SkeletonAppearance.default.tintColor`. + /// - transition: The style of the transition when the skeleton appears. Defaults to `.crossDissolve(0.25)`. + func showSkeleton(usingColor color: UIColor = SkeletonAppearance.default.tintColor, transition: SkeletonTransitionStyle = .crossDissolve(0.25)) { + _delayedShowSkeletonWorkItem?.cancel() + let config = SkeletonConfig(type: .solid, colors: [color], transition: transition) + showSkeleton(skeletonConfig: config) + } + + /// Shows the skeleton using the view that calls this method as root view. + /// + /// - Parameters: + /// - color: The color of the skeleton. Defaults to `SkeletonAppearance.default.tintColor`. + /// - animated: If the skeleton is animated or not. Defaults to `true`. + /// - delay: The amount of time (measured in seconds) to wait before show the skeleton. + /// - transition: The style of the transition when the skeleton appears. Defaults to `.crossDissolve(0.25)`. + func showSkeleton(usingColor color: UIColor = SkeletonAppearance.default.tintColor, animated: Bool = true, delay: TimeInterval, transition: SkeletonTransitionStyle = .crossDissolve(0.25)) { + _delayedShowSkeletonWorkItem?.cancel() + + _delayedShowSkeletonWorkItem = DispatchWorkItem { [weak self] in + let config = SkeletonConfig(type: .solid, colors: [color], animated: animated, transition: transition) + self?.showSkeleton(skeletonConfig: config) + } + + DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: _delayedShowSkeletonWorkItem!) + } + + /// Shows the gradient skeleton without animation using the view that calls this method as root view. + /// + /// - Parameters: + /// - gradient: The gradient of the skeleton. Defaults to `SkeletonAppearance.default.gradient`. + /// - transition: The style of the transition when the skeleton appears. Defaults to `.crossDissolve(0.25)`. + func showGradientSkeleton(usingGradient gradient: SkeletonGradient = SkeletonAppearance.default.gradient, transition: SkeletonTransitionStyle = .crossDissolve(0.25)) { + _delayedShowSkeletonWorkItem?.cancel() + let config = SkeletonConfig(type: .gradient, colors: gradient.colors, transition: transition) + showSkeleton(skeletonConfig: config) + } + + /// Shows the gradient skeleton using the view that calls this method as root view. + /// + /// - Parameters: + /// - gradient: The gradient of the skeleton. Defaults to `SkeletonAppearance.default.gradient`. + /// - animated: If the skeleton is animated or not. Defaults to `true`. + /// - delay: The amount of time (measured in seconds) to wait before show the skeleton. + /// - transition: The style of the transition when the skeleton appears. Defaults to `.crossDissolve(0.25)`. + func showGradientSkeleton( + usingGradient gradient: SkeletonGradient = SkeletonAppearance.default.gradient, + animated: Bool = true, + delay: TimeInterval, + transition: SkeletonTransitionStyle = .crossDissolve(0.25) + ) { + _delayedShowSkeletonWorkItem?.cancel() + + _delayedShowSkeletonWorkItem = DispatchWorkItem { [weak self] in + let config = SkeletonConfig(type: .gradient, colors: gradient.colors, animated: animated, transition: transition) + self?.showSkeleton(skeletonConfig: config) + } + + DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: _delayedShowSkeletonWorkItem!) + } + + /// Shows the animated skeleton using the view that calls this method as root view. + /// + /// If animation is nil, sliding animation will be used, with direction left to right. + /// + /// - Parameters: + /// - color: The color of skeleton. Defaults to `SkeletonAppearance.default.tintColor`. + /// - animation: The animation of the skeleton. Defaults to `nil`. + /// - transition: The style of the transition when the skeleton appears. Defaults to `.crossDissolve(0.25)`. + func showAnimatedSkeleton(usingColor color: UIColor = SkeletonAppearance.default.tintColor, animation: SkeletonLayerAnimation? = nil, transition: SkeletonTransitionStyle = .crossDissolve(0.25)) { + _delayedShowSkeletonWorkItem?.cancel() + let config = SkeletonConfig(type: .solid, colors: [color], animated: true, animation: animation, transition: transition) + showSkeleton(skeletonConfig: config) + } + + /// Shows the gradient skeleton without animation using the view that calls this method as root view. + /// + /// If animation is nil, sliding animation will be used, with direction left to right. + /// + /// - Parameters: + /// - gradient: The gradient of the skeleton. Defaults to `SkeletonAppearance.default.gradient`. + /// - animation: The animation of the skeleton. Defaults to `nil`. + /// - transition: The style of the transition when the skeleton appears. Defaults to `.crossDissolve(0.25)`. + func showAnimatedGradientSkeleton(usingGradient gradient: SkeletonGradient = SkeletonAppearance.default.gradient, animation: SkeletonLayerAnimation? = nil, transition: SkeletonTransitionStyle = .crossDissolve(0.25)) { + _delayedShowSkeletonWorkItem?.cancel() + let config = SkeletonConfig(type: .gradient, colors: gradient.colors, animated: true, animation: animation, transition: transition) + showSkeleton(skeletonConfig: config) + } + + func updateSkeleton(usingColor color: UIColor = SkeletonAppearance.default.tintColor) { + let config = SkeletonConfig(type: .solid, colors: [color]) + updateSkeleton(skeletonConfig: config) + } + + func updateGradientSkeleton(usingGradient gradient: SkeletonGradient = SkeletonAppearance.default.gradient) { + let config = SkeletonConfig(type: .gradient, colors: gradient.colors) + updateSkeleton(skeletonConfig: config) + } + + func updateAnimatedSkeleton(usingColor color: UIColor = SkeletonAppearance.default.tintColor, animation: SkeletonLayerAnimation? = nil) { + let config = SkeletonConfig(type: .solid, colors: [color], animated: true, animation: animation) + updateSkeleton(skeletonConfig: config) + } + + func updateAnimatedGradientSkeleton(usingGradient gradient: SkeletonGradient = SkeletonAppearance.default.gradient, animation: SkeletonLayerAnimation? = nil) { + let config = SkeletonConfig(type: .gradient, colors: gradient.colors, animated: true, animation: animation) + updateSkeleton(skeletonConfig: config) + } + + func layoutSkeletonIfNeeded() { + _flowDelegate?.willBeginLayingSkeletonsIfNeeded(rootView: self) + recursiveLayoutSkeletonIfNeeded(root: self) + } + + func hideSkeleton(reloadDataAfter reload: Bool = true, transition: SkeletonTransitionStyle = .crossDissolve(0.25)) { + _delayedShowSkeletonWorkItem?.cancel() + _flowDelegate?.willBeginHidingSkeletons(rootView: self) + recursiveHideSkeleton(reloadDataAfter: reload, transition: transition, root: self) + } + + func startSkeletonAnimation(_ anim: SkeletonLayerAnimation? = nil) { + subviewsSkeletonables.recursiveSearch(leafBlock: startSkeletonLayerAnimationBlock(anim)) { subview in + subview.startSkeletonAnimation(anim) + } + } + + func stopSkeletonAnimation() { + subviewsSkeletonables.recursiveSearch(leafBlock: stopSkeletonLayerAnimationBlock) { subview in + subview.stopSkeletonAnimation() + } + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/CALayer+Animations.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/CALayer+Animations.swift new file mode 100644 index 0000000..89d2219 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/CALayer+Animations.swift @@ -0,0 +1,32 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// CALayer+Animations.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +public extension CALayer { + + var pulse: CAAnimation { + let pulseAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.backgroundColor)) + pulseAnimation.fromValue = backgroundColor + + // swiftlint:disable:next force_unwrapping + pulseAnimation.toValue = UIColor(cgColor: backgroundColor!).complementaryColor.cgColor + pulseAnimation.duration = 1 + pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) + pulseAnimation.autoreverses = true + pulseAnimation.repeatCount = .infinity + pulseAnimation.isRemovedOnCompletion = false + return pulseAnimation + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UICollectionView+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UICollectionView+Extensions.swift new file mode 100644 index 0000000..b34361c --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UICollectionView+Extensions.swift @@ -0,0 +1,34 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UICollectionView+Extensions.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +public extension UICollectionView { + + static let automaticNumberOfSkeletonItems = -1 + + func prepareSkeleton(completion: @escaping (Bool) -> Void) { + guard let originalDataSource = self.dataSource as? SkeletonCollectionViewDataSource, + !(originalDataSource is SkeletonCollectionDataSource) + else { return } + + let dataSource = SkeletonCollectionDataSource(collectionViewDataSource: originalDataSource, rowHeight: 0.0) + self.skeletonDataSource = dataSource + performBatchUpdates({ + self.reloadData() + }) { done in + completion(done) + + } + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+IBInspectable.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+IBInspectable.swift new file mode 100644 index 0000000..0013860 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+IBInspectable.swift @@ -0,0 +1,42 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UILabel+IBInspectable.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +public extension UILabel { + + @IBInspectable + var lastLineFillPercent: Int { + get { return lastLineFillingPercent } + set { lastLineFillingPercent = min(newValue, 100) } + } + + @IBInspectable + var linesCornerRadius: Int { + get { return multilineCornerRadius } + set { multilineCornerRadius = newValue } + } + + @IBInspectable + var skeletonLineSpacing: CGFloat { + get { return multilineSpacing } + set { multilineSpacing = newValue } + } + + @IBInspectable + var useFontLineHeight: Bool { + get { usesTextHeightForLines } + set { usesTextHeightForLines = newValue } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+SKExtensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+SKExtensions.swift new file mode 100644 index 0000000..ae4e5ed --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UILabel+SKExtensions.swift @@ -0,0 +1,23 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UILabel+SKExtensions.swift +// +// Created by Juanpe Catalán on 23/8/21. + +import UIKit + +public extension UILabel { + + var skeletonPaddingInsets: UIEdgeInsets { + get { return paddingInsets } + set { paddingInsets = newValue } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+IBInspectable.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+IBInspectable.swift new file mode 100644 index 0000000..52d39c7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+IBInspectable.swift @@ -0,0 +1,42 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UITextView+IBInspectable.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +public extension UITextView { + + @IBInspectable + var lastLineFillPercent: Int { + get { return lastLineFillingPercent } + set { lastLineFillingPercent = min(newValue, 100) } + } + + @IBInspectable + var linesCornerRadius: Int { + get { return multilineCornerRadius } + set { multilineCornerRadius = newValue } + } + + @IBInspectable + var skeletonLineSpacing: CGFloat { + get { return multilineSpacing } + set { multilineSpacing = newValue } + } + + @IBInspectable + var useFontLineHeight: Bool { + get { usesTextHeightForLines } + set { usesTextHeightForLines = newValue } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+SKExtensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+SKExtensions.swift new file mode 100644 index 0000000..d18f635 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UITextView+SKExtensions.swift @@ -0,0 +1,23 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UITextView+SKExtensions.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +public extension UITextView { + + var skeletonPaddingInsets: UIEdgeInsets { + get { return paddingInsets } + set { paddingInsets = newValue } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UIView+IBInspectable.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UIView+IBInspectable.swift new file mode 100644 index 0000000..b5a83e0 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UIView+IBInspectable.swift @@ -0,0 +1,42 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UIView+IBInspectable.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +public extension UIView { + + @IBInspectable + var isSkeletonable: Bool { + get { _skeletonable } + set { _skeletonable = newValue } + } + + @IBInspectable + var isHiddenWhenSkeletonIsActive: Bool { + get { _hiddenWhenSkeletonIsActive } + set { _hiddenWhenSkeletonIsActive = newValue } + } + + @IBInspectable + var isUserInteractionDisabledWhenSkeletonIsActive: Bool { + get { _disabledWhenSkeletonIsActive } + set { _disabledWhenSkeletonIsActive = newValue } + } + + @IBInspectable + var skeletonCornerRadius: Float { + get { _skeletonableCornerRadius } + set { _skeletonableCornerRadius = newValue } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UIView+SKExtensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UIView+SKExtensions.swift new file mode 100644 index 0000000..7262ce8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/API/UIKitExtensions/UIView+SKExtensions.swift @@ -0,0 +1,33 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UIView+SKExtensions.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +public extension SkeletonViewExtension where ExtendedType: UIView { + + /// Returns a string that describes the hierarchy of the skeleton, indicating + /// whether the receiver is skeletonable and all skeletonable children. + var skeletonTreeDescription: String { + guard let theJSONData = try? JSONSerialization.data(withJSONObject: treeNode.dictionaryRepresentation, options: [.prettyPrinted]) else { + skeletonLog("Skeleton tree generation has failed!") + return "" + } + + return String(data: theJSONData, encoding: .utf8)! + } + + var isSkeletonActive: Bool { + type._status == .on || type.subviewsSkeletonables.contains(where: { $0.sk.isSkeletonActive }) + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/CollectionSkeleton.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/CollectionSkeleton.swift new file mode 100644 index 0000000..578ad59 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/CollectionSkeleton.swift @@ -0,0 +1,50 @@ +// +// CollectionSkeleton.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 02/11/2017. +// Copyright © 2017 SkeletonView. All rights reserved. +// + +import UIKit + +enum CollectionAssociatedKeys { + static var dummyDataSource = "dummyDataSource" + static var dummyDelegate = "dummyDelegate" +} + +protocol CollectionSkeleton { + + var skeletonDataSource: SkeletonCollectionDataSource? { get set } + var skeletonDelegate: SkeletonCollectionDelegate? { get set } + var estimatedNumberOfRows: Int { get } + + func addDummyDataSource() + func updateDummyDataSource() + func removeDummyDataSource(reloadAfter: Bool) + func disableUserInteraction() + func enableUserInteraction() + +} + +extension CollectionSkeleton where Self: UIScrollView { + + var estimatedNumberOfRows: Int { return 0 } + func addDummyDataSource() {} + func removeDummyDataSource(reloadAfter: Bool) {} + + func disableUserInteraction() { + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = false + isScrollEnabled = false + } + } + + func enableUserInteraction() { + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = true + isScrollEnabled = true + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDataSource.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDataSource.swift new file mode 100644 index 0000000..1b56a04 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDataSource.swift @@ -0,0 +1,124 @@ +// +// SkeletonCollectionDataSource.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 02/11/2017. +// Copyright © 2017 SkeletonView. All rights reserved. +// + +import UIKit + +public typealias ReusableCellIdentifier = String + +class SkeletonCollectionDataSource: NSObject { + weak var originalTableViewDataSource: SkeletonTableViewDataSource? + weak var originalCollectionViewDataSource: SkeletonCollectionViewDataSource? + var rowHeight: CGFloat = 0.0 + var originalRowHeight: CGFloat = 0.0 + + convenience init(tableViewDataSource: SkeletonTableViewDataSource? = nil, collectionViewDataSource: SkeletonCollectionViewDataSource? = nil, rowHeight: CGFloat = 0.0, originalRowHeight: CGFloat = 0.0) { + self.init() + self.originalTableViewDataSource = tableViewDataSource + self.originalCollectionViewDataSource = collectionViewDataSource + self.rowHeight = rowHeight + self.originalRowHeight = originalRowHeight + } +} + +// MARK: - UITableViewDataSource +extension SkeletonCollectionDataSource: UITableViewDataSource { + func numberOfSections(in tableView: UITableView) -> Int { + originalTableViewDataSource?.numSections(in: tableView) ?? 0 + } + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + guard let originalTableViewDataSource = originalTableViewDataSource else { + return 0 + } + + let numberOfRows = originalTableViewDataSource.collectionSkeletonView(tableView, numberOfRowsInSection: section) + + if numberOfRows == UITableView.automaticNumberOfSkeletonRows { + return tableView.estimatedNumberOfRows + } else { + return numberOfRows + } + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + guard let cell = originalTableViewDataSource?.collectionSkeletonView(tableView, skeletonCellForRowAt: indexPath) else { + let cellIdentifier = originalTableViewDataSource?.collectionSkeletonView(tableView, cellIdentifierForRowAt: indexPath) ?? "" + let fakeCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) + + originalTableViewDataSource?.collectionSkeletonView(tableView, prepareCellForSkeleton: fakeCell, at: indexPath) + skeletonViewIfContainerSkeletonIsActive(container: tableView, view: fakeCell) + + return fakeCell + } + + originalTableViewDataSource?.collectionSkeletonView(tableView, prepareCellForSkeleton: cell, at: indexPath) + skeletonViewIfContainerSkeletonIsActive(container: tableView, view: cell) + return cell + } +} + +// MARK: - UICollectionViewDataSource +extension SkeletonCollectionDataSource: UICollectionViewDataSource { + func numberOfSections(in collectionView: UICollectionView) -> Int { + originalCollectionViewDataSource?.numSections(in: collectionView) ?? 0 + } + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + guard let originalCollectionViewDataSource = originalCollectionViewDataSource else { + return 0 + } + + let numberOfItems = originalCollectionViewDataSource.collectionSkeletonView(collectionView, numberOfItemsInSection: section) + + if numberOfItems == UICollectionView.automaticNumberOfSkeletonItems { + return collectionView.estimatedNumberOfRows + } else { + return numberOfItems + } + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + guard let cell = originalCollectionViewDataSource?.collectionSkeletonView(collectionView, skeletonCellForItemAt: indexPath) else { + let cellIdentifier = originalCollectionViewDataSource?.collectionSkeletonView(collectionView, cellIdentifierForItemAt: indexPath) ?? "" + let fakeCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) + + originalCollectionViewDataSource?.collectionSkeletonView(collectionView, prepareCellForSkeleton: fakeCell, at: indexPath) + skeletonViewIfContainerSkeletonIsActive(container: collectionView, view: fakeCell) + + return fakeCell + } + + originalCollectionViewDataSource?.collectionSkeletonView(collectionView, prepareCellForSkeleton: cell, at: indexPath) + skeletonViewIfContainerSkeletonIsActive(container: collectionView, view: cell) + return cell + } + + func collectionView(_ collectionView: UICollectionView, + viewForSupplementaryElementOfKind kind: String, + at indexPath: IndexPath) -> UICollectionReusableView { + if let viewIdentifier = originalCollectionViewDataSource?.collectionSkeletonView(collectionView, supplementaryViewIdentifierOfKind: kind, at: indexPath) { + let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: viewIdentifier, for: indexPath) + skeletonViewIfContainerSkeletonIsActive(container: collectionView, view: view) + return view + } + + return originalCollectionViewDataSource?.collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath) ?? UICollectionReusableView() + } + +} + +extension SkeletonCollectionDataSource { + private func skeletonViewIfContainerSkeletonIsActive(container: UIView, view: UIView) { + guard container.sk.isSkeletonActive, + let skeletonConfig = container._currentSkeletonConfig else { + return + } + + view.showSkeleton(skeletonConfig: skeletonConfig) + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDelegate.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDelegate.swift new file mode 100644 index 0000000..aa9ca70 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonCollectionDelegate.swift @@ -0,0 +1,65 @@ +// +// SkeletonCollectionDelegate.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 30/03/2018. +// Copyright © 2018 SkeletonView. All rights reserved. +// + +import UIKit + +class SkeletonCollectionDelegate: NSObject { + weak var originalTableViewDelegate: SkeletonTableViewDelegate? + weak var originalCollectionViewDelegate: SkeletonCollectionViewDelegate? + + init(tableViewDelegate: SkeletonTableViewDelegate? = nil, collectionViewDelegate: SkeletonCollectionViewDelegate? = nil) { + self.originalTableViewDelegate = tableViewDelegate + self.originalCollectionViewDelegate = collectionViewDelegate + } +} + +// MARK: - UITableViewDelegate +extension SkeletonCollectionDelegate: UITableViewDelegate { + func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { + headerOrFooterView(tableView, for: originalTableViewDelegate?.collectionSkeletonView(tableView, identifierForHeaderInSection: section)) + } + + func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { + headerOrFooterView(tableView, for: originalTableViewDelegate?.collectionSkeletonView(tableView, identifierForFooterInSection: section)) + } + + func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) { + view.hideSkeleton() + originalTableViewDelegate?.tableView?(tableView, didEndDisplayingHeaderView: view, forSection: section) + } + + func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) { + view.hideSkeleton() + originalTableViewDelegate?.tableView?(tableView, didEndDisplayingFooterView: view, forSection: section) + } + + func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { + cell.hideSkeleton() + originalTableViewDelegate?.tableView?(tableView, didEndDisplaying: cell, forRowAt: indexPath) + } + + private func headerOrFooterView(_ tableView: UITableView, for viewIdentifier: String? ) -> UIView? { + guard let viewIdentifier = viewIdentifier, let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: viewIdentifier) else { return nil } + skeletonViewIfContainerSkeletonIsActive(container: tableView, view: header) + return header + } +} + +// MARK: - UICollectionViewDelegate +extension SkeletonCollectionDelegate: UICollectionViewDelegate { } + +extension SkeletonCollectionDelegate { + private func skeletonViewIfContainerSkeletonIsActive(container: UIView, view: UIView) { + guard container.sk.isSkeletonActive, + let skeletonConfig = container._currentSkeletonConfig else { + return + } + + view.showSkeleton(skeletonConfig: skeletonConfig) + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonReusableCell.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonReusableCell.swift new file mode 100644 index 0000000..c2eff14 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Collections/SkeletonReusableCell.swift @@ -0,0 +1,15 @@ +// +// SkeletonReusableCell.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 30/03/2018. +// Copyright © 2018 SkeletonView. All rights reserved. +// + +import UIKit + +public protocol SkeletonReusableCell { } + +extension UITableViewCell: SkeletonReusableCell { } + +extension UICollectionViewCell: SkeletonReusableCell { } diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Debug/SkeletonDebug.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Debug/SkeletonDebug.swift new file mode 100644 index 0000000..27fcb53 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Debug/SkeletonDebug.swift @@ -0,0 +1,34 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonDebug.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import Foundation +import UIKit + +enum SkeletonEnvironmentKey: String { + case debugMode = "SKELETON_DEBUG" +} + +extension Dictionary { + subscript (_ key: SkeletonEnvironmentKey) -> Value? { + // swiftlint:disable:next force_cast + return self[key.rawValue as! Key] + } +} + +func skeletonLog(_ message: String) { + #if DEBUG + if ProcessInfo.processInfo.environment[.debugMode] != nil { + print(message) + } + #endif +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/DispatchQueue+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..20740e3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/DispatchQueue+Extensions.swift @@ -0,0 +1,37 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// DispatchQueue+Extensions.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import Foundation + +extension DispatchQueue { + + private static var _onceTracker = [String]() + + class func once(token: String, block: () -> Void) { + objc_sync_enter(self) + defer { objc_sync_exit(self) } + guard !_onceTracker.contains(token) else { return } + + _onceTracker.append(token) + block() + } + + class func removeOnce(token: String, block: () -> Void) { + objc_sync_enter(self) + defer { objc_sync_exit(self) } + guard let index = _onceTracker.firstIndex(of: token) else { return } + _onceTracker.remove(at: index) + block() + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/Int+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/Int+Extensions.swift new file mode 100644 index 0000000..c114944 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/Int+Extensions.swift @@ -0,0 +1,25 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Int+Extensions.swift +// + +import Foundation + +extension Int { + + var whitespace: String { + whitespaces + } + + var whitespaces: String { + String(repeating: " ", count: self) + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/Notification+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/Notification+Extensions.swift new file mode 100644 index 0000000..959c636 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/Notification+Extensions.swift @@ -0,0 +1,22 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Notification+Extensions.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +extension Notification.Name { + + static let applicationDidBecomeActiveNotification = UIApplication.didBecomeActiveNotification + static let applicationWillTerminateNotification = UIApplication.willTerminateNotification + static let applicationDidEnterForegroundNotification = UIApplication.didEnterBackgroundNotification + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/ProcessInfo+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/ProcessInfo+Extensions.swift new file mode 100644 index 0000000..1b8032b --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/FoundationExtensions/ProcessInfo+Extensions.swift @@ -0,0 +1,26 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// ProcessInfo+Extensions.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import Foundation + +extension ProcessInfo { + + enum Constants { + static let testConfigurationFilePathKey = "XCTestConfigurationFilePath" + } + + static var isRunningXCTest: Bool { + return processInfo.environment[Constants.testConfigurationFilePathKey] != nil + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/AssociationPolicy.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/AssociationPolicy.swift new file mode 100644 index 0000000..e3fade5 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/AssociationPolicy.swift @@ -0,0 +1,45 @@ +// Copyright © 2017 SkeletonView. All rights reserved. + +import Foundation + +// Partially copy/pasted from https://github.com/jameslintaylor/AssociatedObjects/blob/master/AssociatedObjects/AssociatedObjects.swift +enum AssociationPolicy: UInt { + // raw values map to objc_AssociationPolicy's raw values + case assign = 0 + case copy = 771 + case copyNonatomic = 3 + case retain = 769 + case retainNonatomic = 1 + + var objc: objc_AssociationPolicy { + // swiftlint:disable:next force_unwrapping + return objc_AssociationPolicy(rawValue: rawValue)! + } +} + +protocol AssociatedObjects: AnyObject { } + +extension AssociatedObjects { + /// wrapper around `objc_getAssociatedObject` + func ao_get(pkey: UnsafeRawPointer) -> Any? { + return objc_getAssociatedObject(self, pkey) + } + + /// wrapper around `objc_setAssociatedObject` + func ao_setOptional(_ value: Any?, pkey: UnsafeRawPointer, policy: AssociationPolicy = .retainNonatomic) { + guard let value = value else { return } + objc_setAssociatedObject(self, pkey, value, policy.objc) + } + + /// wrapper around `objc_setAssociatedObject` + func ao_set(_ value: Any, pkey: UnsafeRawPointer, policy: AssociationPolicy = .retainNonatomic) { + objc_setAssociatedObject(self, pkey, value, policy.objc) + } + + /// wrapper around 'objc_removeAssociatedObjects' + func ao_removeAll() { + objc_removeAssociatedObjects(self) + } +} + +extension NSObject: AssociatedObjects { } diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/Recursive.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/Recursive.swift new file mode 100644 index 0000000..0cd1fce --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/Recursive.swift @@ -0,0 +1,26 @@ +// Copyright © 2017 SkeletonView. All rights reserved. + +import UIKit + +typealias VoidBlock = () -> Void +typealias RecursiveBlock = (T) -> Void + +protocol IterableElement {} +extension UIView: IterableElement {} +extension CALayer: IterableElement {} + +// MARK: Recursive +protocol Recursive { + associatedtype Element: IterableElement + func recursiveSearch(leafBlock: VoidBlock, recursiveBlock: RecursiveBlock) +} + +extension Array: Recursive where Element: IterableElement { + func recursiveSearch(leafBlock: VoidBlock, recursiveBlock: RecursiveBlock) { + guard !isEmpty else { + leafBlock() + return + } + forEach { recursiveBlock($0) } + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/Swizzling.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/Swizzling.swift new file mode 100644 index 0000000..af3e24c --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Helpers/Swizzling.swift @@ -0,0 +1,15 @@ +// Copyright © 2019 SkeletonView. All rights reserved. + +import Foundation + +func swizzle(selector originalSelector: Selector, with swizzledSelector: Selector, inClass: AnyClass, usingClass: AnyClass) { + guard let originalMethod = class_getInstanceMethod(inClass, originalSelector), + let swizzledMethod = class_getInstanceMethod(usingClass, swizzledSelector) + else { return } + + if class_addMethod(inClass, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) { + class_replaceMethod(inClass, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) + } else { + method_exchangeImplementations(originalMethod, swizzledMethod) + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Models/RecoverableViewState.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Models/RecoverableViewState.swift new file mode 100644 index 0000000..281ef42 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Models/RecoverableViewState.swift @@ -0,0 +1,71 @@ +// +// RecoverableViewState.swift +// SkeletonView +// +// Created by Juanpe Catalán on 13/05/2018. +// Copyright © 2018 SkeletonView. All rights reserved. +// + +import UIKit + +struct RecoverableViewState { + + var backgroundColor: UIColor? + var cornerRadius: CGFloat + var clipToBounds: Bool + var isUserInteractionsEnabled: Bool + + init(view: UIView) { + self.backgroundColor = view.backgroundColor + self.clipToBounds = view.layer.masksToBounds + self.cornerRadius = view.layer.cornerRadius + self.isUserInteractionsEnabled = view.isUserInteractionEnabled + } + +} + +struct RecoverableTextViewState { + var textColor: UIColor? + + init(view: UILabel) { + self.textColor = view.textColor + } + + init(view: UITextView) { + self.textColor = view.textColor + } +} + +struct RecoverableTextFieldState { + var textColor: UIColor? + var placeholder: String? + + init(view: UITextField) { + self.textColor = view.textColor + self.placeholder = view.placeholder + } +} + +struct RecoverableImageViewState { + var image: UIImage? + + init(view: UIImageView) { + self.image = view.image + } +} + +struct RecoverableButtonViewState { + var title: String? + + init(view: UIButton) { + self.title = view.titleLabel?.text + } +} + +struct RecoverableTableViewHeaderFooterViewState { + var backgroundViewColor: UIColor? + + init(view: UITableViewHeaderFooterView) { + self.backgroundViewColor = view.backgroundView?.backgroundColor + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Models/SkeletonLayer.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Models/SkeletonLayer.swift new file mode 100755 index 0000000..fc065c0 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/Models/SkeletonLayer.swift @@ -0,0 +1,111 @@ +// +// SkeletonLayer.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 02/11/2017. +// Copyright © 2017 SkeletonView. All rights reserved. +// + +import UIKit + +struct SkeletonLayer { + + private var maskLayer: CALayer + private weak var holder: UIView? + + var type: SkeletonType { + return maskLayer is CAGradientLayer ? .gradient : .solid + } + + var contentLayer: CALayer { + return maskLayer + } + + init(type: SkeletonType, colors: [UIColor], skeletonHolder holder: UIView) { + self.holder = holder + self.maskLayer = type.layer + self.maskLayer.anchorPoint = .zero + self.maskLayer.bounds = holder.definedMaxBounds + self.maskLayer.cornerRadius = CGFloat(holder.skeletonCornerRadius) + addTextLinesIfNeeded() + self.maskLayer.tint(withColors: colors) + } + + func update(usingColors colors: [UIColor]) { + layoutIfNeeded() + maskLayer.tint(withColors: colors) + } + + func layoutIfNeeded() { + if let bounds = holder?.definedMaxBounds { + maskLayer.bounds = bounds + } + updateLinesIfNeeded() + } + + func removeLayer(transition: SkeletonTransitionStyle, completion: (() -> Void)? = nil) { + switch transition { + case .none: + maskLayer.removeFromSuperlayer() + completion?() + case .crossDissolve(let duration): + maskLayer.setOpacity(from: 1, to: 0, duration: duration) { + self.maskLayer.removeFromSuperlayer() + completion?() + } + } + } + + /// If there is more than one line, or custom preferences have been set for a single line, draw custom layers + func addTextLinesIfNeeded() { + guard let textView = holderAsTextView else { return } + let config = SkeletonMultilinesLayerConfig(lines: textView.numberOfLines, + lineHeight: textView.lineHeight, + type: type, + lastLineFillPercent: textView.lastLineFillingPercent, + multilineCornerRadius: textView.multilineCornerRadius, + multilineSpacing: textView.multilineSpacing, + paddingInsets: textView.paddingInsets, + alignment: textView.textAlignment, + isRTL: holder?.isRTL ?? false) + + maskLayer.addMultilinesLayers(for: config) + } + + func updateLinesIfNeeded() { + guard let textView = holderAsTextView else { return } + let config = SkeletonMultilinesLayerConfig(lines: textView.numberOfLines, + lineHeight: textView.lineHeight, + type: type, + lastLineFillPercent: textView.lastLineFillingPercent, + multilineCornerRadius: textView.multilineCornerRadius, + multilineSpacing: textView.multilineSpacing, + paddingInsets: textView.paddingInsets, + alignment: textView.textAlignment, + isRTL: holder?.isRTL ?? false) + + maskLayer.updateMultilinesLayers(for: config) + } + + var holderAsTextView: SkeletonTextNode? { + guard let textView = holder as? SkeletonTextNode, + (textView.numberOfLines == -1 || textView.numberOfLines == 0 || textView.numberOfLines > 1 || textView.numberOfLines == 1 && !SkeletonAppearance.default.renderSingleLineAsView) else { + return nil + } + return textView + } + +} + +extension SkeletonLayer { + + func start(_ anim: SkeletonLayerAnimation? = nil, completion: (() -> Void)? = nil) { + let animation = anim ?? type.defaultLayerAnimation(isRTL: holder?.isRTL ?? false) + contentLayer.playAnimation(animation, key: "skeletonAnimation", completion: completion) + } + + func stopAnimation() { + contentLayer.stopAnimation(forKey: "skeletonAnimation") + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonConfig.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonConfig.swift new file mode 100644 index 0000000..e467aa2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonConfig.swift @@ -0,0 +1,38 @@ +// Copyright © 2018 SkeletonView. All rights reserved. + +import UIKit + +/// Used to store all config needed to activate the skeleton layer. +struct SkeletonConfig { + /// Type of skeleton layer + let type: SkeletonType + + /// Colors used in skeleton layer + let colors: [UIColor] + + /// If type is gradient, which gradient direction + let gradientDirection: GradientDirection? + + /// Specify if skeleton is animated or not + let animated: Bool + + /// Used to execute a custom animation + let animation: SkeletonLayerAnimation? + + /// Transition style + var transition: SkeletonTransitionStyle + + init(type: SkeletonType, + colors: [UIColor], + gradientDirection: GradientDirection? = nil, + animated: Bool = false, + animation: SkeletonLayerAnimation? = nil, + transition: SkeletonTransitionStyle = .crossDissolve(0.25)) { + self.type = type + self.colors = colors + self.gradientDirection = gradientDirection + self.animated = animated + self.animation = animation + self.transition = transition + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonMultilinesLayerConfig.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonMultilinesLayerConfig.swift new file mode 100644 index 0000000..4d7e371 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonConfigs/SkeletonMultilinesLayerConfig.swift @@ -0,0 +1,36 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonMultilinesLayerConfig.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +struct SkeletonMultilinesLayerConfig { + + var lines: Int + var lineHeight: CGFloat + var type: SkeletonType + var lastLineFillPercent: Int + var multilineCornerRadius: Int + var multilineSpacing: CGFloat + var paddingInsets: UIEdgeInsets + var alignment: NSTextAlignment + var isRTL: Bool + + /// Returns padding insets taking into account if the RTL is activated + var calculatedPaddingInsets: UIEdgeInsets { + UIEdgeInsets(top: paddingInsets.top, + left: isRTL ? paddingInsets.right : paddingInsets.left, + bottom: paddingInsets.bottom, + right: isRTL ? paddingInsets.left : paddingInsets.right) + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/GradientDirection+Animations.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/GradientDirection+Animations.swift new file mode 100644 index 0000000..791b785 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/GradientDirection+Animations.swift @@ -0,0 +1,56 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// GradientDirection+Animations.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +typealias GradientAnimationPoint = (from: CGPoint, to: CGPoint) + +extension GradientDirection { + + // codebeat:disable[ABC] + var startPoint: GradientAnimationPoint { + switch self { + case .leftRight: + return (from: CGPoint(x: -1, y: 0.5), to: CGPoint(x: 1, y: 0.5)) + case .rightLeft: + return (from: CGPoint(x: 1, y: 0.5), to: CGPoint(x: -1, y: 0.5)) + case .topBottom: + return (from: CGPoint(x: 0.5, y: -1), to: CGPoint(x: 0.5, y: 1)) + case .bottomTop: + return (from: CGPoint(x: 0.5, y: 1), to: CGPoint(x: 0.5, y: -1)) + case .topLeftBottomRight: + return (from: CGPoint(x: -1, y: -1), to: CGPoint(x: 1, y: 1)) + case .bottomRightTopLeft: + return (from: CGPoint(x: 1, y: 1), to: CGPoint(x: -1, y: -1)) + } + } + + var endPoint: GradientAnimationPoint { + switch self { + case .leftRight: + return (from: CGPoint(x: 0, y: 0.5), to: CGPoint(x: 2, y: 0.5)) + case .rightLeft: + return ( from: CGPoint(x: 2, y: 0.5), to: CGPoint(x: 0, y: 0.5)) + case .topBottom: + return ( from: CGPoint(x: 0.5, y: 0), to: CGPoint(x: 0.5, y: 2)) + case .bottomTop: + return ( from: CGPoint(x: 0.5, y: 2), to: CGPoint(x: 0.5, y: 0)) + case .topLeftBottomRight: + return ( from: CGPoint(x: 0, y: 0), to: CGPoint(x: 2, y: 2)) + case .bottomRightTopLeft: + return ( from: CGPoint(x: 2, y: 2), to: CGPoint(x: 0, y: 0)) + } + } + // codebeat:enable[ABC] + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/PrepareViewForSkeleton.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/PrepareViewForSkeleton.swift new file mode 100644 index 0000000..660e668 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/PrepareViewForSkeleton.swift @@ -0,0 +1,120 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// PrepareViewForSkeleton.swift +// +// Created by Juanpe Catalán on 04/11/2017. + +import UIKit + +extension UIView { + + @objc func prepareViewForSkeleton() { + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = false + } + + startTransition { [weak self] in + self?.backgroundColor = .clear + } + } + +} + +extension UILabel { + + override func prepareViewForSkeleton() { + backgroundColor = .clear + + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = false + } + + resignFirstResponder() + startTransition { [weak self] in + self?.updateHeightConstraintsIfNeeded() + self?.textColor = .clear + } + } +} + +extension UITextView { + + override func prepareViewForSkeleton() { + backgroundColor = .clear + + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = false + } + + resignFirstResponder() + startTransition { [weak self] in + self?.textColor = .clear + } + } + +} + +extension UITextField { + + override func prepareViewForSkeleton() { + backgroundColor = .clear + resignFirstResponder() + + startTransition { [weak self] in + self?.textColor = .clear + self?.placeholder = nil + } + } + +} + +extension UIImageView { + + override func prepareViewForSkeleton() { + backgroundColor = .clear + + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = false + } + + startTransition { [weak self] in + self?.image = nil + } + } + +} + +extension UIButton { + + override func prepareViewForSkeleton() { + backgroundColor = .clear + + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = false + } + + startTransition { [weak self] in + self?.setTitle(nil, for: .normal) + } + } + +} + +extension UITableViewHeaderFooterView { + + override func prepareViewForSkeleton() { + backgroundView?.backgroundColor = .clear + + if isUserInteractionDisabledWhenSkeletonIsActive { + isUserInteractionEnabled = false + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/Recoverable.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/Recoverable.swift new file mode 100644 index 0000000..9cfb4b1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/Recoverable.swift @@ -0,0 +1,196 @@ +// +// Recoverable.swift +// SkeletonView +// +// Created by Juanpe Catalán on 13/05/2018. +// Copyright © 2018 SkeletonView. All rights reserved. +// + +import UIKit + +protocol Recoverable { + func saveViewState() + func recoverViewState(forced: Bool) +} + +extension UIView: Recoverable { + + var viewState: RecoverableViewState? { + get { return ao_get(pkey: &ViewAssociatedKeys.viewState) as? RecoverableViewState } + set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.viewState) } + } + + @objc func saveViewState() { + viewState = RecoverableViewState(view: self) + } + + @objc func recoverViewState(forced: Bool) { + guard let storedViewState = viewState else { return } + + startTransition { [weak self] in + guard let self = self else { return } + + self.layer.cornerRadius = storedViewState.cornerRadius + self.layer.masksToBounds = storedViewState.clipToBounds + + if self.isUserInteractionDisabledWhenSkeletonIsActive { + self.isUserInteractionEnabled = storedViewState.isUserInteractionsEnabled + } + + if self.backgroundColor == .clear || forced { + self.backgroundColor = storedViewState.backgroundColor + } + } + } + +} + +extension UILabel { + + var labelState: RecoverableTextViewState? { + get { return ao_get(pkey: &ViewAssociatedKeys.labelViewState) as? RecoverableTextViewState } + set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.labelViewState) } + } + + override func saveViewState() { + super.saveViewState() + labelState = RecoverableTextViewState(view: self) + } + + override func recoverViewState(forced: Bool) { + super.recoverViewState(forced: forced) + startTransition { [weak self] in + guard let self = self, + let storedLabelState = self.labelState else { + return + } + + NSLayoutConstraint.deactivate(self.skeletonHeightConstraints) + self.restoreBackupHeightConstraintsIfNeeded() + + if self.textColor == .clear || forced { + self.textColor = storedLabelState.textColor + } + } + } + +} + +extension UITextView { + + var textState: RecoverableTextViewState? { + get { return ao_get(pkey: &ViewAssociatedKeys.labelViewState) as? RecoverableTextViewState } + set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.labelViewState) } + } + + override func saveViewState() { + super.saveViewState() + textState = RecoverableTextViewState(view: self) + } + + override func recoverViewState(forced: Bool) { + super.recoverViewState(forced: forced) + startTransition { [weak self] in + guard let storedLabelState = self?.textState else { return } + + if self?.textColor == .clear || forced { + self?.textColor = storedLabelState.textColor + } + } + } + +} + +extension UITextField { + + var textState: RecoverableTextFieldState? { + get { return ao_get(pkey: &ViewAssociatedKeys.labelViewState) as? RecoverableTextFieldState } + set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.labelViewState) } + } + + override func saveViewState() { + super.saveViewState() + textState = RecoverableTextFieldState(view: self) + } + + override func recoverViewState(forced: Bool) { + super.recoverViewState(forced: forced) + startTransition { [weak self] in + guard let storedLabelState = self?.textState else { return } + + if self?.textColor == .clear || forced { + self?.textColor = storedLabelState.textColor + } + + if self?.placeholder == nil || forced { + self?.placeholder = storedLabelState.placeholder + } + } + } + +} + +extension UIImageView { + + var imageState: RecoverableImageViewState? { + get { return ao_get(pkey: &ViewAssociatedKeys.imageViewState) as? RecoverableImageViewState } + set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.imageViewState) } + } + + override func saveViewState() { + super.saveViewState() + imageState = RecoverableImageViewState(view: self) + } + + override func recoverViewState(forced: Bool) { + super.recoverViewState(forced: forced) + startTransition { [weak self] in + self?.image = self?.image == nil || forced ? self?.imageState?.image : self?.image + } + } + +} + +extension UIButton { + + var buttonState: RecoverableButtonViewState? { + get { return ao_get(pkey: &ViewAssociatedKeys.buttonViewState) as? RecoverableButtonViewState } + set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.buttonViewState) } + } + + override func saveViewState() { + super.saveViewState() + buttonState = RecoverableButtonViewState(view: self) + } + + override func recoverViewState(forced: Bool) { + super.recoverViewState(forced: forced) + startTransition { [weak self] in + if self?.title(for: .normal) == nil { + self?.setTitle(self?.buttonState?.title, for: .normal) + } + } + } + +} + +extension UITableViewHeaderFooterView { + + var headerFooterState: RecoverableTableViewHeaderFooterViewState? { + get { return ao_get(pkey: &ViewAssociatedKeys.headerFooterViewState) as? RecoverableTableViewHeaderFooterViewState } + set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.headerFooterViewState) } + } + + override func saveViewState() { + super.saveViewState() + headerFooterState = RecoverableTableViewHeaderFooterViewState(view: self) + } + + override func recoverViewState(forced: Bool) { + super.recoverViewState(forced: forced) + startTransition { [weak self] in + self?.backgroundView?.backgroundColor = self?.headerFooterState?.backgroundViewColor + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/SkeletonTextNode.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/SkeletonTextNode.swift new file mode 100644 index 0000000..34e5ef6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/SkeletonTextNode.swift @@ -0,0 +1,132 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonTextNode.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +protocol SkeletonTextNode { + + var lineHeight: CGFloat { get } + var numberOfLines: Int { get } + var textAlignment: NSTextAlignment { get } + var lastLineFillingPercent: Int { get } + var multilineCornerRadius: Int { get } + var multilineSpacing: CGFloat { get } + var paddingInsets: UIEdgeInsets { get } + var usesTextHeightForLines: Bool { get } +} + +enum SkeletonTextNodeAssociatedKeys { + + static var lastLineFillingPercent = "lastLineFillingPercent" + static var multilineCornerRadius = "multilineCornerRadius" + static var multilineSpacing = "multilineSpacing" + static var paddingInsets = "paddingInsets" + static var backupHeightConstraints = "backupHeightConstraints" + static var usesTextHeightForLines = "usesTextHeightForLines" + +} + +extension UILabel: SkeletonTextNode { + + var lineHeight: CGFloat { + let constraintsLineHeight = backupHeightConstraints.first?.constant ?? SkeletonAppearance.default.multilineHeight + + if useFontLineHeight, + let fontLineHeight = font?.lineHeight { + return fontLineHeight > constraintsLineHeight ? constraintsLineHeight : fontLineHeight + } else { + return constraintsLineHeight + } + } + + var usesTextHeightForLines: Bool { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.usesTextHeightForLines) as? Bool ?? SkeletonAppearance.default.useFontLineHeight } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.usesTextHeightForLines) } + } + + var lastLineFillingPercent: Int { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.lastLineFillingPercent) as? Int ?? SkeletonAppearance.default.multilineLastLineFillPercent } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.lastLineFillingPercent) } + } + + var multilineCornerRadius: Int { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.multilineCornerRadius) as? Int ?? SkeletonAppearance.default.multilineCornerRadius } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.multilineCornerRadius) } + } + + var multilineSpacing: CGFloat { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.multilineSpacing) as? CGFloat ?? SkeletonAppearance.default.multilineSpacing } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.multilineSpacing) } + } + + var paddingInsets: UIEdgeInsets { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.paddingInsets) as? UIEdgeInsets ?? .zero } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.paddingInsets) } + } + + var backupHeightConstraints: [NSLayoutConstraint] { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.backupHeightConstraints) as? [NSLayoutConstraint] ?? [] } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.backupHeightConstraints) } + } + +} + +extension UITextView: SkeletonTextNode { + + var lineHeight: CGFloat { + let constraintsLineHeight = heightConstraints.first?.constant ?? SkeletonAppearance.default.multilineHeight + + if useFontLineHeight, + let fontLineHeight = font?.lineHeight { + return fontLineHeight > constraintsLineHeight ? constraintsLineHeight : fontLineHeight + } else { + return constraintsLineHeight + } + } + + var usesTextHeightForLines: Bool { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.usesTextHeightForLines) as? Bool ?? SkeletonAppearance.default.useFontLineHeight } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.usesTextHeightForLines) } + } + + var numberOfLines: Int { + -1 + } + + var lastLineFillingPercent: Int { + get { + let defaultValue = SkeletonAppearance.default.multilineLastLineFillPercent + return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.lastLineFillingPercent) as? Int ?? defaultValue + } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.lastLineFillingPercent) } + } + + var multilineCornerRadius: Int { + get { + let defaultValue = SkeletonAppearance.default.multilineCornerRadius + return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.multilineCornerRadius) as? Int ?? defaultValue + } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.multilineCornerRadius) } + } + + var multilineSpacing: CGFloat { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.multilineSpacing) as? CGFloat ?? SkeletonAppearance.default.multilineSpacing } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.multilineSpacing) } + } + + var paddingInsets: UIEdgeInsets { + get { return ao_get(pkey: &SkeletonTextNodeAssociatedKeys.paddingInsets) as? UIEdgeInsets ?? .zero } + set { ao_set(newValue, pkey: &SkeletonTextNodeAssociatedKeys.paddingInsets) } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/SubviewsSkeletonables.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/SubviewsSkeletonables.swift new file mode 100644 index 0000000..17a8788 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonExtensions/SubviewsSkeletonables.swift @@ -0,0 +1,57 @@ +// Copyright © 2018 SkeletonView. All rights reserved. + +import UIKit + +extension UIView { + + @objc var subviewsSkeletonables: [UIView] { + subviewsToSkeleton.filter { $0.isSkeletonable } + } + + @objc var subviewsToSkeleton: [UIView] { + subviews + } + +} + +extension UITableView { + + override var subviewsToSkeleton: [UIView] { + // on `UIViewController'S onViewDidLoad`, the window is still nil. + // Some developer trying to call `view.showAnimatedSkeleton()` + // when the request or data is loading which sometimes happens before the ViewDidAppear + guard window != nil else { return [] } + return subviews + } + +} + +extension UITableViewCell { + override var subviewsToSkeleton: [UIView] { + contentView.subviews + } +} + +extension UITableViewHeaderFooterView { + override var subviewsToSkeleton: [UIView] { + contentView.subviews + } +} + +extension UICollectionView { + override var subviewsToSkeleton: [UIView] { + subviews + } +} + +extension UICollectionViewCell { + override var subviewsToSkeleton: [UIView] { + contentView.subviews + } +} + +extension UIStackView { + override var subviewsToSkeleton: [UIView] { + arrangedSubviews + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonFlowHandler.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonFlowHandler.swift new file mode 100644 index 0000000..90dc0e3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonFlowHandler.swift @@ -0,0 +1,50 @@ +// Copyright © 2018 SkeletonView. All rights reserved. + +import UIKit + +protocol SkeletonFlowDelegate: AnyObject { + func willBeginShowingSkeletons(rootView: UIView) + func didShowSkeletons(rootView: UIView) + func willBeginUpdatingSkeletons(rootView: UIView) + func didUpdateSkeletons(rootView: UIView) + func willBeginLayingSkeletonsIfNeeded(rootView: UIView) + func didLayoutSkeletonsIfNeeded(rootView: UIView) + func willBeginHidingSkeletons(rootView: UIView) + func didHideSkeletons(rootView: UIView) +} + +class SkeletonFlowHandler: SkeletonFlowDelegate { + func willBeginShowingSkeletons(rootView: UIView) { + NotificationCenter.default.post(name: .skeletonWillAppearNotification, object: rootView, userInfo: nil) + rootView.startObservingAppLifecycleNotifications() + } + + func didShowSkeletons(rootView: UIView) { + skeletonLog(rootView.sk.skeletonTreeDescription) + NotificationCenter.default.post(name: .skeletonWillAppearNotification, object: rootView, userInfo: nil) + } + + func willBeginUpdatingSkeletons(rootView: UIView) { + NotificationCenter.default.post(name: .skeletonWillAppearNotification, object: rootView, userInfo: nil) + } + + func didUpdateSkeletons(rootView: UIView) { + NotificationCenter.default.post(name: .skeletonWillAppearNotification, object: rootView, userInfo: nil) + } + + func willBeginLayingSkeletonsIfNeeded(rootView: UIView) { + } + + func didLayoutSkeletonsIfNeeded(rootView: UIView) { + } + + func willBeginHidingSkeletons(rootView: UIView) { + NotificationCenter.default.post(name: .skeletonWillDisappearNotification, object: rootView, userInfo: nil) + rootView.stopObservingAppLifecycleNotications() + } + + func didHideSkeletons(rootView: UIView) { + rootView._flowDelegate = nil + NotificationCenter.default.post(name: .skeletonDidDisappearNotification, object: rootView, userInfo: nil) + } +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonLayerBuilder.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonLayerBuilder.swift new file mode 100644 index 0000000..3c6f5ad --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonLayerBuilder.swift @@ -0,0 +1,47 @@ +// Copyright © 2018 SkeletonView. All rights reserved. + +import UIKit + +/// Object that facilitates the creation of skeleton layers, +/// based on the builder pattern +class SkeletonLayerBuilder { + + var skeletonType: SkeletonType? + var colors: [UIColor] = [] + var holder: UIView? + + @discardableResult + func setSkeletonType(_ type: SkeletonType) -> SkeletonLayerBuilder { + self.skeletonType = type + return self + } + + @discardableResult + func addColor(_ color: UIColor) -> SkeletonLayerBuilder { + addColors([color]) + } + + @discardableResult + func addColors(_ colors: [UIColor]) -> SkeletonLayerBuilder { + self.colors.append(contentsOf: colors) + return self + } + + @discardableResult + func setHolder(_ holder: UIView) -> SkeletonLayerBuilder { + self.holder = holder + return self + } + + @discardableResult + func build() -> SkeletonLayer? { + guard let type = skeletonType, + let holder = holder + else { return nil } + + return SkeletonLayer(type: type, + colors: colors, + skeletonHolder: holder) + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonMultilineLayerBuilder.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonMultilineLayerBuilder.swift new file mode 100644 index 0000000..159a152 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonLayerBuilders/SkeletonMultilineLayerBuilder.swift @@ -0,0 +1,98 @@ +// Copyright © 2018 SkeletonView. All rights reserved. + +import UIKit + +/// Object that facilitates the creation of skeleton layers for multiline +/// elements, based on the builder pattern +class SkeletonMultilineLayerBuilder { + + var skeletonType: SkeletonType? + var index: Int? + var height: CGFloat? + var width: CGFloat? + var cornerRadius: Int? + var multilineSpacing: CGFloat = SkeletonAppearance.default.multilineSpacing + var paddingInsets: UIEdgeInsets = .zero + var alignment: NSTextAlignment = .natural + var isRTL: Bool = false + + @discardableResult + func setSkeletonType(_ type: SkeletonType) -> SkeletonMultilineLayerBuilder { + self.skeletonType = type + return self + } + + @discardableResult + func setIndex(_ index: Int) -> SkeletonMultilineLayerBuilder { + self.index = index + return self + } + + @discardableResult + func setHeight(_ height: CGFloat) -> SkeletonMultilineLayerBuilder { + self.height = height + return self + } + + @discardableResult + func setWidth(_ width: CGFloat) -> SkeletonMultilineLayerBuilder { + self.width = width + return self + } + + @discardableResult + func setCornerRadius(_ radius: Int) -> SkeletonMultilineLayerBuilder { + self.cornerRadius = radius + return self + } + + @discardableResult + func setMultilineSpacing(_ spacing: CGFloat) -> SkeletonMultilineLayerBuilder { + self.multilineSpacing = spacing + return self + } + + @discardableResult + func setPadding(_ insets: UIEdgeInsets) -> SkeletonMultilineLayerBuilder { + self.paddingInsets = insets + return self + } + + @discardableResult + func setAlignment(_ alignment: NSTextAlignment) -> SkeletonMultilineLayerBuilder { + self.alignment = alignment + return self + } + + @discardableResult + func setIsRTL(_ isRTL: Bool) -> SkeletonMultilineLayerBuilder { + self.isRTL = isRTL + return self + } + + func build() -> CALayer? { + guard let type = skeletonType, + let index = index, + let width = width, + let height = height, + let radius = cornerRadius + else { return nil } + + let layer = type.layer + layer.anchorPoint = .zero + layer.name = CALayer.Constants.skeletonSubLayersName + layer.updateLayerFrame(for: index, + totalLines: layer.skeletonSublayers.count, + size: CGSize(width: width, height: height), + multilineSpacing: multilineSpacing, + paddingInsets: paddingInsets, + alignment: alignment, + isRTL: isRTL) + + layer.cornerRadius = CGFloat(radius) + layer.masksToBounds = true + + return layer + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonTree/SkeletonTreeNode.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonTree/SkeletonTreeNode.swift new file mode 100644 index 0000000..2cd9587 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/SkeletonTree/SkeletonTreeNode.swift @@ -0,0 +1,27 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// SkeletonTreeNode.swift +// +// Created by Juanpe Catalán on 23/8/21. + +import UIKit + +public struct SkeletonTreeNode { + /// Base object to extend. + let base: Base + + /// Creates extensions with base object. + /// + /// - parameter base: Base object. + init(_ base: Base) { + self.base = base + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/CALayer+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/CALayer+Extensions.swift new file mode 100644 index 0000000..aac5d35 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/CALayer+Extensions.swift @@ -0,0 +1,207 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// CALayer+Tint.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +extension CAGradientLayer { + + override func tint(withColors colors: [UIColor]) { + skeletonSublayers.recursiveSearch(leafBlock: { + self.colors = colors.map { $0.cgColor } + }) { + $0.tint(withColors: colors) + } + } + +} + +extension CALayer { + + enum Constants { + static let skeletonSubLayersName = "SkeletonSubLayersName" + } + + var skeletonSublayers: [CALayer] { + return sublayers?.filter { $0.name == Constants.skeletonSubLayersName } ?? [CALayer]() + } + + @objc func tint(withColors colors: [UIColor]) { + skeletonSublayers.recursiveSearch(leafBlock: { + backgroundColor = colors.first?.cgColor + }) { + $0.tint(withColors: colors) + } + } + + func playAnimation(_ anim: SkeletonLayerAnimation, key: String, completion: (() -> Void)? = nil) { + skeletonSublayers.recursiveSearch(leafBlock: { + DispatchQueue.main.async { CATransaction.begin() } + DispatchQueue.main.async { CATransaction.setCompletionBlock(completion) } + add(anim(self), forKey: key) + DispatchQueue.main.async { CATransaction.commit() } + }) { + $0.playAnimation(anim, key: key, completion: completion) + } + } + + func stopAnimation(forKey key: String) { + skeletonSublayers.recursiveSearch(leafBlock: { + removeAnimation(forKey: key) + }) { + $0.stopAnimation(forKey: key) + } + } + + func setOpacity(from: Int, to: Int, duration: TimeInterval, completion: (() -> Void)?) { + DispatchQueue.main.async { CATransaction.begin() } + let animation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) + animation.fromValue = from + animation.toValue = to + animation.duration = duration + animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) + DispatchQueue.main.async { CATransaction.setCompletionBlock(completion) } + add(animation, forKey: "setOpacityAnimation") + DispatchQueue.main.async { CATransaction.commit() } + } + + func insertSkeletonLayer(_ sublayer: SkeletonLayer, atIndex index: UInt32, transition: SkeletonTransitionStyle, completion: (() -> Void)? = nil) { + insertSublayer(sublayer.contentLayer, at: index) + switch transition { + case .none: + completion?() + case .crossDissolve(let duration): + sublayer.contentLayer.setOpacity(from: 0, to: 1, duration: duration, completion: completion) + } + } + +} + +private extension CALayer { + + func alignLayerFrame(_ rect: CGRect, alignment: NSTextAlignment, isRTL: Bool) -> CGRect { + var newRect = rect + + switch alignment { + case .natural where isRTL, + .right: + newRect.origin.x = (superlayer?.bounds.width ?? 0) - rect.origin.x - rect.width + case .center: + newRect.origin.x = rect.origin.x + ((superlayer?.bounds.width ?? 0) - rect.width) / 2 + case .natural, .left, .justified: + break + @unknown default: + break + } + + return newRect + } + + func calculatedWidthForLine(at index: Int, totalLines: Int, lastLineFillPercent: Int, paddingInsets: UIEdgeInsets) -> CGFloat { + var width = bounds.width - paddingInsets.left - paddingInsets.right + if index == totalLines - 1 { + width = width * CGFloat(lastLineFillPercent) / 100 + } + return width + } + + func calculateNumLines(for config: SkeletonMultilinesLayerConfig) -> Int { + let definedNumberOfLines = config.lines + let requiredSpaceForEachLine = config.lineHeight + config.multilineSpacing + let neededLines = round(CGFloat(bounds.height - config.paddingInsets.top - config.paddingInsets.bottom) / CGFloat(requiredSpaceForEachLine)) + guard neededLines.isNormal else { + return 0 + } + + let calculatedNumberOfLines = Int(neededLines) + guard calculatedNumberOfLines > 0 else { + return 1 + } + + if definedNumberOfLines > 0, definedNumberOfLines <= calculatedNumberOfLines { + return definedNumberOfLines + } + + return calculatedNumberOfLines + } +} + +extension CALayer { + + func addMultilinesLayers(for config: SkeletonMultilinesLayerConfig) { + let numberOfSublayers = config.lines > 0 ? config.lines : calculateNumLines(for: config) + var height = config.lineHeight + + if numberOfSublayers == 1 && SkeletonAppearance.default.renderSingleLineAsView { + height = bounds.height + } + + let layerBuilder = SkeletonMultilineLayerBuilder() + .setSkeletonType(config.type) + .setCornerRadius(config.multilineCornerRadius) + .setMultilineSpacing(config.multilineSpacing) + .setPadding(config.paddingInsets) + .setHeight(height) + .setAlignment(config.alignment) + .setIsRTL(config.isRTL) + + (0..] { + base.subviewsSkeletonables.map { $0.sk.treeNode } + } + + var parent: SkeletonTreeNode? { + base.superview?.sk.treeNode + } + +} + +// MARK: Debug + +extension SkeletonTreeNode where Base: UIView { + + var dictionaryRepresentation: [String: Any] { + let skeletonableChildren = children + + var nodeInfo: [String: Any] = [ + "type": "\(type(of: base))", + "reference": "\(Unmanaged.passUnretained(base).toOpaque())", + "isSkeletonable": base.isSkeletonable + ] + + if !skeletonableChildren.isEmpty { + nodeInfo["children"] = skeletonableChildren.map { $0.dictionaryRepresentation } + } + + return nodeInfo + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UICollectionView+CollectionSkeleton.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UICollectionView+CollectionSkeleton.swift new file mode 100644 index 0000000..c5c9451 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UICollectionView+CollectionSkeleton.swift @@ -0,0 +1,66 @@ +// +// UICollectionView+CollectionSkeleton.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 02/02/2018. +// Copyright © 2018 SkeletonView. All rights reserved. +// + +import UIKit + +extension UICollectionView: CollectionSkeleton { + + var estimatedNumberOfRows: Int { + guard let flowlayout = collectionViewLayout as? UICollectionViewFlowLayout else { return 0 } + switch flowlayout.scrollDirection { + case .vertical: + return Int(ceil(frame.height / flowlayout.itemSize.height)) + case .horizontal: + return Int(ceil(frame.width / flowlayout.itemSize.width)) + default: + return 0 + } + } + + var skeletonDataSource: SkeletonCollectionDataSource? { + get { return ao_get(pkey: &CollectionAssociatedKeys.dummyDataSource) as? SkeletonCollectionDataSource } + set { + ao_setOptional(newValue, pkey: &CollectionAssociatedKeys.dummyDataSource) + self.dataSource = newValue + } + } + + var skeletonDelegate: SkeletonCollectionDelegate? { + get { return ao_get(pkey: &CollectionAssociatedKeys.dummyDelegate) as? SkeletonCollectionDelegate } + set { + ao_setOptional(newValue, pkey: &CollectionAssociatedKeys.dummyDelegate) + self.delegate = newValue + } + } + + func addDummyDataSource() { + guard let originalDataSource = self.dataSource as? SkeletonCollectionViewDataSource, + !(originalDataSource is SkeletonCollectionDataSource) + else { return } + + let dataSource = SkeletonCollectionDataSource(collectionViewDataSource: originalDataSource) + self.skeletonDataSource = dataSource + reloadData() + } + + func updateDummyDataSource() { + if (dataSource as? SkeletonCollectionDataSource) != nil { + reloadData() + } else { + addDummyDataSource() + } + } + + func removeDummyDataSource(reloadAfter: Bool) { + guard let dataSource = self.dataSource as? SkeletonCollectionDataSource else { return } + self.skeletonDataSource = nil + self.dataSource = dataSource.originalCollectionViewDataSource + if reloadAfter { self.reloadData() } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIColor+Skeleton.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIColor+Skeleton.swift new file mode 100644 index 0000000..a219dc6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIColor+Skeleton.swift @@ -0,0 +1,88 @@ +// Copyright © 2017 SkeletonView. All rights reserved. + +import UIKit + +// codebeat:disable[TOO_MANY_IVARS] +public extension UIColor { + + static var greenSea = UIColor(0x16a085) + static var turquoise = UIColor(0x1abc9c) + static var emerald = UIColor(0x2ecc71) + static var peterRiver = UIColor(0x3498db) + static var amethyst = UIColor(0x9b59b6) + static var wetAsphalt = UIColor(0x34495e) + static var nephritis = UIColor(0x27ae60) + static var belizeHole = UIColor(0x2980b9) + static var wisteria = UIColor(0x8e44ad) + static var midnightBlue = UIColor(0x2c3e50) + static var sunFlower = UIColor(0xf1c40f) + static var carrot = UIColor(0xe67e22) + static var alizarin = UIColor(0xe74c3c) + static var clouds = UIColor(0xecf0f1) + static var darkClouds = UIColor(0x1c2325) + static var concrete = UIColor(0x95a5a6) + static var flatOrange = UIColor(0xf39c12) + static var pumpkin = UIColor(0xd35400) + static var pomegranate = UIColor(0xc0392b) + static var silver = UIColor(0xbdc3c7) + static var asbestos = UIColor(0x7f8c8d) + + static var skeletonDefault: UIColor { + if #available(iOS 13, tvOS 13, *) { + return UIColor { traitCollection in + switch traitCollection.userInterfaceStyle { + case .dark: + return .darkClouds + default: + return .clouds + } + } + } else { + return .clouds + } + } + + var complementaryColor: UIColor { + isLight ? darker : lighter + } + + var lighter: UIColor { + adjust(by: 1.35) + } + + var darker: UIColor { + adjust(by: 0.94) + } + +} + +extension UIColor { + + convenience init(_ hex: UInt) { + self.init( + red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, + green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, + blue: CGFloat(hex & 0x0000FF) / 255.0, + alpha: CGFloat(1.0) + ) + } + + var isLight: Bool { + guard let components = cgColor.components, + components.count >= 3 else { return false } + let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000 + return !(brightness < 0.5) + } + + func adjust(by percent: CGFloat) -> UIColor { + var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 + getHue(&h, saturation: &s, brightness: &b, alpha: &a) + return UIColor(hue: h, saturation: s, brightness: b * percent, alpha: a) + } + + func makeGradient() -> [UIColor] { + [self, self.complementaryColor, self] + } + +} +// codebeat:enable[TOO_MANY_IVARS] diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UILabel+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UILabel+Extensions.swift new file mode 100644 index 0000000..f3c348a --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UILabel+Extensions.swift @@ -0,0 +1,49 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UILabel+Extensions.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +extension UILabel { + + var desiredHeightBasedOnNumberOfLines: CGFloat { + let spaceNeededForEachLine = lineHeight * CGFloat(numberOfLines) + let spaceNeededForSpaces = skeletonLineSpacing * CGFloat(numberOfLines - 1) + let padding = paddingInsets.top + paddingInsets.bottom + + return spaceNeededForEachLine + spaceNeededForSpaces + padding + } + + func updateHeightConstraintsIfNeeded() { + guard numberOfLines > 1 || numberOfLines == 0 else { return } + + // Workaround to simulate content when the label is contained in a `UIStackView`. + if isSuperviewAStackView, bounds.height == 0 { + // This is a placeholder text to simulate content because it's contained in a stack view in order to prevent that the content size will be zero. + text = " " + } + + let desiredHeight = desiredHeightBasedOnNumberOfLines + if desiredHeight > definedMaxHeight { + backupHeightConstraints = heightConstraints + NSLayoutConstraint.deactivate(heightConstraints) + setHeight(equalToConstant: desiredHeight) + } + } + + func restoreBackupHeightConstraintsIfNeeded() { + guard !backupHeightConstraints.isEmpty else { return } + NSLayoutConstraint.activate(backupHeightConstraints) + backupHeightConstraints.removeAll() + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+CollectionSkeleton.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+CollectionSkeleton.swift new file mode 100644 index 0000000..132041e --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+CollectionSkeleton.swift @@ -0,0 +1,89 @@ +// +// UITableView+CollectionSkeleton.swift +// SkeletonView-iOS +// +// Created by Juanpe Catalán on 02/02/2018. +// Copyright © 2018 SkeletonView. All rights reserved. +// + +import UIKit + +extension UITableView: CollectionSkeleton { + + var estimatedNumberOfRows: Int { + return Int(ceil(frame.height / rowHeight)) + } + + var skeletonDataSource: SkeletonCollectionDataSource? { + get { return ao_get(pkey: &CollectionAssociatedKeys.dummyDataSource) as? SkeletonCollectionDataSource } + set { + ao_setOptional(newValue, pkey: &CollectionAssociatedKeys.dummyDataSource) + self.dataSource = newValue + } + } + + var skeletonDelegate: SkeletonCollectionDelegate? { + get { return ao_get(pkey: &CollectionAssociatedKeys.dummyDelegate) as? SkeletonCollectionDelegate } + set { + ao_setOptional(newValue, pkey: &CollectionAssociatedKeys.dummyDelegate) + self.delegate = newValue + } + } + + func addDummyDataSource() { + guard let originalDataSource = self.dataSource as? SkeletonTableViewDataSource, + !(originalDataSource is SkeletonCollectionDataSource) + else { return } + let calculatedRowHeight = calculateRowHeight() + let dataSource = SkeletonCollectionDataSource(tableViewDataSource: originalDataSource, + rowHeight: rowHeight, + originalRowHeight: self.rowHeight) + rowHeight = calculatedRowHeight + self.skeletonDataSource = dataSource + + if let originalDelegate = self.delegate as? SkeletonTableViewDelegate, + !(originalDelegate is SkeletonCollectionDelegate) { + let delegate = SkeletonCollectionDelegate(tableViewDelegate: originalDelegate) + self.skeletonDelegate = delegate + } + + reloadData() + } + + func updateDummyDataSource() { + if (dataSource as? SkeletonCollectionDataSource) != nil { + reloadData() + } else { + addDummyDataSource() + } + } + + func removeDummyDataSource(reloadAfter: Bool) { + guard let dataSource = self.dataSource as? SkeletonCollectionDataSource else { return } + restoreRowHeight() + self.skeletonDataSource = nil + self.dataSource = dataSource.originalTableViewDataSource + + if let delegate = self.delegate as? SkeletonCollectionDelegate { + self.skeletonDelegate = nil + self.delegate = delegate.originalTableViewDelegate + } + + if reloadAfter { self.reloadData() } + } + +} + +private extension UITableView { + + func restoreRowHeight() { + guard let dataSource = self.dataSource as? SkeletonCollectionDataSource else { return } + rowHeight = dataSource.originalRowHeight + } + + func calculateRowHeight() -> CGFloat { + guard rowHeight == UITableView.automaticDimension else { return rowHeight } + return estimatedRowHeight + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+Extensions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+Extensions.swift new file mode 100644 index 0000000..372222f --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UITableView+Extensions.swift @@ -0,0 +1,45 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UITableView+Extensions.swift +// +// Created by Juanpe Catalán on 18/8/21. + +import UIKit + +extension UITableView { + + var indexesOfVisibleSections: [Int] { + (0.. { + SkeletonTreeNode(self.type) + } + +} + +extension UIView { + + /// Flags + + var isSuperviewAStackView: Bool { + superview is UIStackView + } + + var isRTL: Bool { + if #available(iOS 10.0, *), #available(tvOS 10.0, *) { + return effectiveUserInterfaceLayoutDirection == .rightToLeft + } else { + return false + } + } + + /// Math + + var definedMaxBounds: CGRect { + if let parentStackView = (superview as? UIStackView) { + var origin: CGPoint = .zero + switch parentStackView.alignment { + case .trailing: + origin.x = definedMaxWidth + default: + break + } + return CGRect(origin: origin, size: definedMaxSize) + } + return CGRect(origin: .zero, size: definedMaxSize) + } + + var definedMaxSize: CGSize { + CGSize(width: definedMaxWidth, height: definedMaxHeight) + } + + var definedMaxWidth: CGFloat { + let constraintsMaxWidth = widthConstraints + .map { $0.constant } + .max() ?? 0 + + return max(frame.size.width, constraintsMaxWidth) + } + + var definedMaxHeight: CGFloat { + let constraintsMaxHeight = heightConstraints + .map { $0.constant } + .max() ?? 0 + + return max(frame.size.height, constraintsMaxHeight) + } + + /// Autolayout + + var widthConstraints: [NSLayoutConstraint] { + nonContentSizeLayoutConstraints.filter { $0.firstAttribute == NSLayoutConstraint.Attribute.width } + } + + var heightConstraints: [NSLayoutConstraint] { + nonContentSizeLayoutConstraints.filter { $0.firstAttribute == NSLayoutConstraint.Attribute.height } + } + + var skeletonHeightConstraints: [NSLayoutConstraint] { + nonContentSizeLayoutConstraints.filter { + $0.firstAttribute == NSLayoutConstraint.Attribute.height + && $0.identifier?.contains("SkeletonView.Constraint.Height") ?? false + } + } + + @discardableResult + func setHeight(equalToConstant constant: CGFloat) -> NSLayoutConstraint { + let heightConstraint = heightAnchor.constraint(equalToConstant: constant) + heightConstraint.identifier = "SkeletonView.Constraint.Height.\(constant)" + NSLayoutConstraint.activate([heightConstraint]) + return heightConstraint + } + + var nonContentSizeLayoutConstraints: [NSLayoutConstraint] { + constraints.filter({ "\(type(of: $0))" != "NSContentSizeLayoutConstraint" }) + } + + /// Animations + + func startSkeletonLayerAnimationBlock(_ anim: SkeletonLayerAnimation? = nil) -> VoidBlock { + { + self._isSkeletonAnimated = true + guard let layer = self._skeletonLayer else { return } + layer.start(anim) { [weak self] in + self?._isSkeletonAnimated = false + } + } + } + + var stopSkeletonLayerAnimationBlock: VoidBlock { + { + self._isSkeletonAnimated = false + guard let layer = self._skeletonLayer else { return } + layer.stopAnimation() + } + } + + /// Skeleton Layer + + func addSkeletonLayer(skeletonConfig config: SkeletonConfig) { + guard let skeletonLayer = SkeletonLayerBuilder() + .setSkeletonType(config.type) + .addColors(config.colors) + .setHolder(self) + .build() + else { return } + + self._skeletonLayer = skeletonLayer + layer.insertSkeletonLayer( + skeletonLayer, + atIndex: UInt32.max, + transition: config.transition + ) { [weak self] in + guard let self = self else { return } + + // Workaround to fix the problem when inserting a sublayer and + // the content offset is modified by the system. + (self as? UITextView)?.setContentOffset(.zero, animated: false) + + if config.animated { + self.startSkeletonAnimation(config.animation) + } + } + _status = .on + } + + func updateSkeletonLayer(skeletonConfig config: SkeletonConfig) { + guard let skeletonLayer = _skeletonLayer else { return } + skeletonLayer.update(usingColors: config.colors) + if config.animated { + startSkeletonAnimation(config.animation) + } else { + skeletonLayer.stopAnimation() + } + } + + func layoutSkeletonLayerIfNeeded() { + guard let skeletonLayer = _skeletonLayer else { return } + skeletonLayer.layoutIfNeeded() + } + + func removeSkeletonLayer() { + guard sk.isSkeletonActive, + let skeletonLayer = _skeletonLayer, + let transitionStyle = _currentSkeletonConfig?.transition else { return } + skeletonLayer.stopAnimation() + _status = .off + skeletonLayer.removeLayer(transition: transitionStyle) { + self._skeletonLayer = nil + self._currentSkeletonConfig = nil + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+SkeletonView.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+SkeletonView.swift new file mode 100644 index 0000000..df6bc33 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+SkeletonView.swift @@ -0,0 +1,121 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UIView+SkeletonView.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +extension UIView { + + func showSkeleton(skeletonConfig config: SkeletonConfig) { + _isSkeletonAnimated = config.animated + _flowDelegate = SkeletonFlowHandler() + _flowDelegate?.willBeginShowingSkeletons(rootView: self) + recursiveShowSkeleton(skeletonConfig: config, root: self) + } + + func updateSkeleton(skeletonConfig config: SkeletonConfig) { + _isSkeletonAnimated = config.animated + _flowDelegate?.willBeginUpdatingSkeletons(rootView: self) + recursiveUpdateSkeleton(skeletonConfig: config, root: self) + } + + func recursiveLayoutSkeletonIfNeeded(root: UIView? = nil) { + subviewsSkeletonables.recursiveSearch(leafBlock: { + guard isSkeletonable, sk.isSkeletonActive else { return } + layoutSkeletonLayerIfNeeded() + if let config = _currentSkeletonConfig, config.animated, !_isSkeletonAnimated { + startSkeletonAnimation(config.animation) + } + }) { subview in + subview.recursiveLayoutSkeletonIfNeeded() + } + + if let root = root { + _flowDelegate?.didLayoutSkeletonsIfNeeded(rootView: root) + } + } + + func recursiveHideSkeleton(reloadDataAfter reload: Bool, transition: SkeletonTransitionStyle, root: UIView? = nil) { + guard sk.isSkeletonActive else { return } + if isHiddenWhenSkeletonIsActive { + isHidden = false + } + _currentSkeletonConfig?.transition = transition + unSwizzleLayoutSubviews() + unSwizzleTraitCollectionDidChange() + removeDummyDataSourceIfNeeded(reloadAfter: reload) + subviewsSkeletonables.recursiveSearch(leafBlock: { + recoverViewState(forced: false) + removeSkeletonLayer() + }) { subview in + subview.recursiveHideSkeleton(reloadDataAfter: reload, transition: transition) + } + + if let root = root { + _flowDelegate?.didHideSkeletons(rootView: root) + } + } + +} + +private extension UIView { + + func showSkeletonIfNotActive(skeletonConfig config: SkeletonConfig) { + guard !sk.isSkeletonActive else { return } + saveViewState() + + prepareViewForSkeleton() + addSkeletonLayer(skeletonConfig: config) + } + + func recursiveShowSkeleton(skeletonConfig config: SkeletonConfig, root: UIView? = nil) { + if isHiddenWhenSkeletonIsActive { + isHidden = true + } + guard isSkeletonable && !sk.isSkeletonActive else { return } + _currentSkeletonConfig = config + swizzleLayoutSubviews() + swizzleTraitCollectionDidChange() + addDummyDataSourceIfNeeded() + subviewsSkeletonables.recursiveSearch(leafBlock: { + showSkeletonIfNotActive(skeletonConfig: config) + }) { subview in + subview.recursiveShowSkeleton(skeletonConfig: config) + } + + if let root = root { + _flowDelegate?.didShowSkeletons(rootView: root) + } + } + + func recursiveUpdateSkeleton(skeletonConfig config: SkeletonConfig, root: UIView? = nil) { + guard sk.isSkeletonActive else { return } + _currentSkeletonConfig = config + updateDummyDataSourceIfNeeded() + subviewsSkeletonables.recursiveSearch(leafBlock: { + if let skeletonLayer = _skeletonLayer, + skeletonLayer.type != config.type { + removeSkeletonLayer() + addSkeletonLayer(skeletonConfig: config) + } else { + updateSkeletonLayer(skeletonConfig: config) + } + }) { subview in + subview.recursiveUpdateSkeleton(skeletonConfig: config) + } + + if let root = root { + _flowDelegate?.didUpdateSkeletons(rootView: root) + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Swizzling.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Swizzling.swift new file mode 100644 index 0000000..3c25716 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Swizzling.swift @@ -0,0 +1,76 @@ +// +// Copyright SkeletonView. All Rights Reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// UIView+Swizzling.swift +// +// Created by Juanpe Catalán on 19/8/21. + +import UIKit + +extension UIView { + + @objc func skeletonLayoutSubviews() { + guard Thread.isMainThread else { return } + skeletonLayoutSubviews() + guard sk.isSkeletonActive else { return } + layoutSkeletonIfNeeded() + } + + @objc func skeletonTraitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { + skeletonTraitCollectionDidChange(previousTraitCollection) + guard isSkeletonable, sk.isSkeletonActive, let config = _currentSkeletonConfig else { return } + updateSkeleton(skeletonConfig: config) + } + + func swizzleLayoutSubviews() { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { + DispatchQueue.once(token: "UIView.SkeletonView.swizzleLayoutSubviews") { + swizzle(selector: #selector(UIView.layoutSubviews), + with: #selector(UIView.skeletonLayoutSubviews), + inClass: UIView.self, + usingClass: UIView.self) + self.layoutSkeletonIfNeeded() + } + } + } + + func unSwizzleLayoutSubviews() { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { + DispatchQueue.removeOnce(token: "UIView.SkeletonView.swizzleLayoutSubviews") { + swizzle(selector: #selector(UIView.skeletonLayoutSubviews), + with: #selector(UIView.layoutSubviews), + inClass: UIView.self, + usingClass: UIView.self) + } + } + } + + func swizzleTraitCollectionDidChange() { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { + DispatchQueue.once(token: "UIView.SkeletonView.swizzleTraitCollectionDidChange") { + swizzle(selector: #selector(UIView.traitCollectionDidChange(_:)), + with: #selector(UIView.skeletonTraitCollectionDidChange(_:)), + inClass: UIView.self, + usingClass: UIView.self) + } + } + } + + func unSwizzleTraitCollectionDidChange() { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { + DispatchQueue.removeOnce(token: "UIView.SkeletonView.swizzleTraitCollectionDidChange") { + swizzle(selector: #selector(UIView.skeletonTraitCollectionDidChange(_:)), + with: #selector(UIView.traitCollectionDidChange(_:)), + inClass: UIView.self, + usingClass: UIView.self) + } + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Transitions.swift b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Transitions.swift new file mode 100644 index 0000000..66b3a61 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SkeletonView/SkeletonViewCore/Sources/Internal/UIKitExtensions/UIView+Transitions.swift @@ -0,0 +1,23 @@ +// Copyright © 2019 SkeletonView. All rights reserved. + +import UIKit + +extension UIView { + + func startTransition(transitionBlock: @escaping () -> Void) { + guard let transitionStyle = _currentSkeletonConfig?.transition, + transitionStyle != .none else { + transitionBlock() + return + } + + if case let .crossDissolve(duration) = transitionStyle { + UIView.transition(with: self, + duration: duration, + options: .transitionCrossDissolve, + animations: transitionBlock, + completion: nil) + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/LICENSE b/sopt_29th_Assignment/Pods/SnapKit/LICENSE new file mode 100644 index 0000000..a18ccfb --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/sopt_29th_Assignment/Pods/SnapKit/README.md b/sopt_29th_Assignment/Pods/SnapKit/README.md new file mode 100644 index 0000000..0945ce6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/README.md @@ -0,0 +1,136 @@ + + +SnapKit is a DSL to make Auto Layout easy on both iOS and OS X. + +[![Build Status](https://travis-ci.org/SnapKit/SnapKit.svg)](https://travis-ci.org/SnapKit/SnapKit) +[![Platform](https://img.shields.io/cocoapods/p/SnapKit.svg?style=flat)](https://github.com/SnapKit/SnapKit) +[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/SnapKit.svg)](https://cocoapods.org/pods/SnapKit) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +#### ⚠️ **To use with Swift 4.x please ensure you are using >= 4.0.0** ⚠️ +#### ⚠️ **To use with Swift 5.x please ensure you are using >= 5.0.0** ⚠️ + +## Contents + +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](#usage) +- [Credits](#credits) +- [License](#license) + +## Requirements + +- iOS 10.0+ / Mac OS X 10.12+ / tvOS 10.0+ +- Xcode 10.0+ +- Swift 4.0+ + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/snapkit). (Tag 'snapkit') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/snapkit). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1.0+ is required to build SnapKit 4.0.0+. + +To integrate SnapKit into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'SnapKit', '~> 5.0.0' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate SnapKit into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "SnapKit/SnapKit" ~> 5.0.0 +``` + +Run `carthage update` to build the framework and drag the built `SnapKit.framework` into your Xcode project. + +### Manually + +If you prefer not to use either of the aforementioned dependency managers, you can integrate SnapKit into your project manually. + +--- + +## Usage + +### Quick Start + +```swift +import SnapKit + +class MyViewController: UIViewController { + + lazy var box = UIView() + + override func viewDidLoad() { + super.viewDidLoad() + + self.view.addSubview(box) + box.snp.makeConstraints { (make) -> Void in + make.width.height.equalTo(50) + make.center.equalTo(self.view) + } + } + +} +``` + +### Playground +You can try SnapKit in Playground. + +**Note:** + +> To try SnapKit in playground, open `SnapKit.xcworkspace` and build SnapKit.framework for any simulator first. + +### Resources + +- [Documentation](http://snapkit.io/docs/) +- [F.A.Q.](http://snapkit.io/faq/) + +## Credits + +- Robert Payne ([@robertjpayne](https://twitter.com/robertjpayne)) +- Many other contributors + +## License + +SnapKit is released under the MIT license. See LICENSE for details. diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/Constraint.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/Constraint.swift new file mode 100644 index 0000000..390629e --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/Constraint.swift @@ -0,0 +1,341 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + +public final class Constraint { + + internal let sourceLocation: (String, UInt) + internal let label: String? + + private let from: ConstraintItem + private let to: ConstraintItem + private let relation: ConstraintRelation + private let multiplier: ConstraintMultiplierTarget + private var constant: ConstraintConstantTarget { + didSet { + self.updateConstantAndPriorityIfNeeded() + } + } + private var priority: ConstraintPriorityTarget { + didSet { + self.updateConstantAndPriorityIfNeeded() + } + } + public var layoutConstraints: [LayoutConstraint] + + public var isActive: Bool { + set { + if newValue { + activate() + } + else { + deactivate() + } + } + + get { + for layoutConstraint in self.layoutConstraints { + if layoutConstraint.isActive { + return true + } + } + return false + } + } + + // MARK: Initialization + + internal init(from: ConstraintItem, + to: ConstraintItem, + relation: ConstraintRelation, + sourceLocation: (String, UInt), + label: String?, + multiplier: ConstraintMultiplierTarget, + constant: ConstraintConstantTarget, + priority: ConstraintPriorityTarget) { + self.from = from + self.to = to + self.relation = relation + self.sourceLocation = sourceLocation + self.label = label + self.multiplier = multiplier + self.constant = constant + self.priority = priority + self.layoutConstraints = [] + + // get attributes + let layoutFromAttributes = self.from.attributes.layoutAttributes + let layoutToAttributes = self.to.attributes.layoutAttributes + + // get layout from + let layoutFrom = self.from.layoutConstraintItem! + + // get relation + let layoutRelation = self.relation.layoutRelation + + for layoutFromAttribute in layoutFromAttributes { + // get layout to attribute + let layoutToAttribute: LayoutAttribute + #if os(iOS) || os(tvOS) + if layoutToAttributes.count > 0 { + if self.from.attributes == .edges && self.to.attributes == .margins { + switch layoutFromAttribute { + case .left: + layoutToAttribute = .leftMargin + case .right: + layoutToAttribute = .rightMargin + case .top: + layoutToAttribute = .topMargin + case .bottom: + layoutToAttribute = .bottomMargin + default: + fatalError() + } + } else if self.from.attributes == .margins && self.to.attributes == .edges { + switch layoutFromAttribute { + case .leftMargin: + layoutToAttribute = .left + case .rightMargin: + layoutToAttribute = .right + case .topMargin: + layoutToAttribute = .top + case .bottomMargin: + layoutToAttribute = .bottom + default: + fatalError() + } + } else if self.from.attributes == .directionalEdges && self.to.attributes == .directionalMargins { + switch layoutFromAttribute { + case .leading: + layoutToAttribute = .leadingMargin + case .trailing: + layoutToAttribute = .trailingMargin + case .top: + layoutToAttribute = .topMargin + case .bottom: + layoutToAttribute = .bottomMargin + default: + fatalError() + } + } else if self.from.attributes == .directionalMargins && self.to.attributes == .directionalEdges { + switch layoutFromAttribute { + case .leadingMargin: + layoutToAttribute = .leading + case .trailingMargin: + layoutToAttribute = .trailing + case .topMargin: + layoutToAttribute = .top + case .bottomMargin: + layoutToAttribute = .bottom + default: + fatalError() + } + } else if self.from.attributes == self.to.attributes { + layoutToAttribute = layoutFromAttribute + } else { + layoutToAttribute = layoutToAttributes[0] + } + } else { + if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) { + layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top + } else { + layoutToAttribute = layoutFromAttribute + } + } + #else + if self.from.attributes == self.to.attributes { + layoutToAttribute = layoutFromAttribute + } else if layoutToAttributes.count > 0 { + layoutToAttribute = layoutToAttributes[0] + } else { + layoutToAttribute = layoutFromAttribute + } + #endif + + // get layout constant + let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) + + // get layout to + var layoutTo: AnyObject? = self.to.target + + // use superview if possible + if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { + layoutTo = layoutFrom.superview + } + + // create layout constraint + let layoutConstraint = LayoutConstraint( + item: layoutFrom, + attribute: layoutFromAttribute, + relatedBy: layoutRelation, + toItem: layoutTo, + attribute: layoutToAttribute, + multiplier: self.multiplier.constraintMultiplierTargetValue, + constant: layoutConstant + ) + + // set label + layoutConstraint.label = self.label + + // set priority + layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) + + // set constraint + layoutConstraint.constraint = self + + // append + self.layoutConstraints.append(layoutConstraint) + } + } + + // MARK: Public + + @available(*, deprecated, message:"Use activate().") + public func install() { + self.activate() + } + + @available(*, deprecated, message:"Use deactivate().") + public func uninstall() { + self.deactivate() + } + + public func activate() { + self.activateIfNeeded() + } + + public func deactivate() { + self.deactivateIfNeeded() + } + + @discardableResult + public func update(offset: ConstraintOffsetTarget) -> Constraint { + self.constant = offset.constraintOffsetTargetValue + return self + } + + @discardableResult + public func update(inset: ConstraintInsetTarget) -> Constraint { + self.constant = inset.constraintInsetTargetValue + return self + } + + #if os(iOS) || os(tvOS) + @discardableResult + @available(iOS 11.0, tvOS 11.0, *) + public func update(inset: ConstraintDirectionalInsetTarget) -> Constraint { + self.constant = inset.constraintDirectionalInsetTargetValue + return self + } + #endif + + @discardableResult + public func update(priority: ConstraintPriorityTarget) -> Constraint { + self.priority = priority.constraintPriorityTargetValue + return self + } + + @discardableResult + public func update(priority: ConstraintPriority) -> Constraint { + self.priority = priority.value + return self + } + + @available(*, deprecated, message:"Use update(offset: ConstraintOffsetTarget) instead.") + public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) } + + @available(*, deprecated, message:"Use update(inset: ConstraintInsetTarget) instead.") + public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) } + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") + public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) } + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") + public func updatePriorityRequired() -> Void {} + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") + public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") + public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") + public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } + + // MARK: Internal + + internal func updateConstantAndPriorityIfNeeded() { + for layoutConstraint in self.layoutConstraints { + let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute + layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) + + let requiredPriority = ConstraintPriority.required.value + if (layoutConstraint.priority.rawValue < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) { + layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) + } + } + } + + internal func activateIfNeeded(updatingExisting: Bool = false) { + guard let item = self.from.layoutConstraintItem else { + print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.") + return + } + let layoutConstraints = self.layoutConstraints + + if updatingExisting { + var existingLayoutConstraints: [LayoutConstraint] = [] + for constraint in item.constraints { + existingLayoutConstraints += constraint.layoutConstraints + } + + for layoutConstraint in layoutConstraints { + let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } + guard let updateLayoutConstraint = existingLayoutConstraint else { + fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") + } + + let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute + updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) + } + } else { + NSLayoutConstraint.activate(layoutConstraints) + item.add(constraints: [self]) + } + } + + internal func deactivateIfNeeded() { + guard let item = self.from.layoutConstraintItem else { + print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.") + return + } + let layoutConstraints = self.layoutConstraints + NSLayoutConstraint.deactivate(layoutConstraints) + item.remove(constraints: [self]) + } +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintAttributes.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintAttributes.swift new file mode 100644 index 0000000..2f0fbe9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintAttributes.swift @@ -0,0 +1,199 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +internal struct ConstraintAttributes : OptionSet, ExpressibleByIntegerLiteral { + + typealias IntegerLiteralType = UInt + + internal init(rawValue: UInt) { + self.rawValue = rawValue + } + internal init(_ rawValue: UInt) { + self.init(rawValue: rawValue) + } + internal init(nilLiteral: ()) { + self.rawValue = 0 + } + internal init(integerLiteral rawValue: IntegerLiteralType) { + self.init(rawValue: rawValue) + } + + internal private(set) var rawValue: UInt + internal static var allZeros: ConstraintAttributes { return 0 } + internal static func convertFromNilLiteral() -> ConstraintAttributes { return 0 } + internal var boolValue: Bool { return self.rawValue != 0 } + + internal func toRaw() -> UInt { return self.rawValue } + internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) } + internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) } + + // normal + + internal static var none: ConstraintAttributes { return 0 } + internal static var left: ConstraintAttributes { return 1 } + internal static var top: ConstraintAttributes { return 2 } + internal static var right: ConstraintAttributes { return 4 } + internal static var bottom: ConstraintAttributes { return 8 } + internal static var leading: ConstraintAttributes { return 16 } + internal static var trailing: ConstraintAttributes { return 32 } + internal static var width: ConstraintAttributes { return 64 } + internal static var height: ConstraintAttributes { return 128 } + internal static var centerX: ConstraintAttributes { return 256 } + internal static var centerY: ConstraintAttributes { return 512 } + internal static var lastBaseline: ConstraintAttributes { return 1024 } + + @available(iOS 8.0, OSX 10.11, *) + internal static var firstBaseline: ConstraintAttributes { return 2048 } + + @available(iOS 8.0, *) + internal static var leftMargin: ConstraintAttributes { return 4096 } + + @available(iOS 8.0, *) + internal static var rightMargin: ConstraintAttributes { return 8192 } + + @available(iOS 8.0, *) + internal static var topMargin: ConstraintAttributes { return 16384 } + + @available(iOS 8.0, *) + internal static var bottomMargin: ConstraintAttributes { return 32768 } + + @available(iOS 8.0, *) + internal static var leadingMargin: ConstraintAttributes { return 65536 } + + @available(iOS 8.0, *) + internal static var trailingMargin: ConstraintAttributes { return 131072 } + + @available(iOS 8.0, *) + internal static var centerXWithinMargins: ConstraintAttributes { return 262144 } + + @available(iOS 8.0, *) + internal static var centerYWithinMargins: ConstraintAttributes { return 524288 } + + // aggregates + + internal static var edges: ConstraintAttributes { return 15 } + internal static var directionalEdges: ConstraintAttributes { return 58 } + internal static var size: ConstraintAttributes { return 192 } + internal static var center: ConstraintAttributes { return 768 } + + @available(iOS 8.0, *) + internal static var margins: ConstraintAttributes { return 61440 } + + @available(iOS 8.0, *) + internal static var directionalMargins: ConstraintAttributes { return 245760 } + + @available(iOS 8.0, *) + internal static var centerWithinMargins: ConstraintAttributes { return 786432 } + + internal var layoutAttributes:[LayoutAttribute] { + var attrs = [LayoutAttribute]() + if (self.contains(ConstraintAttributes.left)) { + attrs.append(.left) + } + if (self.contains(ConstraintAttributes.top)) { + attrs.append(.top) + } + if (self.contains(ConstraintAttributes.right)) { + attrs.append(.right) + } + if (self.contains(ConstraintAttributes.bottom)) { + attrs.append(.bottom) + } + if (self.contains(ConstraintAttributes.leading)) { + attrs.append(.leading) + } + if (self.contains(ConstraintAttributes.trailing)) { + attrs.append(.trailing) + } + if (self.contains(ConstraintAttributes.width)) { + attrs.append(.width) + } + if (self.contains(ConstraintAttributes.height)) { + attrs.append(.height) + } + if (self.contains(ConstraintAttributes.centerX)) { + attrs.append(.centerX) + } + if (self.contains(ConstraintAttributes.centerY)) { + attrs.append(.centerY) + } + if (self.contains(ConstraintAttributes.lastBaseline)) { + attrs.append(.lastBaseline) + } + + #if os(iOS) || os(tvOS) + if (self.contains(ConstraintAttributes.firstBaseline)) { + attrs.append(.firstBaseline) + } + if (self.contains(ConstraintAttributes.leftMargin)) { + attrs.append(.leftMargin) + } + if (self.contains(ConstraintAttributes.rightMargin)) { + attrs.append(.rightMargin) + } + if (self.contains(ConstraintAttributes.topMargin)) { + attrs.append(.topMargin) + } + if (self.contains(ConstraintAttributes.bottomMargin)) { + attrs.append(.bottomMargin) + } + if (self.contains(ConstraintAttributes.leadingMargin)) { + attrs.append(.leadingMargin) + } + if (self.contains(ConstraintAttributes.trailingMargin)) { + attrs.append(.trailingMargin) + } + if (self.contains(ConstraintAttributes.centerXWithinMargins)) { + attrs.append(.centerXWithinMargins) + } + if (self.contains(ConstraintAttributes.centerYWithinMargins)) { + attrs.append(.centerYWithinMargins) + } + #endif + + return attrs + } +} + +internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes { + return left.union(right) +} + +internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) { + left.formUnion(right) +} + +internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) { + left.subtract(right) +} + +internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool { + return left.rawValue == right.rawValue +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintConfig.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintConfig.swift new file mode 100644 index 0000000..2746b7d --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintConfig.swift @@ -0,0 +1,37 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit + public typealias ConstraintInterfaceLayoutDirection = UIUserInterfaceLayoutDirection +#else + import AppKit + public typealias ConstraintInterfaceLayoutDirection = NSUserInterfaceLayoutDirection +#endif + + +public struct ConstraintConfig { + + public static var interfaceLayoutDirection: ConstraintInterfaceLayoutDirection = .leftToRight + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintConstantTarget.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintConstantTarget.swift new file mode 100644 index 0000000..7f54907 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintConstantTarget.swift @@ -0,0 +1,213 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol ConstraintConstantTarget { +} + +extension CGPoint: ConstraintConstantTarget { +} + +extension CGSize: ConstraintConstantTarget { +} + +extension ConstraintInsets: ConstraintConstantTarget { +} + +#if os(iOS) || os(tvOS) +@available(iOS 11.0, tvOS 11.0, *) +extension ConstraintDirectionalInsets: ConstraintConstantTarget { +} +#endif + +extension ConstraintConstantTarget { + + internal func constraintConstantTargetValueFor(layoutAttribute: LayoutAttribute) -> CGFloat { + if let value = self as? CGFloat { + return value + } + + if let value = self as? Float { + return CGFloat(value) + } + + if let value = self as? Double { + return CGFloat(value) + } + + if let value = self as? Int { + return CGFloat(value) + } + + if let value = self as? UInt { + return CGFloat(value) + } + + if let value = self as? CGSize { + if layoutAttribute == .width { + return value.width + } else if layoutAttribute == .height { + return value.height + } else { + return 0.0 + } + } + + if let value = self as? CGPoint { + #if os(iOS) || os(tvOS) + switch layoutAttribute { + case .left, .right, .leading, .trailing, .centerX, .leftMargin, .rightMargin, .leadingMargin, .trailingMargin, .centerXWithinMargins: + return value.x + case .top, .bottom, .centerY, .topMargin, .bottomMargin, .centerYWithinMargins, .lastBaseline, .firstBaseline: + return value.y + case .width, .height, .notAnAttribute: + return 0.0 + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } + #else + switch layoutAttribute { + case .left, .right, .leading, .trailing, .centerX: + return value.x + case .top, .bottom, .centerY, .lastBaseline, .firstBaseline: + return value.y + case .width, .height, .notAnAttribute: + return 0.0 + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } + #endif + } + + if let value = self as? ConstraintInsets { + #if os(iOS) || os(tvOS) + switch layoutAttribute { + case .left, .leftMargin: + return value.left + case .top, .topMargin, .firstBaseline: + return value.top + case .right, .rightMargin: + return -value.right + case .bottom, .bottomMargin, .lastBaseline: + return -value.bottom + case .leading, .leadingMargin: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.left : value.right + case .trailing, .trailingMargin: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.right : -value.left + case .centerX, .centerXWithinMargins: + return (value.left - value.right) / 2 + case .centerY, .centerYWithinMargins: + return (value.top - value.bottom) / 2 + case .width: + return -(value.left + value.right) + case .height: + return -(value.top + value.bottom) + case .notAnAttribute: + return 0.0 + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } + #else + switch layoutAttribute { + case .left: + return value.left + case .top, .firstBaseline: + return value.top + case .right: + return -value.right + case .bottom, .lastBaseline: + return -value.bottom + case .leading: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.left : value.right + case .trailing: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.right : -value.left + case .centerX: + return (value.left - value.right) / 2 + case .centerY: + return (value.top - value.bottom) / 2 + case .width: + return -(value.left + value.right) + case .height: + return -(value.top + value.bottom) + case .notAnAttribute: + return 0.0 + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } + #endif + } + + #if os(iOS) || os(tvOS) + if #available(iOS 11.0, tvOS 11.0, *), let value = self as? ConstraintDirectionalInsets { + switch layoutAttribute { + case .left, .leftMargin: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.leading : value.trailing + case .top, .topMargin, .firstBaseline: + return value.top + case .right, .rightMargin: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.trailing : -value.leading + case .bottom, .bottomMargin, .lastBaseline: + return -value.bottom + case .leading, .leadingMargin: + return value.leading + case .trailing, .trailingMargin: + return -value.trailing + case .centerX, .centerXWithinMargins: + return (value.leading - value.trailing) / 2 + case .centerY, .centerYWithinMargins: + return (value.top - value.bottom) / 2 + case .width: + return -(value.leading + value.trailing) + case .height: + return -(value.top + value.bottom) + case .notAnAttribute: + return 0.0 + #if swift(>=5.0) + @unknown default: + return 0.0 + #else + default: + return 0.0 + #endif + } + } + #endif + + return 0.0 + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDSL.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDSL.swift new file mode 100644 index 0000000..ecc5173 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDSL.swift @@ -0,0 +1,194 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol ConstraintDSL { + + var target: AnyObject? { get } + + func setLabel(_ value: String?) + func label() -> String? + +} +extension ConstraintDSL { + + public func setLabel(_ value: String?) { + objc_setAssociatedObject(self.target as Any, &labelKey, value, .OBJC_ASSOCIATION_COPY_NONATOMIC) + } + public func label() -> String? { + return objc_getAssociatedObject(self.target as Any, &labelKey) as? String + } + +} +private var labelKey: UInt8 = 0 + + +public protocol ConstraintBasicAttributesDSL : ConstraintDSL { +} +extension ConstraintBasicAttributesDSL { + + // MARK: Basics + + public var left: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.left) + } + + public var top: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.top) + } + + public var right: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.right) + } + + public var bottom: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.bottom) + } + + public var leading: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.leading) + } + + public var trailing: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.trailing) + } + + public var width: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.width) + } + + public var height: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.height) + } + + public var centerX: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerX) + } + + public var centerY: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerY) + } + + public var edges: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.edges) + } + + public var directionalEdges: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.directionalEdges) + } + + public var size: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.size) + } + + public var center: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.center) + } + +} + +public protocol ConstraintAttributesDSL : ConstraintBasicAttributesDSL { +} +extension ConstraintAttributesDSL { + + // MARK: Baselines + + @available(*, deprecated, message:"Use .lastBaseline instead") + public var baseline: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.lastBaseline) + } + + @available(iOS 8.0, OSX 10.11, *) + public var lastBaseline: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.lastBaseline) + } + + @available(iOS 8.0, OSX 10.11, *) + public var firstBaseline: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.firstBaseline) + } + + // MARK: Margins + + @available(iOS 8.0, *) + public var leftMargin: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.leftMargin) + } + + @available(iOS 8.0, *) + public var topMargin: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.topMargin) + } + + @available(iOS 8.0, *) + public var rightMargin: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.rightMargin) + } + + @available(iOS 8.0, *) + public var bottomMargin: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.bottomMargin) + } + + @available(iOS 8.0, *) + public var leadingMargin: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.leadingMargin) + } + + @available(iOS 8.0, *) + public var trailingMargin: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.trailingMargin) + } + + @available(iOS 8.0, *) + public var centerXWithinMargins: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerXWithinMargins) + } + + @available(iOS 8.0, *) + public var centerYWithinMargins: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerYWithinMargins) + } + + @available(iOS 8.0, *) + public var margins: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.margins) + } + + @available(iOS 8.0, *) + public var directionalMargins: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.directionalMargins) + } + + @available(iOS 8.0, *) + public var centerWithinMargins: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerWithinMargins) + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDescription.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDescription.swift new file mode 100644 index 0000000..3521f9f --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDescription.swift @@ -0,0 +1,69 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public class ConstraintDescription { + + internal let item: LayoutConstraintItem + internal var attributes: ConstraintAttributes + internal var relation: ConstraintRelation? = nil + internal var sourceLocation: (String, UInt)? = nil + internal var label: String? = nil + internal var related: ConstraintItem? = nil + internal var multiplier: ConstraintMultiplierTarget = 1.0 + internal var constant: ConstraintConstantTarget = 0.0 + internal var priority: ConstraintPriorityTarget = 1000.0 + internal lazy var constraint: Constraint? = { + guard let relation = self.relation, + let related = self.related, + let sourceLocation = self.sourceLocation else { + return nil + } + let from = ConstraintItem(target: self.item, attributes: self.attributes) + + return Constraint( + from: from, + to: related, + relation: relation, + sourceLocation: sourceLocation, + label: self.label, + multiplier: self.multiplier, + constant: self.constant, + priority: self.priority + ) + }() + + // MARK: Initialization + + internal init(item: LayoutConstraintItem, attributes: ConstraintAttributes) { + self.item = item + self.attributes = attributes + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift new file mode 100644 index 0000000..955aec3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift @@ -0,0 +1,49 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) +import UIKit +#else +import AppKit +#endif + +#if os(iOS) || os(tvOS) +public protocol ConstraintDirectionalInsetTarget: ConstraintConstantTarget { +} + +@available(iOS 11.0, tvOS 11.0, *) +extension ConstraintDirectionalInsets: ConstraintDirectionalInsetTarget { +} + +extension ConstraintDirectionalInsetTarget { + + @available(iOS 11.0, tvOS 11.0, *) + internal var constraintDirectionalInsetTargetValue: ConstraintDirectionalInsets { + if let amount = self as? ConstraintDirectionalInsets { + return amount + } else { + return ConstraintDirectionalInsets(top: 0, leading: 0, bottom: 0, trailing: 0) + } + } +} +#endif diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift new file mode 100644 index 0000000..ada8ed5 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift @@ -0,0 +1,34 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +#if os(iOS) || os(tvOS) + @available(iOS 11.0, tvOS 11.0, *) + public typealias ConstraintDirectionalInsets = NSDirectionalEdgeInsets +#endif diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintInsetTarget.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintInsetTarget.swift new file mode 100644 index 0000000..ba8a0f3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintInsetTarget.swift @@ -0,0 +1,72 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol ConstraintInsetTarget: ConstraintConstantTarget { +} + +extension Int: ConstraintInsetTarget { +} + +extension UInt: ConstraintInsetTarget { +} + +extension Float: ConstraintInsetTarget { +} + +extension Double: ConstraintInsetTarget { +} + +extension CGFloat: ConstraintInsetTarget { +} + +extension ConstraintInsets: ConstraintInsetTarget { +} + +extension ConstraintInsetTarget { + + internal var constraintInsetTargetValue: ConstraintInsets { + if let amount = self as? ConstraintInsets { + return amount + } else if let amount = self as? Float { + return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) + } else if let amount = self as? Double { + return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) + } else if let amount = self as? CGFloat { + return ConstraintInsets(top: amount, left: amount, bottom: amount, right: amount) + } else if let amount = self as? Int { + return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) + } else if let amount = self as? UInt { + return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) + } else { + return ConstraintInsets(top: 0, left: 0, bottom: 0, right: 0) + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintInsets.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintInsets.swift new file mode 100644 index 0000000..738ca05 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintInsets.swift @@ -0,0 +1,35 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +#if os(iOS) || os(tvOS) + public typealias ConstraintInsets = UIEdgeInsets +#else + public typealias ConstraintInsets = NSEdgeInsets +#endif diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintItem.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintItem.swift new file mode 100644 index 0000000..a342c1d --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintItem.swift @@ -0,0 +1,61 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public final class ConstraintItem { + + internal weak var target: AnyObject? + internal let attributes: ConstraintAttributes + + internal init(target: AnyObject?, attributes: ConstraintAttributes) { + self.target = target + self.attributes = attributes + } + + internal var layoutConstraintItem: LayoutConstraintItem? { + return self.target as? LayoutConstraintItem + } + +} + +public func ==(lhs: ConstraintItem, rhs: ConstraintItem) -> Bool { + // pointer equality + guard lhs !== rhs else { + return true + } + + // must both have valid targets and identical attributes + guard let target1 = lhs.target, + let target2 = rhs.target, + target1 === target2 && lhs.attributes == rhs.attributes else { + return false + } + + return true +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift new file mode 100644 index 0000000..d429e0c --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift @@ -0,0 +1,36 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#endif + + +@available(iOS 9.0, OSX 10.11, *) +public extension ConstraintLayoutGuide { + + var snp: ConstraintLayoutGuideDSL { + return ConstraintLayoutGuideDSL(guide: self) + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuide.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuide.swift new file mode 100644 index 0000000..e3e50c8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuide.swift @@ -0,0 +1,37 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +#if os(iOS) || os(tvOS) + @available(iOS 9.0, *) + public typealias ConstraintLayoutGuide = UILayoutGuide +#else + @available(OSX 10.11, *) + public typealias ConstraintLayoutGuide = NSLayoutGuide +#endif diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift new file mode 100644 index 0000000..0007819 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift @@ -0,0 +1,66 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +@available(iOS 9.0, OSX 10.11, *) +public struct ConstraintLayoutGuideDSL: ConstraintAttributesDSL { + + @discardableResult + public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { + return ConstraintMaker.prepareConstraints(item: self.guide, closure: closure) + } + + public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.makeConstraints(item: self.guide, closure: closure) + } + + public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.remakeConstraints(item: self.guide, closure: closure) + } + + public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.updateConstraints(item: self.guide, closure: closure) + } + + public func removeConstraints() { + ConstraintMaker.removeConstraints(item: self.guide) + } + + public var target: AnyObject? { + return self.guide + } + + internal let guide: ConstraintLayoutGuide + + internal init(guide: ConstraintLayoutGuide) { + self.guide = guide + + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutSupport.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutSupport.swift new file mode 100644 index 0000000..e92e9fb --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutSupport.swift @@ -0,0 +1,36 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +#if os(iOS) || os(tvOS) + @available(iOS 8.0, *) + public typealias ConstraintLayoutSupport = UILayoutSupport +#else + public class ConstraintLayoutSupport {} +#endif diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift new file mode 100644 index 0000000..5d6ae89 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift @@ -0,0 +1,56 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +@available(iOS 8.0, *) +public struct ConstraintLayoutSupportDSL: ConstraintDSL { + + public var target: AnyObject? { + return self.support + } + + internal let support: ConstraintLayoutSupport + + internal init(support: ConstraintLayoutSupport) { + self.support = support + + } + + public var top: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.top) + } + + public var bottom: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.bottom) + } + + public var height: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.height) + } +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMaker.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMaker.swift new file mode 100644 index 0000000..38f4d31 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMaker.swift @@ -0,0 +1,212 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + +public class ConstraintMaker { + + public var left: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.left) + } + + public var top: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.top) + } + + public var bottom: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.bottom) + } + + public var right: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.right) + } + + public var leading: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.leading) + } + + public var trailing: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.trailing) + } + + public var width: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.width) + } + + public var height: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.height) + } + + public var centerX: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.centerX) + } + + public var centerY: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.centerY) + } + + @available(*, deprecated, message:"Use lastBaseline instead") + public var baseline: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.lastBaseline) + } + + public var lastBaseline: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.lastBaseline) + } + + @available(iOS 8.0, OSX 10.11, *) + public var firstBaseline: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.firstBaseline) + } + + @available(iOS 8.0, *) + public var leftMargin: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.leftMargin) + } + + @available(iOS 8.0, *) + public var rightMargin: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.rightMargin) + } + + @available(iOS 8.0, *) + public var topMargin: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.topMargin) + } + + @available(iOS 8.0, *) + public var bottomMargin: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.bottomMargin) + } + + @available(iOS 8.0, *) + public var leadingMargin: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.leadingMargin) + } + + @available(iOS 8.0, *) + public var trailingMargin: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.trailingMargin) + } + + @available(iOS 8.0, *) + public var centerXWithinMargins: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.centerXWithinMargins) + } + + @available(iOS 8.0, *) + public var centerYWithinMargins: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.centerYWithinMargins) + } + + public var edges: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.edges) + } + public var directionalEdges: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.directionalEdges) + } + public var size: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.size) + } + public var center: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.center) + } + + @available(iOS 8.0, *) + public var margins: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.margins) + } + + @available(iOS 8.0, *) + public var directionalMargins: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.directionalMargins) + } + + @available(iOS 8.0, *) + public var centerWithinMargins: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.centerWithinMargins) + } + + private let item: LayoutConstraintItem + private var descriptions = [ConstraintDescription]() + + internal init(item: LayoutConstraintItem) { + self.item = item + self.item.prepare() + } + + internal func makeExtendableWithAttributes(_ attributes: ConstraintAttributes) -> ConstraintMakerExtendable { + let description = ConstraintDescription(item: self.item, attributes: attributes) + self.descriptions.append(description) + return ConstraintMakerExtendable(description) + } + + internal static func prepareConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { + let maker = ConstraintMaker(item: item) + closure(maker) + var constraints: [Constraint] = [] + for description in maker.descriptions { + guard let constraint = description.constraint else { + continue + } + constraints.append(constraint) + } + return constraints + } + + internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { + let constraints = prepareConstraints(item: item, closure: closure) + for constraint in constraints { + constraint.activateIfNeeded(updatingExisting: false) + } + } + + internal static func remakeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { + self.removeConstraints(item: item) + self.makeConstraints(item: item, closure: closure) + } + + internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { + guard item.constraints.count > 0 else { + self.makeConstraints(item: item, closure: closure) + return + } + + let constraints = prepareConstraints(item: item, closure: closure) + for constraint in constraints { + constraint.activateIfNeeded(updatingExisting: true) + } + } + + internal static func removeConstraints(item: LayoutConstraintItem) { + let constraints = item.constraints + for constraint in constraints { + constraint.deactivateIfNeeded() + } + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerEditable.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerEditable.swift new file mode 100644 index 0000000..f768a17 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerEditable.swift @@ -0,0 +1,64 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public class ConstraintMakerEditable: ConstraintMakerPriortizable { + + @discardableResult + public func multipliedBy(_ amount: ConstraintMultiplierTarget) -> ConstraintMakerEditable { + self.description.multiplier = amount + return self + } + + @discardableResult + public func dividedBy(_ amount: ConstraintMultiplierTarget) -> ConstraintMakerEditable { + return self.multipliedBy(1.0 / amount.constraintMultiplierTargetValue) + } + + @discardableResult + public func offset(_ amount: ConstraintOffsetTarget) -> ConstraintMakerEditable { + self.description.constant = amount.constraintOffsetTargetValue + return self + } + + @discardableResult + public func inset(_ amount: ConstraintInsetTarget) -> ConstraintMakerEditable { + self.description.constant = amount.constraintInsetTargetValue + return self + } + + #if os(iOS) || os(tvOS) + @discardableResult + @available(iOS 11.0, tvOS 11.0, *) + public func inset(_ amount: ConstraintDirectionalInsetTarget) -> ConstraintMakerEditable { + self.description.constant = amount.constraintDirectionalInsetTargetValue + return self + } + #endif +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerExtendable.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerExtendable.swift new file mode 100644 index 0000000..ce47169 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerExtendable.swift @@ -0,0 +1,179 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public class ConstraintMakerExtendable: ConstraintMakerRelatable { + + public var left: ConstraintMakerExtendable { + self.description.attributes += .left + return self + } + + public var top: ConstraintMakerExtendable { + self.description.attributes += .top + return self + } + + public var bottom: ConstraintMakerExtendable { + self.description.attributes += .bottom + return self + } + + public var right: ConstraintMakerExtendable { + self.description.attributes += .right + return self + } + + public var leading: ConstraintMakerExtendable { + self.description.attributes += .leading + return self + } + + public var trailing: ConstraintMakerExtendable { + self.description.attributes += .trailing + return self + } + + public var width: ConstraintMakerExtendable { + self.description.attributes += .width + return self + } + + public var height: ConstraintMakerExtendable { + self.description.attributes += .height + return self + } + + public var centerX: ConstraintMakerExtendable { + self.description.attributes += .centerX + return self + } + + public var centerY: ConstraintMakerExtendable { + self.description.attributes += .centerY + return self + } + + @available(*, deprecated, message:"Use lastBaseline instead") + public var baseline: ConstraintMakerExtendable { + self.description.attributes += .lastBaseline + return self + } + + public var lastBaseline: ConstraintMakerExtendable { + self.description.attributes += .lastBaseline + return self + } + + @available(iOS 8.0, OSX 10.11, *) + public var firstBaseline: ConstraintMakerExtendable { + self.description.attributes += .firstBaseline + return self + } + + @available(iOS 8.0, *) + public var leftMargin: ConstraintMakerExtendable { + self.description.attributes += .leftMargin + return self + } + + @available(iOS 8.0, *) + public var rightMargin: ConstraintMakerExtendable { + self.description.attributes += .rightMargin + return self + } + + @available(iOS 8.0, *) + public var topMargin: ConstraintMakerExtendable { + self.description.attributes += .topMargin + return self + } + + @available(iOS 8.0, *) + public var bottomMargin: ConstraintMakerExtendable { + self.description.attributes += .bottomMargin + return self + } + + @available(iOS 8.0, *) + public var leadingMargin: ConstraintMakerExtendable { + self.description.attributes += .leadingMargin + return self + } + + @available(iOS 8.0, *) + public var trailingMargin: ConstraintMakerExtendable { + self.description.attributes += .trailingMargin + return self + } + + @available(iOS 8.0, *) + public var centerXWithinMargins: ConstraintMakerExtendable { + self.description.attributes += .centerXWithinMargins + return self + } + + @available(iOS 8.0, *) + public var centerYWithinMargins: ConstraintMakerExtendable { + self.description.attributes += .centerYWithinMargins + return self + } + + public var edges: ConstraintMakerExtendable { + self.description.attributes += .edges + return self + } + public var directionalEdges: ConstraintMakerExtendable { + self.description.attributes += .directionalEdges + return self + } + public var size: ConstraintMakerExtendable { + self.description.attributes += .size + return self + } + + @available(iOS 8.0, *) + public var margins: ConstraintMakerExtendable { + self.description.attributes += .margins + return self + } + + @available(iOS 8.0, *) + public var directionalMargins: ConstraintMakerExtendable { + self.description.attributes += .directionalMargins + return self + } + + @available(iOS 8.0, *) + public var centerWithinMargins: ConstraintMakerExtendable { + self.description.attributes += .centerWithinMargins + return self + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift new file mode 100644 index 0000000..4e1379e --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift @@ -0,0 +1,49 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public class ConstraintMakerFinalizable { + + internal let description: ConstraintDescription + + internal init(_ description: ConstraintDescription) { + self.description = description + } + + @discardableResult + public func labeled(_ label: String) -> ConstraintMakerFinalizable { + self.description.label = label + return self + } + + public var constraint: Constraint { + return self.description.constraint! + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift new file mode 100644 index 0000000..e0d452d --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift @@ -0,0 +1,68 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public class ConstraintMakerPriortizable: ConstraintMakerFinalizable { + + @discardableResult + public func priority(_ amount: ConstraintPriority) -> ConstraintMakerFinalizable { + self.description.priority = amount.value + return self + } + + @discardableResult + public func priority(_ amount: ConstraintPriorityTarget) -> ConstraintMakerFinalizable { + self.description.priority = amount + return self + } + + @available(*, deprecated, message:"Use priority(.required) instead.") + @discardableResult + public func priorityRequired() -> ConstraintMakerFinalizable { + return self.priority(.required) + } + + @available(*, deprecated, message:"Use priority(.high) instead.") + @discardableResult + public func priorityHigh() -> ConstraintMakerFinalizable { + return self.priority(.high) + } + + @available(*, deprecated, message:"Use priority(.medium) instead.") + @discardableResult + public func priorityMedium() -> ConstraintMakerFinalizable { + return self.priority(.medium) + } + + @available(*, deprecated, message:"Use priority(.low) instead.") + @discardableResult + public func priorityLow() -> ConstraintMakerFinalizable { + return self.priority(.low) + } +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerRelatable.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerRelatable.swift new file mode 100644 index 0000000..7889532 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMakerRelatable.swift @@ -0,0 +1,115 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public class ConstraintMakerRelatable { + + internal let description: ConstraintDescription + + internal init(_ description: ConstraintDescription) { + self.description = description + } + + internal func relatedTo(_ other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable { + let related: ConstraintItem + let constant: ConstraintConstantTarget + + if let other = other as? ConstraintItem { + guard other.attributes == ConstraintAttributes.none || + other.attributes.layoutAttributes.count <= 1 || + other.attributes.layoutAttributes == self.description.attributes.layoutAttributes || + other.attributes == .edges && self.description.attributes == .margins || + other.attributes == .margins && self.description.attributes == .edges || + other.attributes == .directionalEdges && self.description.attributes == .directionalMargins || + other.attributes == .directionalMargins && self.description.attributes == .directionalEdges else { + fatalError("Cannot constraint to multiple non identical attributes. (\(file), \(line))"); + } + + related = other + constant = 0.0 + } else if let other = other as? ConstraintView { + related = ConstraintItem(target: other, attributes: ConstraintAttributes.none) + constant = 0.0 + } else if let other = other as? ConstraintConstantTarget { + related = ConstraintItem(target: nil, attributes: ConstraintAttributes.none) + constant = other + } else if #available(iOS 9.0, OSX 10.11, *), let other = other as? ConstraintLayoutGuide { + related = ConstraintItem(target: other, attributes: ConstraintAttributes.none) + constant = 0.0 + } else { + fatalError("Invalid constraint. (\(file), \(line))") + } + + let editable = ConstraintMakerEditable(self.description) + editable.description.sourceLocation = (file, line) + editable.description.relation = relation + editable.description.related = related + editable.description.constant = constant + return editable + } + + @discardableResult + public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { + return self.relatedTo(other, relation: .equal, file: file, line: line) + } + + @discardableResult + public func equalToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { + guard let other = self.description.item.superview else { + fatalError("Expected superview but found nil when attempting make constraint `equalToSuperview`.") + } + return self.relatedTo(other, relation: .equal, file: file, line: line) + } + + @discardableResult + public func lessThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { + return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line) + } + + @discardableResult + public func lessThanOrEqualToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { + guard let other = self.description.item.superview else { + fatalError("Expected superview but found nil when attempting make constraint `lessThanOrEqualToSuperview`.") + } + return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line) + } + + @discardableResult + public func greaterThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { + return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line) + } + + @discardableResult + public func greaterThanOrEqualToSuperview(_ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { + guard let other = self.description.item.superview else { + fatalError("Expected superview but found nil when attempting make constraint `greaterThanOrEqualToSuperview`.") + } + return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line) + } +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift new file mode 100644 index 0000000..6fecd33 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift @@ -0,0 +1,75 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol ConstraintMultiplierTarget { + + var constraintMultiplierTargetValue: CGFloat { get } + +} + +extension Int: ConstraintMultiplierTarget { + + public var constraintMultiplierTargetValue: CGFloat { + return CGFloat(self) + } + +} + +extension UInt: ConstraintMultiplierTarget { + + public var constraintMultiplierTargetValue: CGFloat { + return CGFloat(self) + } + +} + +extension Float: ConstraintMultiplierTarget { + + public var constraintMultiplierTargetValue: CGFloat { + return CGFloat(self) + } + +} + +extension Double: ConstraintMultiplierTarget { + + public var constraintMultiplierTargetValue: CGFloat { + return CGFloat(self) + } + +} + +extension CGFloat: ConstraintMultiplierTarget { + + public var constraintMultiplierTargetValue: CGFloat { + return self + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintOffsetTarget.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintOffsetTarget.swift new file mode 100644 index 0000000..bd9e0a1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintOffsetTarget.swift @@ -0,0 +1,69 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol ConstraintOffsetTarget: ConstraintConstantTarget { +} + +extension Int: ConstraintOffsetTarget { +} + +extension UInt: ConstraintOffsetTarget { +} + +extension Float: ConstraintOffsetTarget { +} + +extension Double: ConstraintOffsetTarget { +} + +extension CGFloat: ConstraintOffsetTarget { +} + +extension ConstraintOffsetTarget { + + internal var constraintOffsetTargetValue: CGFloat { + let offset: CGFloat + if let amount = self as? Float { + offset = CGFloat(amount) + } else if let amount = self as? Double { + offset = CGFloat(amount) + } else if let amount = self as? CGFloat { + offset = CGFloat(amount) + } else if let amount = self as? Int { + offset = CGFloat(amount) + } else if let amount = self as? UInt { + offset = CGFloat(amount) + } else { + offset = 0.0 + } + return offset + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintPriority.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintPriority.swift new file mode 100644 index 0000000..f9dab16 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintPriority.swift @@ -0,0 +1,77 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + +public struct ConstraintPriority : ExpressibleByFloatLiteral, Equatable, Strideable { + public typealias FloatLiteralType = Float + + public let value: Float + + public init(floatLiteral value: Float) { + self.value = value + } + + public init(_ value: Float) { + self.value = value + } + + public static var required: ConstraintPriority { + return 1000.0 + } + + public static var high: ConstraintPriority { + return 750.0 + } + + public static var medium: ConstraintPriority { + #if os(OSX) + return 501.0 + #else + return 500.0 + #endif + + } + + public static var low: ConstraintPriority { + return 250.0 + } + + public static func ==(lhs: ConstraintPriority, rhs: ConstraintPriority) -> Bool { + return lhs.value == rhs.value + } + + // MARK: Strideable + + public func advanced(by n: FloatLiteralType) -> ConstraintPriority { + return ConstraintPriority(floatLiteral: value + n) + } + + public func distance(to other: ConstraintPriority) -> FloatLiteralType { + return other.value - value + } +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintPriorityTarget.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintPriorityTarget.swift new file mode 100644 index 0000000..064f750 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintPriorityTarget.swift @@ -0,0 +1,85 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol ConstraintPriorityTarget { + + var constraintPriorityTargetValue: Float { get } + +} + +extension Int: ConstraintPriorityTarget { + + public var constraintPriorityTargetValue: Float { + return Float(self) + } + +} + +extension UInt: ConstraintPriorityTarget { + + public var constraintPriorityTargetValue: Float { + return Float(self) + } + +} + +extension Float: ConstraintPriorityTarget { + + public var constraintPriorityTargetValue: Float { + return self + } + +} + +extension Double: ConstraintPriorityTarget { + + public var constraintPriorityTargetValue: Float { + return Float(self) + } + +} + +extension CGFloat: ConstraintPriorityTarget { + + public var constraintPriorityTargetValue: Float { + return Float(self) + } + +} + +#if os(iOS) || os(tvOS) +extension UILayoutPriority: ConstraintPriorityTarget { + + public var constraintPriorityTargetValue: Float { + return self.rawValue + } + +} +#endif diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintRelatableTarget.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintRelatableTarget.swift new file mode 100644 index 0000000..d517a61 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintRelatableTarget.swift @@ -0,0 +1,72 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol ConstraintRelatableTarget { +} + +extension Int: ConstraintRelatableTarget { +} + +extension UInt: ConstraintRelatableTarget { +} + +extension Float: ConstraintRelatableTarget { +} + +extension Double: ConstraintRelatableTarget { +} + +extension CGFloat: ConstraintRelatableTarget { +} + +extension CGSize: ConstraintRelatableTarget { +} + +extension CGPoint: ConstraintRelatableTarget { +} + +extension ConstraintInsets: ConstraintRelatableTarget { +} + +#if os(iOS) || os(tvOS) +@available(iOS 11.0, tvOS 11.0, *) +extension ConstraintDirectionalInsets: ConstraintRelatableTarget { +} +#endif + +extension ConstraintItem: ConstraintRelatableTarget { +} + +extension ConstraintView: ConstraintRelatableTarget { +} + +@available(iOS 9.0, OSX 10.11, *) +extension ConstraintLayoutGuide: ConstraintRelatableTarget { +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintRelation.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintRelation.swift new file mode 100644 index 0000000..446aaf7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintRelation.swift @@ -0,0 +1,48 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +internal enum ConstraintRelation : Int { + case equal = 1 + case lessThanOrEqual + case greaterThanOrEqual + + internal var layoutRelation: LayoutRelation { + get { + switch(self) { + case .equal: + return .equal + case .lessThanOrEqual: + return .lessThanOrEqual + case .greaterThanOrEqual: + return .greaterThanOrEqual + } + } + } +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintView+Extensions.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintView+Extensions.swift new file mode 100644 index 0000000..a4898dc --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintView+Extensions.swift @@ -0,0 +1,152 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public extension ConstraintView { + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_left: ConstraintItem { return self.snp.left } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_top: ConstraintItem { return self.snp.top } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_right: ConstraintItem { return self.snp.right } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_bottom: ConstraintItem { return self.snp.bottom } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_leading: ConstraintItem { return self.snp.leading } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_trailing: ConstraintItem { return self.snp.trailing } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_width: ConstraintItem { return self.snp.width } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_height: ConstraintItem { return self.snp.height } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_centerX: ConstraintItem { return self.snp.centerX } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_centerY: ConstraintItem { return self.snp.centerY } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_baseline: ConstraintItem { return self.snp.baseline } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, OSX 10.11, *) + var snp_lastBaseline: ConstraintItem { return self.snp.lastBaseline } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, OSX 10.11, *) + var snp_firstBaseline: ConstraintItem { return self.snp.firstBaseline } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_leftMargin: ConstraintItem { return self.snp.leftMargin } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_topMargin: ConstraintItem { return self.snp.topMargin } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_rightMargin: ConstraintItem { return self.snp.rightMargin } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_bottomMargin: ConstraintItem { return self.snp.bottomMargin } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_leadingMargin: ConstraintItem { return self.snp.leadingMargin } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_trailingMargin: ConstraintItem { return self.snp.trailingMargin } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_centerXWithinMargins: ConstraintItem { return self.snp.centerXWithinMargins } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_centerYWithinMargins: ConstraintItem { return self.snp.centerYWithinMargins } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_edges: ConstraintItem { return self.snp.edges } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_size: ConstraintItem { return self.snp.size } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_center: ConstraintItem { return self.snp.center } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_margins: ConstraintItem { return self.snp.margins } + + @available(iOS, deprecated, message:"Use newer snp.* syntax.") + @available(iOS 8.0, *) + var snp_centerWithinMargins: ConstraintItem { return self.snp.centerWithinMargins } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { + return self.snp.prepareConstraints(closure) + } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + self.snp.makeConstraints(closure) + } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + self.snp.remakeConstraints(closure) + } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + self.snp.updateConstraints(closure) + } + + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_removeConstraints() { + self.snp.removeConstraints() + } + + var snp: ConstraintViewDSL { + return ConstraintViewDSL(view: self) + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintView.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintView.swift new file mode 100644 index 0000000..6ff8a76 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintView.swift @@ -0,0 +1,35 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +#if os(iOS) || os(tvOS) + public typealias ConstraintView = UIView +#else + public typealias ConstraintView = NSView +#endif diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintViewDSL.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintViewDSL.swift new file mode 100644 index 0000000..a0187f9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/ConstraintViewDSL.swift @@ -0,0 +1,101 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public struct ConstraintViewDSL: ConstraintAttributesDSL { + + @discardableResult + public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { + return ConstraintMaker.prepareConstraints(item: self.view, closure: closure) + } + + public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.makeConstraints(item: self.view, closure: closure) + } + + public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.remakeConstraints(item: self.view, closure: closure) + } + + public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.updateConstraints(item: self.view, closure: closure) + } + + public func removeConstraints() { + ConstraintMaker.removeConstraints(item: self.view) + } + + public var contentHuggingHorizontalPriority: Float { + get { + return self.view.contentHuggingPriority(for: .horizontal).rawValue + } + nonmutating set { + self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .horizontal) + } + } + + public var contentHuggingVerticalPriority: Float { + get { + return self.view.contentHuggingPriority(for: .vertical).rawValue + } + nonmutating set { + self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .vertical) + } + } + + public var contentCompressionResistanceHorizontalPriority: Float { + get { + return self.view.contentCompressionResistancePriority(for: .horizontal).rawValue + } + nonmutating set { + self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .horizontal) + } + } + + public var contentCompressionResistanceVerticalPriority: Float { + get { + return self.view.contentCompressionResistancePriority(for: .vertical).rawValue + } + nonmutating set { + self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .vertical) + } + } + + public var target: AnyObject? { + return self.view + } + + internal let view: ConstraintView + + internal init(view: ConstraintView) { + self.view = view + + } + +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/Debugging.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/Debugging.swift new file mode 100644 index 0000000..a78579a --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/Debugging.swift @@ -0,0 +1,169 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + +public extension LayoutConstraint { + + override var description: String { + var description = "<" + + description += descriptionForObject(self) + + if let firstItem = conditionalOptional(from: self.firstItem) { + description += " \(descriptionForObject(firstItem))" + } + + if self.firstAttribute != .notAnAttribute { + description += ".\(descriptionForAttribute(self.firstAttribute))" + } + + description += " \(descriptionForRelation(self.relation))" + + if let secondItem = self.secondItem { + description += " \(descriptionForObject(secondItem))" + } + + if self.secondAttribute != .notAnAttribute { + description += ".\(descriptionForAttribute(self.secondAttribute))" + } + + if self.multiplier != 1.0 { + description += " * \(self.multiplier)" + } + + if self.secondAttribute == .notAnAttribute { + description += " \(self.constant)" + } else { + if self.constant > 0.0 { + description += " + \(self.constant)" + } else if self.constant < 0.0 { + description += " - \(abs(self.constant))" + } + } + + if self.priority.rawValue != 1000.0 { + description += " ^\(self.priority)" + } + + description += ">" + + return description + } + +} + +private func descriptionForRelation(_ relation: LayoutRelation) -> String { + switch relation { + case .equal: return "==" + case .greaterThanOrEqual: return ">=" + case .lessThanOrEqual: return "<=" + #if swift(>=5.0) + @unknown default: return "unknown" + #endif + } +} + +private func descriptionForAttribute(_ attribute: LayoutAttribute) -> String { + #if os(iOS) || os(tvOS) + switch attribute { + case .notAnAttribute: return "notAnAttribute" + case .top: return "top" + case .left: return "left" + case .bottom: return "bottom" + case .right: return "right" + case .leading: return "leading" + case .trailing: return "trailing" + case .width: return "width" + case .height: return "height" + case .centerX: return "centerX" + case .centerY: return "centerY" + case .lastBaseline: return "lastBaseline" + case .firstBaseline: return "firstBaseline" + case .topMargin: return "topMargin" + case .leftMargin: return "leftMargin" + case .bottomMargin: return "bottomMargin" + case .rightMargin: return "rightMargin" + case .leadingMargin: return "leadingMargin" + case .trailingMargin: return "trailingMargin" + case .centerXWithinMargins: return "centerXWithinMargins" + case .centerYWithinMargins: return "centerYWithinMargins" + #if swift(>=5.0) + @unknown default: return "unknown" + #endif + } + #else + switch attribute { + case .notAnAttribute: return "notAnAttribute" + case .top: return "top" + case .left: return "left" + case .bottom: return "bottom" + case .right: return "right" + case .leading: return "leading" + case .trailing: return "trailing" + case .width: return "width" + case .height: return "height" + case .centerX: return "centerX" + case .centerY: return "centerY" + case .lastBaseline: return "lastBaseline" + case .firstBaseline: return "firstBaseline" + #if swift(>=5.0) + @unknown default: return "unknown" + #endif + } + #endif +} + +private func conditionalOptional(from object: Optional) -> Optional { + return object +} + +private func conditionalOptional(from object: T) -> Optional { + return Optional.some(object) +} + +private func descriptionForObject(_ object: AnyObject) -> String { + let pointerDescription = String(format: "%p", UInt(bitPattern: ObjectIdentifier(object))) + var desc = "" + + desc += type(of: object).description() + + if let object = object as? ConstraintView { + desc += ":\(object.snp.label() ?? pointerDescription)" + } else if let object = object as? LayoutConstraint { + desc += ":\(object.label ?? pointerDescription)" + } else { + desc += ":\(pointerDescription)" + } + + if let object = object as? LayoutConstraint, let file = object.constraint?.sourceLocation.0, let line = object.constraint?.sourceLocation.1 { + desc += "@\((file as NSString).lastPathComponent)#\(line)" + } + + desc += "" + return desc +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/LayoutConstraint.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/LayoutConstraint.swift new file mode 100644 index 0000000..5425ea8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/LayoutConstraint.swift @@ -0,0 +1,61 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public class LayoutConstraint : NSLayoutConstraint { + + public var label: String? { + get { + return self.identifier + } + set { + self.identifier = newValue + } + } + + internal weak var constraint: Constraint? = nil + +} + +internal func ==(lhs: LayoutConstraint, rhs: LayoutConstraint) -> Bool { + // If firstItem or secondItem on either constraint has a dangling pointer + // this comparison can cause a crash. The solution for this is to ensure + // your layout code hold strong references to things like Views, LayoutGuides + // and LayoutAnchors as SnapKit will not keep strong references to any of these. + guard lhs.firstAttribute == rhs.firstAttribute && + lhs.secondAttribute == rhs.secondAttribute && + lhs.relation == rhs.relation && + lhs.priority == rhs.priority && + lhs.multiplier == rhs.multiplier && + lhs.secondItem === rhs.secondItem && + lhs.firstItem === rhs.firstItem else { + return false + } + return true +} diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/LayoutConstraintItem.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/LayoutConstraintItem.swift new file mode 100644 index 0000000..a59de6b --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/LayoutConstraintItem.swift @@ -0,0 +1,93 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol LayoutConstraintItem: class { +} + +@available(iOS 9.0, OSX 10.11, *) +extension ConstraintLayoutGuide : LayoutConstraintItem { +} + +extension ConstraintView : LayoutConstraintItem { +} + + +extension LayoutConstraintItem { + + internal func prepare() { + if let view = self as? ConstraintView { + view.translatesAutoresizingMaskIntoConstraints = false + } + } + + internal var superview: ConstraintView? { + if let view = self as? ConstraintView { + return view.superview + } + + if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide { + return guide.owningView + } + + return nil + } + internal var constraints: [Constraint] { + return self.constraintsSet.allObjects as! [Constraint] + } + + internal func add(constraints: [Constraint]) { + let constraintsSet = self.constraintsSet + for constraint in constraints { + constraintsSet.add(constraint) + } + } + + internal func remove(constraints: [Constraint]) { + let constraintsSet = self.constraintsSet + for constraint in constraints { + constraintsSet.remove(constraint) + } + } + + private var constraintsSet: NSMutableSet { + let constraintsSet: NSMutableSet + + if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet { + constraintsSet = existing + } else { + constraintsSet = NSMutableSet() + objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + return constraintsSet + + } + +} +private var constraintsKey: UInt8 = 0 diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/Typealiases.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/Typealiases.swift new file mode 100644 index 0000000..ded96cc --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/Typealiases.swift @@ -0,0 +1,42 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION 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) + import UIKit +#if swift(>=4.2) + typealias LayoutRelation = NSLayoutConstraint.Relation + typealias LayoutAttribute = NSLayoutConstraint.Attribute +#else + typealias LayoutRelation = NSLayoutRelation + typealias LayoutAttribute = NSLayoutAttribute +#endif + typealias LayoutPriority = UILayoutPriority +#else + import AppKit + typealias LayoutRelation = NSLayoutConstraint.Relation + typealias LayoutAttribute = NSLayoutConstraint.Attribute + typealias LayoutPriority = NSLayoutConstraint.Priority +#endif + diff --git a/sopt_29th_Assignment/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift b/sopt_29th_Assignment/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift new file mode 100644 index 0000000..8e7644c --- /dev/null +++ b/sopt_29th_Assignment/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift @@ -0,0 +1,36 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#endif + + +@available(iOS 8.0, *) +public extension ConstraintLayoutSupport { + + var snp: ConstraintLayoutSupportDSL { + return ConstraintLayoutSupportDSL(support: self) + } + +} diff --git a/sopt_29th_Assignment/Pods/SwiftyJSON/LICENSE b/sopt_29th_Assignment/Pods/SwiftyJSON/LICENSE new file mode 100644 index 0000000..68e3fd7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SwiftyJSON/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Ruoyu Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/sopt_29th_Assignment/Pods/SwiftyJSON/README.md b/sopt_29th_Assignment/Pods/SwiftyJSON/README.md new file mode 100644 index 0000000..7a10e29 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SwiftyJSON/README.md @@ -0,0 +1,562 @@ +# SwiftyJSON + +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) + +SwiftyJSON makes it easy to deal with JSON data in Swift. + +Platform | Build Status +---------| --------------| +*OS | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) | +[Linux](https://github.com/IBM-Swift/SwiftyJSON) | [![Build Status](https://travis-ci.org/IBM-Swift/SwiftyJSON.svg?branch=master)](https://travis-ci.org/IBM-Swift/SwiftyJSON) | + + +1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) +2. [Requirements](#requirements) +3. [Integration](#integration) +4. [Usage](#usage) + - [Initialization](#initialization) + - [Subscript](#subscript) + - [Loop](#loop) + - [Error](#error) + - [Optional getter](#optional-getter) + - [Non-optional getter](#non-optional-getter) + - [Setter](#setter) + - [Raw object](#raw-object) + - [Literal convertibles](#literal-convertibles) + - [Merging](#merging) +5. [Work with Alamofire](#work-with-alamofire) +6. [Work with Moya](#work-with-moya) +7. [SwiftyJSON Model Generator](#swiftyjson-model-generator) + +> [中文介绍](http://tangplin.github.io/swiftyjson/) + + +## Why is the typical JSON handling in Swift NOT good? + +Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. + +Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to [Twitter's API](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline)). + +The code would look like this: + +```swift +if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], + let user = statusesArray[0]["user"] as? [String: Any], + let username = user["name"] as? String { + // Finally we got the username +} +``` + +It's not good. + +Even if we use optional chaining, it would be messy: + +```swift +if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], + let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { + // There's our username +} +``` + +An unreadable mess--for something that should really be simple! + +With SwiftyJSON all you have to do is: + +```swift +let json = JSON(data: dataFromNetworking) +if let userName = json[0]["user"]["name"].string { + //Now you got your value +} +``` + +And don't worry about the Optional Wrapping thing. It's done for you automatically. + +```swift +let json = JSON(data: dataFromNetworking) +let result = json[999999]["wrong_key"]["wrong_name"] +if let userName = result.string { + //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety +} else { + //Print the error + print(result.error) +} +``` + +## Requirements + +- iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ +- Xcode 8 + +## Integration + +#### CocoaPods (iOS 8+, OS X 10.9+) + +You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`: + +```ruby +platform :ios, '8.0' +use_frameworks! + +target 'MyApp' do + pod 'SwiftyJSON', '~> 4.0' +end +``` + +#### Carthage (iOS 8+, OS X 10.9+) + +You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: + +``` +github "SwiftyJSON/SwiftyJSON" ~> 4.0 +``` + +If you use Carthage to build your dependencies, make sure you have added `SwiftyJSON.framework` to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase. + +#### Swift Package Manager + +You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: + +```swift +// swift-tools-version:4.0 +import PackageDescription + +let package = Package( + name: "YOUR_PROJECT_NAME", + dependencies: [ + .package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", from: "4.0.0"), + ] +) +``` +Then run `swift build` whenever you get prepared. + +#### Manually (iOS 7+, OS X 10.9+) + +To use this library in your project manually you may: + +1. for Projects, just drag SwiftyJSON.swift to the project tree +2. for Workspaces, include the whole SwiftyJSON.xcodeproj + +## Usage + +#### Initialization + +```swift +import SwiftyJSON +``` + +```swift +let json = JSON(data: dataFromNetworking) +``` +Or + +```swift +let json = JSON(jsonObject) +``` +Or + +```swift +if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) { + let json = JSON(data: dataFromString) +} +``` + +#### Subscript + +```swift +// Getting a double from a JSON Array +let name = json[0].double +``` + +```swift +// Getting an array of string from a JSON Array +let arrayNames = json["users"].arrayValue.map {$0["name"].stringValue} +``` + +```swift +// Getting a string from a JSON Dictionary +let name = json["name"].stringValue +``` + +```swift +// Getting a string using a path to the element +let path: [JSONSubscriptType] = [1,"list",2,"name"] +let name = json[path].string +// Just the same +let name = json[1]["list"][2]["name"].string +// Alternatively +let name = json[1,"list",2,"name"].string +``` + +```swift +// With a hard way +let name = json[].string +``` + +```swift +// With a custom way +let keys:[JSONSubscriptType] = [1,"list",2,"name"] +let name = json[keys].string +``` + +#### Loop + +```swift +// If json is .Dictionary +for (key,subJson):(String, JSON) in json { + // Do something you want +} +``` + +*The first element is always a String, even if the JSON is an Array* + +```swift +// If json is .Array +// The `index` is 0.. = json["list"].arrayValue +``` + +```swift +// If not a Dictionary or nil, return [:] +let user: Dictionary = json["user"].dictionaryValue +``` + +#### Setter + +```swift +json["name"] = JSON("new-name") +json[0] = JSON(1) +``` + +```swift +json["id"].int = 1234567890 +json["coordinate"].double = 8766.766 +json["name"].string = "Jack" +json.arrayObject = [1,2,3,4] +json.dictionaryObject = ["name":"Jack", "age":25] +``` + +#### Raw object + +```swift +let rawObject: Any = json.object +``` + +```swift +let rawValue: Any = json.rawValue +``` + +```swift +//convert the JSON to raw NSData +do { + let rawData = try json.rawData() + //Do something you want +} catch { + print("Error \(error)") +} +``` + +```swift +//convert the JSON to a raw String +if let rawString = json.rawString() { + //Do something you want +} else { + print("json.rawString is nil") +} +``` + +#### Existence + +```swift +// shows you whether value specified in JSON or not +if json["name"].exists() +``` + +#### Literal convertibles + +For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) + +```swift +// StringLiteralConvertible +let json: JSON = "I'm a json" +``` + +```swift +/ /IntegerLiteralConvertible +let json: JSON = 12345 +``` + +```swift +// BooleanLiteralConvertible +let json: JSON = true +``` + +```swift +// FloatLiteralConvertible +let json: JSON = 2.8765 +``` + +```swift +// DictionaryLiteralConvertible +let json: JSON = ["I":"am", "a":"json"] +``` + +```swift +// ArrayLiteralConvertible +let json: JSON = ["I", "am", "a", "json"] +``` + +```swift +// With subscript in array +var json: JSON = [1,2,3] +json[0] = 100 +json[1] = 200 +json[2] = 300 +json[999] = 300 // Don't worry, nothing will happen +``` + +```swift +// With subscript in dictionary +var json: JSON = ["name": "Jack", "age": 25] +json["name"] = "Mike" +json["age"] = "25" // It's OK to set String +json["address"] = "L.A." // Add the "address": "L.A." in json +``` + +```swift +// Array & Dictionary +var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] +json["list"][3]["what"] = "that" +json["list",3,"what"] = "that" +let path: [JSONSubscriptType] = ["list",3,"what"] +json[path] = "that" +``` + +```swift +// With other JSON objects +let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] +let auth: JSON = [ + "user": user.object, // use user.object instead of just user + "apikey": "supersecretapitoken" +] +``` + +#### Merging + +It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON. + +If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: + +- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. +- In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. + +In case, where two fields in a JSON have a different types, the value will get always overwritten. + +There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. + +```swift +let original: JSON = [ + "first_name": "John", + "age": 20, + "skills": ["Coding", "Reading"], + "address": [ + "street": "Front St", + "zip": "12345", + ] +] + +let update: JSON = [ + "last_name": "Doe", + "age": 21, + "skills": ["Writing"], + "address": [ + "zip": "12342", + "city": "New York City" + ] +] + +let updated = original.merge(with: update) +// [ +// "first_name": "John", +// "last_name": "Doe", +// "age": 21, +// "skills": ["Coding", "Reading", "Writing"], +// "address": [ +// "street": "Front St", +// "zip": "12342", +// "city": "New York City" +// ] +// ] +``` + +## String representation +There are two options available: +- use the default Swift one +- use a custom one that will handle optionals well and represent `nil` as `"null"`: +```swift +let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] +let json = JSON(dict) +let representation = json.rawString(options: [.castNilToNSNull: true]) +// representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} +``` + +## Work with [Alamofire](https://github.com/Alamofire/Alamofire) + +SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: + +```swift +Alamofire.request(url, method: .get).validate().responseJSON { response in + switch response.result { + case .success(let value): + let json = JSON(value) + print("JSON: \(json)") + case .failure(let error): + print(error) + } +} +``` + +We also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON. + +See: [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) + + +## Work with [Moya](https://github.com/Moya/Moya) + +SwiftyJSON parse data to JSON: + +```swift +let provider = MoyaProvider() +provider.request(.showProducts) { result in + switch result { + case let .success(moyaResponse): + let data = moyaResponse.data + let json = JSON(data: data) // convert network data to json + print(json) + case let .failure(error): + print("error: \(error)") + } +} + +``` + +## SwiftyJSON Model Generator +Tools to generate SwiftyJSON Models +* [JSON Cafe](http://www.jsoncafe.com/) +* [JSON Export](https://github.com/Ahmed-Ali/JSONExport) diff --git a/sopt_29th_Assignment/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift b/sopt_29th_Assignment/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift new file mode 100644 index 0000000..f7a3f08 --- /dev/null +++ b/sopt_29th_Assignment/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift @@ -0,0 +1,1401 @@ +// SwiftyJSON.swift +// +// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: - Error +// swiftlint:disable line_length +public enum SwiftyJSONError: Int, Swift.Error { + case unsupportedType = 999 + case indexOutOfBounds = 900 + case elementTooDeep = 902 + case wrongType = 901 + case notExist = 500 + case invalidJSON = 490 +} + +extension SwiftyJSONError: CustomNSError { + + /// return the error domain of SwiftyJSONError + public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } + + /// return the error code of SwiftyJSONError + public var errorCode: Int { return self.rawValue } + + /// return the userInfo of SwiftyJSONError + public var errorUserInfo: [String: Any] { + switch self { + case .unsupportedType: + return [NSLocalizedDescriptionKey: "It is an unsupported type."] + case .indexOutOfBounds: + return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] + case .wrongType: + return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] + case .notExist: + return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] + case .invalidJSON: + return [NSLocalizedDescriptionKey: "JSON is invalid."] + case .elementTooDeep: + return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] + } + } +} + +// MARK: - JSON Type + +/** +JSON's type definitions. + +See http://www.json.org +*/ +public enum Type: Int { + case number + case string + case bool + case array + case dictionary + case null + case unknown +} + +// MARK: - JSON Base + +public struct JSON { + + /** + Creates a JSON using the data. + + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary + - parameter opt: The JSON serialization reading options. `[]` by default. + + - returns: The created JSON + */ + public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { + let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) + self.init(jsonObject: object) + } + + /** + Creates a JSON object + - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` + + - parameter object: the object + + - returns: the created JSON object + */ + public init(_ object: Any) { + switch object { + case let object as Data: + do { + try self.init(data: object) + } catch { + self.init(jsonObject: NSNull()) + } + default: + self.init(jsonObject: object) + } + } + + /** + Parses the JSON string into a JSON object + + - parameter json: the JSON string + + - returns: the created JSON object + */ + public init(parseJSON jsonString: String) { + if let data = jsonString.data(using: .utf8) { + self.init(data) + } else { + self.init(NSNull()) + } + } + + /** + Creates a JSON using the object. + + - parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. + + - returns: The created JSON + */ + fileprivate init(jsonObject: Any) { + object = jsonObject + } + + /** + Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + */ + public mutating func merge(with other: JSON) throws { + try self.merge(with: other, typecheck: true) + } + + /** + Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + + - returns: New merged JSON + */ + public func merged(with other: JSON) throws -> JSON { + var merged = self + try merged.merge(with: other, typecheck: true) + return merged + } + + /** + Private woker function which does the actual merging + Typecheck is set to true for the first recursion level to prevent total override of the source JSON + */ + fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { + if type == other.type { + switch type { + case .dictionary: + for (key, _) in other { + try self[key].merge(with: other[key], typecheck: false) + } + case .array: + self = JSON(arrayValue + other.arrayValue) + default: + self = other + } + } else { + if typecheck { + throw SwiftyJSONError.wrongType + } else { + self = other + } + } + } + + /// Private object + fileprivate var rawArray: [Any] = [] + fileprivate var rawDictionary: [String: Any] = [:] + fileprivate var rawString: String = "" + fileprivate var rawNumber: NSNumber = 0 + fileprivate var rawNull: NSNull = NSNull() + fileprivate var rawBool: Bool = false + + /// JSON type, fileprivate setter + public fileprivate(set) var type: Type = .null + + /// Error in JSON, fileprivate setter + public fileprivate(set) var error: SwiftyJSONError? + + /// Object in JSON + public var object: Any { + get { + switch type { + case .array: return rawArray + case .dictionary: return rawDictionary + case .string: return rawString + case .number: return rawNumber + case .bool: return rawBool + default: return rawNull + } + } + set { + error = nil + switch unwrap(newValue) { + case let number as NSNumber: + if number.isBool { + type = .bool + rawBool = number.boolValue + } else { + type = .number + rawNumber = number + } + case let string as String: + type = .string + rawString = string + case _ as NSNull: + type = .null + case nil: + type = .null + case let array as [Any]: + type = .array + rawArray = array + case let dictionary as [String: Any]: + type = .dictionary + rawDictionary = dictionary + default: + type = .unknown + error = SwiftyJSONError.unsupportedType + } + } + } + + /// The static null JSON + @available(*, unavailable, renamed:"null") + public static var nullJSON: JSON { return null } + public static var null: JSON { return JSON(NSNull()) } +} + +/// Private method to unwarp an object recursively +private func unwrap(_ object: Any) -> Any { + switch object { + case let json as JSON: + return unwrap(json.object) + case let array as [Any]: + return array.map(unwrap) + case let dictionary as [String: Any]: + var d = dictionary + dictionary.forEach { pair in + d[pair.key] = unwrap(pair.value) + } + return d + default: + return object + } +} + +public enum Index: Comparable { + case array(Int) + case dictionary(DictionaryIndex) + case null + + static public func == (lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { + case (.array(let left), .array(let right)): return left == right + case (.dictionary(let left), .dictionary(let right)): return left == right + case (.null, .null): return true + default: return false + } + } + + static public func < (lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { + case (.array(let left), .array(let right)): return left < right + case (.dictionary(let left), .dictionary(let right)): return left < right + default: return false + } + } +} + +public typealias JSONIndex = Index +public typealias JSONRawIndex = Index + +extension JSON: Swift.Collection { + + public typealias Index = JSONRawIndex + + public var startIndex: Index { + switch type { + case .array: return .array(rawArray.startIndex) + case .dictionary: return .dictionary(rawDictionary.startIndex) + default: return .null + } + } + + public var endIndex: Index { + switch type { + case .array: return .array(rawArray.endIndex) + case .dictionary: return .dictionary(rawDictionary.endIndex) + default: return .null + } + } + + public func index(after i: Index) -> Index { + switch i { + case .array(let idx): return .array(rawArray.index(after: idx)) + case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) + default: return .null + } + } + + public subscript (position: Index) -> (String, JSON) { + switch position { + case .array(let idx): return (String(idx), JSON(rawArray[idx])) + case .dictionary(let idx): return (rawDictionary[idx].key, JSON(rawDictionary[idx].value)) + default: return ("", JSON.null) + } + } +} + +// MARK: - Subscript + +/** + * To mark both String and Int can be used in subscript. + */ +public enum JSONKey { + case index(Int) + case key(String) +} + +public protocol JSONSubscriptType { + var jsonKey: JSONKey { get } +} + +extension Int: JSONSubscriptType { + public var jsonKey: JSONKey { + return JSONKey.index(self) + } +} + +extension String: JSONSubscriptType { + public var jsonKey: JSONKey { + return JSONKey.key(self) + } +} + +extension JSON { + + /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. + fileprivate subscript(index index: Int) -> JSON { + get { + if type != .array { + var r = JSON.null + r.error = self.error ?? SwiftyJSONError.wrongType + return r + } else if rawArray.indices.contains(index) { + return JSON(rawArray[index]) + } else { + var r = JSON.null + r.error = SwiftyJSONError.indexOutOfBounds + return r + } + } + set { + if type == .array && + rawArray.indices.contains(index) && + newValue.error == nil { + rawArray[index] = newValue.object + } + } + } + + /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. + fileprivate subscript(key key: String) -> JSON { + get { + var r = JSON.null + if type == .dictionary { + if let o = rawDictionary[key] { + r = JSON(o) + } else { + r.error = SwiftyJSONError.notExist + } + } else { + r.error = self.error ?? SwiftyJSONError.wrongType + } + return r + } + set { + if type == .dictionary && newValue.error == nil { + rawDictionary[key] = newValue.object + } + } + } + + /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. + fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { + get { + switch sub.jsonKey { + case .index(let index): return self[index: index] + case .key(let key): return self[key: key] + } + } + set { + switch sub.jsonKey { + case .index(let index): self[index: index] = newValue + case .key(let key): self[key: key] = newValue + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + Example: + + ``` + let json = JSON[data] + let path = [9,"list","person","name"] + let name = json[path] + ``` + + The same as: let name = json[9]["list"]["person"]["name"] + + - parameter path: The target json's path. + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: [JSONSubscriptType]) -> JSON { + get { + return path.reduce(self) { $0[sub: $1] } + } + set { + switch path.count { + case 0: return + case 1: self[sub:path[0]].object = newValue.object + default: + var aPath = path + aPath.remove(at: 0) + var nextJSON = self[sub: path[0]] + nextJSON[aPath] = newValue + self[sub: path[0]] = nextJSON + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + - parameter path: The target json's path. Example: + + let name = json[9,"list","person","name"] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: JSONSubscriptType...) -> JSON { + get { + return self[path] + } + set { + self[path] = newValue + } + } +} + +// MARK: - LiteralConvertible + +extension JSON: Swift.ExpressibleByStringLiteral { + + public init(stringLiteral value: StringLiteralType) { + self.init(value) + } + + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { + self.init(value) + } + + public init(unicodeScalarLiteral value: StringLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByIntegerLiteral { + + public init(integerLiteral value: IntegerLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByBooleanLiteral { + + public init(booleanLiteral value: BooleanLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByFloatLiteral { + + public init(floatLiteral value: FloatLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, Any)...) { + let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) + self.init(dictionary) + } +} + +extension JSON: Swift.ExpressibleByArrayLiteral { + + public init(arrayLiteral elements: Any...) { + self.init(elements) + } +} + +// MARK: - Raw + +extension JSON: Swift.RawRepresentable { + + public init?(rawValue: Any) { + if JSON(rawValue).type == .unknown { + return nil + } else { + self.init(rawValue) + } + } + + public var rawValue: Any { + return object + } + + public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { + guard JSONSerialization.isValidJSONObject(object) else { + throw SwiftyJSONError.invalidJSON + } + + return try JSONSerialization.data(withJSONObject: object, options: opt) + } + + public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { + do { + return try _rawString(encoding, options: [.jsonSerialization: opt]) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { + let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 + let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 + do { + return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { + guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } + switch type { + case .dictionary: + do { + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } + + guard let dict = object as? [String: Any?] else { + return nil + } + let body = try dict.keys.map { key throws -> String in + guard let value = dict[key] else { + return "\"\(key)\": null" + } + guard let unwrappedValue = value else { + return "\"\(key)\": null" + } + + let nestedValue = JSON(unwrappedValue) + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { + throw SwiftyJSONError.elementTooDeep + } + if nestedValue.type == .string { + return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return "\"\(key)\": \(nestedString)" + } + } + + return "{\(body.joined(separator: ","))}" + } catch _ { + return nil + } + case .array: + do { + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } + + guard let array = object as? [Any?] else { + return nil + } + let body = try array.map { value throws -> String in + guard let unwrappedValue = value else { + return "null" + } + + let nestedValue = JSON(unwrappedValue) + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { + throw SwiftyJSONError.invalidJSON + } + if nestedValue.type == .string { + return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return nestedString + } + } + + return "[\(body.joined(separator: ","))]" + } catch _ { + return nil + } + case .string: return rawString + case .number: return rawNumber.stringValue + case .bool: return rawBool.description + case .null: return "null" + default: return nil + } + } +} + +// MARK: - Printable, DebugPrintable + +extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { + + public var description: String { + return rawString(options: .prettyPrinted) ?? "unknown" + } + + public var debugDescription: String { + return description + } +} + +// MARK: - Array + +extension JSON { + + //Optional [JSON] + public var array: [JSON]? { + return type == .array ? rawArray.map { JSON($0) } : nil + } + + //Non-optional [JSON] + public var arrayValue: [JSON] { + return self.array ?? [] + } + + //Optional [Any] + public var arrayObject: [Any]? { + get { + switch type { + case .array: return rawArray + default: return nil + } + } + set { + self.object = newValue ?? NSNull() + } + } +} + +// MARK: - Dictionary + +extension JSON { + + //Optional [String : JSON] + public var dictionary: [String: JSON]? { + if type == .dictionary { + var d = [String: JSON](minimumCapacity: rawDictionary.count) + rawDictionary.forEach { pair in + d[pair.key] = JSON(pair.value) + } + return d + } else { + return nil + } + } + + //Non-optional [String : JSON] + public var dictionaryValue: [String: JSON] { + return dictionary ?? [:] + } + + //Optional [String : Any] + + public var dictionaryObject: [String: Any]? { + get { + switch type { + case .dictionary: return rawDictionary + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } +} + +// MARK: - Bool + +extension JSON { // : Swift.Bool + + //Optional bool + public var bool: Bool? { + get { + switch type { + case .bool: return rawBool + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional bool + public var boolValue: Bool { + get { + switch type { + case .bool: return rawBool + case .number: return rawNumber.boolValue + case .string: return ["true", "y", "t", "yes", "1"].contains { rawString.caseInsensitiveCompare($0) == .orderedSame } + default: return false + } + } + set { + object = newValue + } + } +} + +// MARK: - String + +extension JSON { + + //Optional string + public var string: String? { + get { + switch type { + case .string: return object as? String + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional string + public var stringValue: String { + get { + switch type { + case .string: return object as? String ?? "" + case .number: return rawNumber.stringValue + case .bool: return (object as? Bool).map { String($0) } ?? "" + default: return "" + } + } + set { + object = newValue + } + } +} + +// MARK: - Number + +extension JSON { + + //Optional number + public var number: NSNumber? { + get { + switch type { + case .number: return rawNumber + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional number + public var numberValue: NSNumber { + get { + switch type { + case .string: + let decimal = NSDecimalNumber(string: object as? String) + return decimal == .notANumber ? .zero : decimal + case .number: return object as? NSNumber ?? NSNumber(value: 0) + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return NSNumber(value: 0.0) + } + } + set { + object = newValue + } + } +} + +// MARK: - Null + +extension JSON { + + public var null: NSNull? { + set { + object = NSNull() + } + get { + switch type { + case .null: return rawNull + default: return nil + } + } + } + public func exists() -> Bool { + if let errorValue = error, (400...1000).contains(errorValue.errorCode) { + return false + } + return true + } +} + +// MARK: - URL + +extension JSON { + + //Optional URL + public var url: URL? { + get { + switch type { + case .string: + // Check for existing percent escapes first to prevent double-escaping of % character + if rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { + return Foundation.URL(string: rawString) + } else if let encodedString_ = rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { + // We have to use `Foundation.URL` otherwise it conflicts with the variable name. + return Foundation.URL(string: encodedString_) + } else { + return nil + } + default: + return nil + } + } + set { + object = newValue?.absoluteString ?? NSNull() + } + } +} + +// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 + +extension JSON { + + public var double: Double? { + get { + return number?.doubleValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var doubleValue: Double { + get { + return numberValue.doubleValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var float: Float? { + get { + return number?.floatValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var floatValue: Float { + get { + return numberValue.floatValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var int: Int? { + get { + return number?.intValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var intValue: Int { + get { + return numberValue.intValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt: UInt? { + get { + return number?.uintValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uIntValue: UInt { + get { + return numberValue.uintValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var int8: Int8? { + get { + return number?.int8Value + } + set { + if let newValue = newValue { + object = NSNumber(value: Int(newValue)) + } else { + object = NSNull() + } + } + } + + public var int8Value: Int8 { + get { + return numberValue.int8Value + } + set { + object = NSNumber(value: Int(newValue)) + } + } + + public var uInt8: UInt8? { + get { + return number?.uint8Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt8Value: UInt8 { + get { + return numberValue.uint8Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int16: Int16? { + get { + return number?.int16Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int16Value: Int16 { + get { + return numberValue.int16Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt16: UInt16? { + get { + return number?.uint16Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt16Value: UInt16 { + get { + return numberValue.uint16Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int32: Int32? { + get { + return number?.int32Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int32Value: Int32 { + get { + return numberValue.int32Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt32: UInt32? { + get { + return number?.uint32Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt32Value: UInt32 { + get { + return numberValue.uint32Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int64: Int64? { + get { + return number?.int64Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int64Value: Int64 { + get { + return numberValue.int64Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt64: UInt64? { + get { + return number?.uint64Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt64Value: UInt64 { + get { + return numberValue.uint64Value + } + set { + object = NSNumber(value: newValue) + } + } +} + +// MARK: - Comparable + +extension JSON: Swift.Comparable {} + +public func == (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber == rhs.rawNumber + case (.string, .string): return lhs.rawString == rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func <= (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber <= rhs.rawNumber + case (.string, .string): return lhs.rawString <= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func >= (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber >= rhs.rawNumber + case (.string, .string): return lhs.rawString >= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func > (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber > rhs.rawNumber + case (.string, .string): return lhs.rawString > rhs.rawString + default: return false + } +} + +public func < (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber < rhs.rawNumber + case (.string, .string): return lhs.rawString < rhs.rawString + default: return false + } +} + +private let trueNumber = NSNumber(value: true) +private let falseNumber = NSNumber(value: false) +private let trueObjCType = String(cString: trueNumber.objCType) +private let falseObjCType = String(cString: falseNumber.objCType) + +// MARK: - NSNumber: Comparable + +extension NSNumber { + fileprivate var isBool: Bool { + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { + return true + } else { + return false + } + } +} + +func == (lhs: NSNumber, rhs: NSNumber) -> Bool { + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedSame + } +} + +func != (lhs: NSNumber, rhs: NSNumber) -> Bool { + return !(lhs == rhs) +} + +func < (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedAscending + } +} + +func > (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == ComparisonResult.orderedDescending + } +} + +func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedDescending + } +} + +func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedAscending + } +} + +public enum writingOptionsKeys { + case jsonSerialization + case castNilToNSNull + case maxObjextDepth + case encoding +} + +// MARK: - JSON: Codable +extension JSON: Codable { + private static var codableTypes: [Codable.Type] { + return [ + Bool.self, + Int.self, + Int8.self, + Int16.self, + Int32.self, + Int64.self, + UInt.self, + UInt8.self, + UInt16.self, + UInt32.self, + UInt64.self, + Double.self, + String.self, + [JSON].self, + [String: JSON].self + ] + } + public init(from decoder: Decoder) throws { + var object: Any? + + if let container = try? decoder.singleValueContainer(), !container.decodeNil() { + for type in JSON.codableTypes { + if object != nil { + break + } + // try to decode value + switch type { + case let boolType as Bool.Type: + object = try? container.decode(boolType) + case let intType as Int.Type: + object = try? container.decode(intType) + case let int8Type as Int8.Type: + object = try? container.decode(int8Type) + case let int32Type as Int32.Type: + object = try? container.decode(int32Type) + case let int64Type as Int64.Type: + object = try? container.decode(int64Type) + case let uintType as UInt.Type: + object = try? container.decode(uintType) + case let uint8Type as UInt8.Type: + object = try? container.decode(uint8Type) + case let uint16Type as UInt16.Type: + object = try? container.decode(uint16Type) + case let uint32Type as UInt32.Type: + object = try? container.decode(uint32Type) + case let uint64Type as UInt64.Type: + object = try? container.decode(uint64Type) + case let doubleType as Double.Type: + object = try? container.decode(doubleType) + case let stringType as String.Type: + object = try? container.decode(stringType) + case let jsonValueArrayType as [JSON].Type: + object = try? container.decode(jsonValueArrayType) + case let jsonValueDictType as [String: JSON].Type: + object = try? container.decode(jsonValueDictType) + default: + break + } + } + } + self.init(object ?? NSNull()) + } + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + if object is NSNull { + try container.encodeNil() + return + } + switch object { + case let intValue as Int: + try container.encode(intValue) + case let int8Value as Int8: + try container.encode(int8Value) + case let int32Value as Int32: + try container.encode(int32Value) + case let int64Value as Int64: + try container.encode(int64Value) + case let uintValue as UInt: + try container.encode(uintValue) + case let uint8Value as UInt8: + try container.encode(uint8Value) + case let uint16Value as UInt16: + try container.encode(uint16Value) + case let uint32Value as UInt32: + try container.encode(uint32Value) + case let uint64Value as UInt64: + try container.encode(uint64Value) + case let doubleValue as Double: + try container.encode(doubleValue) + case let boolValue as Bool: + try container.encode(boolValue) + case let stringValue as String: + try container.encode(stringValue) + case is [Any]: + let jsonValueArray = array ?? [] + try container.encode(jsonValueArray) + case is [String: Any]: + let jsonValueDictValue = dictionary ?? [:] + try container.encode(jsonValueDictValue) + default: + break + } + } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-Info.plist new file mode 100644 index 0000000..40a20b1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.4.4 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..00014e3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig new file mode 100644 index 0000000..7d169c4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig new file mode 100644 index 0000000..7d169c4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-Info.plist new file mode 100644 index 0000000..1b8fa1c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.15.8 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-dummy.m new file mode 100644 index 0000000..1b89d0e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Kingfisher : NSObject +@end +@implementation PodsDummy_Kingfisher +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-umbrella.h new file mode 100644 index 0000000..89b88ac --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher-umbrella.h @@ -0,0 +1,17 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "Kingfisher.h" + +FOUNDATION_EXPORT double KingfisherVersionNumber; +FOUNDATION_EXPORT const unsigned char KingfisherVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.debug.xcconfig new file mode 100644 index 0000000..f65bd7c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Kingfisher +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Accelerate" -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Kingfisher +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.modulemap new file mode 100644 index 0000000..2a20d91 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.modulemap @@ -0,0 +1,6 @@ +framework module Kingfisher { + umbrella header "Kingfisher-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.release.xcconfig new file mode 100644 index 0000000..f65bd7c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Kingfisher/Kingfisher.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Kingfisher +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Accelerate" -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Kingfisher +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-Info.plist new file mode 100644 index 0000000..a7a6daf --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.5.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-dummy.m new file mode 100644 index 0000000..47f9230 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_ListPlaceholder : NSObject +@end +@implementation PodsDummy_ListPlaceholder +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-umbrella.h new file mode 100644 index 0000000..1ba9b3e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double ListPlaceholderVersionNumber; +FOUNDATION_EXPORT const unsigned char ListPlaceholderVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.debug.xcconfig new file mode 100644 index 0000000..f6fec3e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/ListPlaceholder +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -l"z" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/ListPlaceholder +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.modulemap new file mode 100644 index 0000000..0f06e84 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.modulemap @@ -0,0 +1,6 @@ +framework module ListPlaceholder { + umbrella header "ListPlaceholder-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.release.xcconfig new file mode 100644 index 0000000..f6fec3e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/ListPlaceholder/ListPlaceholder.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/ListPlaceholder +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -l"z" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/ListPlaceholder +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-Info.plist new file mode 100644 index 0000000..7f41e09 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 14.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-dummy.m new file mode 100644 index 0000000..260473f --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Moya : NSObject +@end +@implementation PodsDummy_Moya +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-umbrella.h new file mode 100644 index 0000000..8d81047 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double MoyaVersionNumber; +FOUNDATION_EXPORT const unsigned char MoyaVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.debug.xcconfig new file mode 100644 index 0000000..ffcdff8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.debug.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Moya +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "Foundation" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Moya +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.modulemap new file mode 100644 index 0000000..7b84cdb --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.modulemap @@ -0,0 +1,6 @@ +framework module Moya { + umbrella header "Moya-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.release.xcconfig new file mode 100644 index 0000000..ffcdff8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Moya/Moya.release.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Moya +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "Foundation" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Moya +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-acknowledgements.markdown b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-acknowledgements.markdown new file mode 100644 index 0000000..d2c5b99 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-acknowledgements.markdown @@ -0,0 +1,443 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +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. + + +## Kingfisher + +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. + + + +## ListPlaceholder + +Copyright (c) 2017 Moayad Al kouz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## Moya + +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. + + +## RxCocoa + +**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. + + +## RxRelay + +**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. + + +## RxSwift + +**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. + + +## SkeletonView + +The MIT License (MIT) + +Copyright (c) 2017 Juanpe Catalán + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +## SnapKit + +Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## SwiftyJSON + +The MIT License (MIT) + +Copyright (c) 2017 Ruoyu Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## Then + +The MIT License (MIT) + +Copyright (c) 2015 Suyeol Jeon (xoul.kr) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +## lottie-ios + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Airbnb, Inc. + + 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 + + https://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. + +Generated by CocoaPods - https://cocoapods.org diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-acknowledgements.plist b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-acknowledgements.plist new file mode 100644 index 0000000..c411065 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-acknowledgements.plist @@ -0,0 +1,541 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + 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. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + 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. + + + License + MIT + Title + Kingfisher + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2017 Moayad Al kouz <moayad_kouz9@hotmail.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + ListPlaceholder + Type + PSGroupSpecifier + + + FooterText + 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. + + License + MIT + Title + Moya + Type + PSGroupSpecifier + + + FooterText + **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. + + License + MIT + Title + RxCocoa + Type + PSGroupSpecifier + + + FooterText + **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. + + License + MIT + Title + RxRelay + Type + PSGroupSpecifier + + + FooterText + **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. + + License + MIT + Title + RxSwift + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2017 Juanpe Catalán + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + License + MIT + Title + SkeletonView + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + SnapKit + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2017 Ruoyu Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + SwiftyJSON + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2015 Suyeol Jeon (xoul.kr) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + License + MIT + Title + Then + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Airbnb, Inc. + + 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 + + https://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. + + License + Apache + Title + lottie-ios + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-dummy.m new file mode 100644 index 0000000..a0f189e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_sopt_29th_Assignment : NSObject +@end +@implementation PodsDummy_Pods_sopt_29th_Assignment +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Debug-input-files.xcfilelist b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 0000000..2902c53 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,13 @@ +${PODS_ROOT}/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/Kingfisher/Kingfisher.framework +${BUILT_PRODUCTS_DIR}/ListPlaceholder/ListPlaceholder.framework +${BUILT_PRODUCTS_DIR}/Moya/Moya.framework +${BUILT_PRODUCTS_DIR}/RxCocoa/RxCocoa.framework +${BUILT_PRODUCTS_DIR}/RxRelay/RxRelay.framework +${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework +${BUILT_PRODUCTS_DIR}/SkeletonView/SkeletonView.framework +${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework +${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework +${BUILT_PRODUCTS_DIR}/Then/Then.framework +${BUILT_PRODUCTS_DIR}/lottie-ios/Lottie.framework \ No newline at end of file diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Debug-output-files.xcfilelist b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 0000000..20766ca --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,12 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Kingfisher.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ListPlaceholder.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Moya.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxCocoa.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxRelay.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SkeletonView.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftyJSON.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Then.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Lottie.framework \ No newline at end of file diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Release-input-files.xcfilelist b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Release-input-files.xcfilelist new file mode 100644 index 0000000..2902c53 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,13 @@ +${PODS_ROOT}/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/Kingfisher/Kingfisher.framework +${BUILT_PRODUCTS_DIR}/ListPlaceholder/ListPlaceholder.framework +${BUILT_PRODUCTS_DIR}/Moya/Moya.framework +${BUILT_PRODUCTS_DIR}/RxCocoa/RxCocoa.framework +${BUILT_PRODUCTS_DIR}/RxRelay/RxRelay.framework +${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework +${BUILT_PRODUCTS_DIR}/SkeletonView/SkeletonView.framework +${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework +${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework +${BUILT_PRODUCTS_DIR}/Then/Then.framework +${BUILT_PRODUCTS_DIR}/lottie-ios/Lottie.framework \ No newline at end of file diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Release-output-files.xcfilelist b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Release-output-files.xcfilelist new file mode 100644 index 0000000..20766ca --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,12 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Kingfisher.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ListPlaceholder.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Moya.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxCocoa.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxRelay.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SkeletonView.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftyJSON.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Then.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Lottie.framework \ No newline at end of file diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks.sh b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks.sh new file mode 100755 index 0000000..920a6e8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks.sh @@ -0,0 +1,208 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + mkdir -p "${DWARF_DSYM_FOLDER_PATH}" + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Kingfisher/Kingfisher.framework" + install_framework "${BUILT_PRODUCTS_DIR}/ListPlaceholder/ListPlaceholder.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Moya/Moya.framework" + install_framework "${BUILT_PRODUCTS_DIR}/RxCocoa/RxCocoa.framework" + install_framework "${BUILT_PRODUCTS_DIR}/RxRelay/RxRelay.framework" + install_framework "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SkeletonView/SkeletonView.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Then/Then.framework" + install_framework "${BUILT_PRODUCTS_DIR}/lottie-ios/Lottie.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Kingfisher/Kingfisher.framework" + install_framework "${BUILT_PRODUCTS_DIR}/ListPlaceholder/ListPlaceholder.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Moya/Moya.framework" + install_framework "${BUILT_PRODUCTS_DIR}/RxCocoa/RxCocoa.framework" + install_framework "${BUILT_PRODUCTS_DIR}/RxRelay/RxRelay.framework" + install_framework "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SkeletonView/SkeletonView.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Then/Then.framework" + install_framework "${BUILT_PRODUCTS_DIR}/lottie-ios/Lottie.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-umbrella.h new file mode 100644 index 0000000..14af721 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_sopt_29th_AssignmentVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_sopt_29th_AssignmentVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.debug.xcconfig new file mode 100644 index 0000000..aba099f --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.debug.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kingfisher" "${PODS_CONFIGURATION_BUILD_DIR}/ListPlaceholder" "${PODS_CONFIGURATION_BUILD_DIR}/Moya" "${PODS_CONFIGURATION_BUILD_DIR}/RxCocoa" "${PODS_CONFIGURATION_BUILD_DIR}/RxRelay" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SkeletonView" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" "${PODS_CONFIGURATION_BUILD_DIR}/Then" "${PODS_CONFIGURATION_BUILD_DIR}/lottie-ios" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kingfisher/Kingfisher.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ListPlaceholder/ListPlaceholder.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Moya/Moya.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxCocoa/RxCocoa.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxRelay/RxRelay.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SkeletonView/SkeletonView.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Then/Then.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/lottie-ios/Lottie.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -l"z" -framework "Accelerate" -framework "Alamofire" -framework "CFNetwork" -framework "CoreGraphics" -framework "Foundation" -framework "Kingfisher" -framework "ListPlaceholder" -framework "Lottie" -framework "Moya" -framework "QuartzCore" -framework "RxCocoa" -framework "RxRelay" -framework "RxSwift" -framework "SkeletonView" -framework "SnapKit" -framework "SwiftyJSON" -framework "Then" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.modulemap new file mode 100644 index 0000000..79ae7fd --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.modulemap @@ -0,0 +1,6 @@ +framework module Pods_sopt_29th_Assignment { + umbrella header "Pods-sopt_29th_Assignment-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.release.xcconfig new file mode 100644 index 0000000..aba099f --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.release.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kingfisher" "${PODS_CONFIGURATION_BUILD_DIR}/ListPlaceholder" "${PODS_CONFIGURATION_BUILD_DIR}/Moya" "${PODS_CONFIGURATION_BUILD_DIR}/RxCocoa" "${PODS_CONFIGURATION_BUILD_DIR}/RxRelay" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SkeletonView" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" "${PODS_CONFIGURATION_BUILD_DIR}/Then" "${PODS_CONFIGURATION_BUILD_DIR}/lottie-ios" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kingfisher/Kingfisher.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ListPlaceholder/ListPlaceholder.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Moya/Moya.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxCocoa/RxCocoa.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxRelay/RxRelay.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SkeletonView/SkeletonView.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Then/Then.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/lottie-ios/Lottie.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -l"z" -framework "Accelerate" -framework "Alamofire" -framework "CFNetwork" -framework "CoreGraphics" -framework "Foundation" -framework "Kingfisher" -framework "ListPlaceholder" -framework "Lottie" -framework "Moya" -framework "QuartzCore" -framework "RxCocoa" -framework "RxRelay" -framework "RxSwift" -framework "SkeletonView" -framework "SnapKit" -framework "SwiftyJSON" -framework "Then" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-Info.plist new file mode 100644 index 0000000..45024a7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 6.2.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-dummy.m new file mode 100644 index 0000000..d4711fd --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_RxCocoa : NSObject +@end +@implementation PodsDummy_RxCocoa +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-umbrella.h new file mode 100644 index 0000000..26f89e6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa-umbrella.h @@ -0,0 +1,22 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "RxCocoaRuntime.h" +#import "_RX.h" +#import "_RXDelegateProxy.h" +#import "_RXKVOObserver.h" +#import "_RXObjCRuntime.h" +#import "RxCocoa.h" + +FOUNDATION_EXPORT double RxCocoaVersionNumber; +FOUNDATION_EXPORT const unsigned char RxCocoaVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.debug.xcconfig new file mode 100644 index 0000000..493ddf9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.debug.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RxCocoa +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RxRelay" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "RxRelay" -framework "RxSwift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/RxCocoa +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.modulemap new file mode 100644 index 0000000..0aa97aa --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.modulemap @@ -0,0 +1,6 @@ +framework module RxCocoa { + umbrella header "RxCocoa-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.release.xcconfig new file mode 100644 index 0000000..493ddf9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxCocoa/RxCocoa.release.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RxCocoa +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RxRelay" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "RxRelay" -framework "RxSwift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/RxCocoa +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-Info.plist new file mode 100644 index 0000000..45024a7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 6.2.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-dummy.m new file mode 100644 index 0000000..eec0190 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_RxRelay : NSObject +@end +@implementation PodsDummy_RxRelay +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-umbrella.h new file mode 100644 index 0000000..67f7f55 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double RxRelayVersionNumber; +FOUNDATION_EXPORT const unsigned char RxRelayVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.debug.xcconfig new file mode 100644 index 0000000..f76af3e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.debug.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RxRelay +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "RxSwift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/RxRelay +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.modulemap new file mode 100644 index 0000000..96a115a --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.modulemap @@ -0,0 +1,6 @@ +framework module RxRelay { + umbrella header "RxRelay-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.release.xcconfig new file mode 100644 index 0000000..f76af3e --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxRelay/RxRelay.release.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RxRelay +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "RxSwift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/RxRelay +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-Info.plist new file mode 100644 index 0000000..45024a7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 6.2.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-dummy.m new file mode 100644 index 0000000..3783f72 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_RxSwift : NSObject +@end +@implementation PodsDummy_RxSwift +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h new file mode 100644 index 0000000..9a27211 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double RxSwiftVersionNumber; +FOUNDATION_EXPORT const unsigned char RxSwiftVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.debug.xcconfig new file mode 100644 index 0000000..6baebfc --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RxSwift +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/RxSwift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.modulemap new file mode 100644 index 0000000..eae3d1c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.modulemap @@ -0,0 +1,6 @@ +framework module RxSwift { + umbrella header "RxSwift-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.release.xcconfig new file mode 100644 index 0000000..6baebfc --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/RxSwift/RxSwift.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/RxSwift +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/RxSwift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-Info.plist new file mode 100644 index 0000000..f051c77 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.25.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-dummy.m new file mode 100644 index 0000000..324c44c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SkeletonView : NSObject +@end +@implementation PodsDummy_SkeletonView +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-umbrella.h new file mode 100644 index 0000000..2f6e096 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double SkeletonViewVersionNumber; +FOUNDATION_EXPORT const unsigned char SkeletonViewVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.debug.xcconfig new file mode 100644 index 0000000..2fc6999 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SkeletonView +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SkeletonView +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.modulemap new file mode 100644 index 0000000..6f2c1fc --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.modulemap @@ -0,0 +1,6 @@ +framework module SkeletonView { + umbrella header "SkeletonView-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.release.xcconfig new file mode 100644 index 0000000..2fc6999 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SkeletonView/SkeletonView.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SkeletonView +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SkeletonView +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-Info.plist new file mode 100644 index 0000000..8d87a1a --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-dummy.m new file mode 100644 index 0000000..b44e8e5 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SnapKit : NSObject +@end +@implementation PodsDummy_SnapKit +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h new file mode 100644 index 0000000..1b1be64 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double SnapKitVersionNumber; +FOUNDATION_EXPORT const unsigned char SnapKitVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.debug.xcconfig new file mode 100644 index 0000000..03fb3c1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SnapKit +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SnapKit +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.modulemap new file mode 100644 index 0000000..4b3e47b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.modulemap @@ -0,0 +1,6 @@ +framework module SnapKit { + umbrella header "SnapKit-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.release.xcconfig new file mode 100644 index 0000000..03fb3c1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SnapKit/SnapKit.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SnapKit +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SnapKit +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist new file mode 100644 index 0000000..a83149a --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.3.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m new file mode 100644 index 0000000..3159bec --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SwiftyJSON : NSObject +@end +@implementation PodsDummy_SwiftyJSON +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h new file mode 100644 index 0000000..b627dec --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double SwiftyJSONVersionNumber; +FOUNDATION_EXPORT const unsigned char SwiftyJSONVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig new file mode 100644 index 0000000..c9f18d8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap new file mode 100644 index 0000000..6f41751 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap @@ -0,0 +1,6 @@ +framework module SwiftyJSON { + umbrella header "SwiftyJSON-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig new file mode 100644 index 0000000..c9f18d8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-Info.plist new file mode 100644 index 0000000..e511383 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.7.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-dummy.m new file mode 100644 index 0000000..6be6d43 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Then : NSObject +@end +@implementation PodsDummy_Then +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-umbrella.h new file mode 100644 index 0000000..851f9ac --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double ThenVersionNumber; +FOUNDATION_EXPORT const unsigned char ThenVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.debug.xcconfig new file mode 100644 index 0000000..876568b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Then +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Then +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.modulemap new file mode 100644 index 0000000..4385750 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.modulemap @@ -0,0 +1,6 @@ +framework module Then { + umbrella header "Then-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.release.xcconfig new file mode 100644 index 0000000..876568b --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/Then/Then.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Then +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Then +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-Info.plist b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-Info.plist new file mode 100644 index 0000000..806ba0d --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.2.3 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-dummy.m b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-dummy.m new file mode 100644 index 0000000..67e66c9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_lottie_ios : NSObject +@end +@implementation PodsDummy_lottie_ios +@end diff --git a/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-prefix.pch b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-umbrella.h b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-umbrella.h new file mode 100644 index 0000000..287f9db --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double LottieVersionNumber; +FOUNDATION_EXPORT const unsigned char LottieVersionString[]; + diff --git a/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.debug.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.debug.xcconfig new file mode 100644 index 0000000..bc9cd34 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/lottie-ios +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CoreGraphics" -framework "QuartzCore" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/lottie-ios +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.modulemap b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.modulemap new file mode 100644 index 0000000..494806f --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.modulemap @@ -0,0 +1,6 @@ +framework module Lottie { + umbrella header "lottie-ios-umbrella.h" + + export * + module * { export * } +} diff --git a/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.release.xcconfig b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.release.xcconfig new file mode 100644 index 0000000..bc9cd34 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Target Support Files/lottie-ios/lottie-ios.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/lottie-ios +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CoreGraphics" -framework "QuartzCore" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/lottie-ios +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/sopt_29th_Assignment/Pods/Then/LICENSE b/sopt_29th_Assignment/Pods/Then/LICENSE new file mode 100644 index 0000000..7f0cb52 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Then/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Suyeol Jeon (xoul.kr) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/sopt_29th_Assignment/Pods/Then/README.md b/sopt_29th_Assignment/Pods/Then/README.md new file mode 100644 index 0000000..159c105 --- /dev/null +++ b/sopt_29th_Assignment/Pods/Then/README.md @@ -0,0 +1,124 @@ +# Then + +![Swift](https://img.shields.io/badge/Swift-5.0-orange.svg) +[![CocoaPods](http://img.shields.io/cocoapods/v/Then.svg)](https://cocoapods.org/pods/Then) +[![Build Status](https://travis-ci.org/devxoul/Then.svg?branch=master)](https://travis-ci.org/devxoul/Then) + +✨ Super sweet syntactic sugar for Swift initializers. + +## At a Glance + +Initialize UILabel **then** set its properties. + +```swift +let label = UILabel().then { + $0.textAlignment = .center + $0.textColor = .black + $0.text = "Hello, World!" +} +``` + +This is equivalent to: + +```swift +let label: UILabel = { + let label = UILabel() + label.textAlignment = .center + label.textColor = .black + label.text = "Hello, World!" + return label +}() +``` + +## Tips and Tricks + +- You can use `then()` to all of `NSObject` subclasses. + + ```swift + let queue = OperationQueue().then { + $0.maxConcurrentOperationCount = 1 + } + ``` + +- Want to use with your own types? Just make extensions. + + ```swift + extension MyType: Then {} + + let instance = MyType().then { + $0.really = "awesome!" + } + ``` + +- Use `with()` when copying the value types. + + ```swift + let newFrame = oldFrame.with { + $0.size.width = 200 + $0.size.height = 100 + } + newFrame.width // 200 + newFrame.height // 100 + ``` + +- Use `do()` to do something with less typing. + + ```swift + UserDefaults.standard.do { + $0.set("devxoul", forKey: "username") + $0.set("devxoul@gmail.com", forKey: "email") + $0.synchronize() + } + ``` + +## Real World Example + +Here's an example usage in an UIViewController subclass. + +```swift +final class MyViewController: UIViewController { + + let titleLabel = UILabel().then { + $0.textColor = .black + $0.textAlignment = .center + } + + let tableView = UITableView().then { + $0.backgroundColor = .clear + $0.separatorStyle = .none + $0.register(MyCell.self, forCellReuseIdentifier: "myCell") + } + + override func viewDidLoad() { + super.viewDidLoad() + self.view.addSubview(self.titleLabel) + self.view.addSubview(self.tableView) + } + +} +``` + +## Installation + +- **Using [CocoaPods](https://cocoapods.org)**: + + ```ruby + pod 'Then' + ``` + +- **Using [Swift Package Manager](https://swift.org/package-manager)**: + + ```swift + import PackageDescription + + let package = Package( + name: "MyAwesomeApp", + dependencies: [ + .Package(url: "https://github.com/devxoul/Then", majorVersion: 2), + ] + ) + ``` + +## License + +**Then** is under MIT license. See the [LICENSE](LICENSE) file for more info. diff --git a/sopt_29th_Assignment/Pods/Then/Sources/Then/Then.swift b/sopt_29th_Assignment/Pods/Then/Sources/Then/Then.swift new file mode 100644 index 0000000..fa0da8c --- /dev/null +++ b/sopt_29th_Assignment/Pods/Then/Sources/Then/Then.swift @@ -0,0 +1,96 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015 Suyeol Jeon (xoul.kr) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION 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(Linux) + import CoreGraphics +#endif +#if os(iOS) || os(tvOS) + import UIKit.UIGeometry +#endif + +public protocol Then {} + +extension Then where Self: Any { + + /// Makes it available to set properties with closures just after initializing and copying the value types. + /// + /// let frame = CGRect().with { + /// $0.origin.x = 10 + /// $0.size.width = 100 + /// } + @inlinable + public func with(_ block: (inout Self) throws -> Void) rethrows -> Self { + var copy = self + try block(©) + return copy + } + + /// Makes it available to execute something with closures. + /// + /// UserDefaults.standard.do { + /// $0.set("devxoul", forKey: "username") + /// $0.set("devxoul@gmail.com", forKey: "email") + /// $0.synchronize() + /// } + @inlinable + public func `do`(_ block: (Self) throws -> Void) rethrows { + try block(self) + } + +} + +extension Then where Self: AnyObject { + + /// Makes it available to set properties with closures just after initializing. + /// + /// let label = UILabel().then { + /// $0.textAlignment = .center + /// $0.textColor = UIColor.black + /// $0.text = "Hello, World!" + /// } + @inlinable + public func then(_ block: (Self) throws -> Void) rethrows -> Self { + try block(self) + return self + } + +} + +extension NSObject: Then {} + +#if !os(Linux) + extension CGPoint: Then {} + extension CGRect: Then {} + extension CGSize: Then {} + extension CGVector: Then {} +#endif + +extension Array: Then {} +extension Dictionary: Then {} +extension Set: Then {} + +#if os(iOS) || os(tvOS) + extension UIEdgeInsets: Then {} + extension UIOffset: Then {} + extension UIRectEdge: Then {} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/LICENSE b/sopt_29th_Assignment/Pods/lottie-ios/LICENSE new file mode 100644 index 0000000..55bb178 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Airbnb, Inc. + + 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 + + https://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. diff --git a/sopt_29th_Assignment/Pods/lottie-ios/README.md b/sopt_29th_Assignment/Pods/lottie-ios/README.md new file mode 100644 index 0000000..386ed7d --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/README.md @@ -0,0 +1,116 @@ +# Lottie for iOS, macOS (and [Android](https://github.com/airbnb/lottie-android) and [React Native](https://github.com/airbnb/lottie-react-native)) +[![Version](https://img.shields.io/cocoapods/v/lottie-ios.svg?style=flat)](https://cocoapods.org/pods/lottie-ios)[![License](https://img.shields.io/cocoapods/l/lottie-ios.svg?style=flat)](https://cocoapods.org/pods/lottie-ios)[![Platform](https://img.shields.io/cocoapods/p/lottie-ios.svg?style=flat)](https://cocoapods.org/pods/lottie-ios) + +# View documentation, FAQ, help, examples, and more at [airbnb.io/lottie](http://airbnb.io/lottie/) + +Lottie is a mobile library for Android and iOS that natively renders vector based animations and art in realtime with minimal code. + +Lottie loads and renders animations and vectors exported in the bodymovin JSON format. Bodymovin JSON can be created and exported from After Effects with [bodymovin](https://github.com/bodymovin/bodymovin), Sketch with [Lottie Sketch Export](https://github.com/buba447/Lottie-Sketch-Export), and from [Haiku](https://www.haiku.ai). + +For the first time, designers can create **and ship** beautiful animations without an engineer painstakingly recreating it by hand. +Since the animation is backed by JSON they are extremely small in size but can be large in complexity! +Animations can be played, resized, looped, sped up, slowed down, reversed, and even interactively scrubbed. +Lottie can play or loop just a portion of the animation as well, the possibilities are endless! +Animations can even be ***changed at runtime*** in various ways! Change the color, position or any keyframable value! +Lottie also supports native UIViewController Transitions out of the box! + +Here is just a small sampling of the power of Lottie + +![Example1](_Gifs/Examples1.gif) +![Example2](_Gifs/Examples2.gif) + + + +![Example3](_Gifs/Examples3.gif) + +![Abcs](_Gifs/Examples4.gif) + +## Installing Lottie +Lottie supports [CocoaPods](https://cocoapods.org/) and [Carthage](https://github.com/Carthage/Carthage) (Both dynamic and static). Lottie is written in ***Swift 4.2***. +### Github Repo + +You can pull the [Lottie Github Repo](https://github.com/airbnb/lottie-ios/) and include the Lottie.xcodeproj to build a dynamic or static library. + +### CocoaPods +Add the pod to your Podfile: +```ruby +pod 'lottie-ios' +``` + +And then run: +```ruby +pod install +``` +After installing the cocoapod into your project import Lottie with +```swift +import Lottie +``` +### Carthage +Add Lottie to your Cartfile: +``` +github "airbnb/lottie-ios" "master" +``` + +And then run: +``` +carthage update +``` +In your application targets “General” tab under the “Linked Frameworks and Libraries” section, drag and drop lottie-ios.framework from the Carthage/Build/iOS directory that `carthage update` produced. + +### Swift Package Manager +``` swift +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "YourTestProject", + platforms: [ + .iOS(.v12), + ], + dependencies: [ + .package(url: "https://github.com/airbnb/lottie-ios.git", from: "3.1.2") + ], + targets: [ + .target(name: "YourTestProject", dependencies: ["Lottie"]) + ] +) +``` +And then import wherever needed: ```import Lottie``` + +#### Adding it to an existent iOS Project via Swift Package Manager + +1. Using Xcode 11 go to File > Swift Packages > Add Package Dependency +2. Paste the project URL: https://github.com/airbnb/lottie-ios +3. Click on next and select the project target +4. Don't forget to set `DEAD_CODE_STRIPPING = NO` in your `Build Settings` (https://bugs.swift.org/plugins/servlet/mobile#issue/SR-11564) + **NOTE: For MacOS you must set the `Branch` field to `lottie/macos-spm` + ![Example](_Gifs/spm-branch.png) + +If you have doubts, please, check the following links: + +[How to use](https://developer.apple.com/videos/play/wwdc2019/408/) + +[Creating Swift Packages](https://developer.apple.com/videos/play/wwdc2019/410/) + +After successfully retrieved the package and added it to your project, just import `Lottie` and you can get the full benefits of it. + +----- + +### Objective-C Support + +As of 3.0 Lottie has been completely rewritten in Swift! + +For Objective-C support please use Lottie 2.5.3. Alternatively an Objective-C branch exists and is still active. + +The official objective c branch can be found here: + +[Objective-C Branch](https://github.com/airbnb/lottie-ios/tree/lottie/objectiveC) + +Also check out the documentation regarding it here: + +[iOS Migration](http://airbnb.io/lottie/#/ios-migration) + +### Data collection + +The Lottie SDK does not collect any data. We provide this notice to help you fill out [App Privacy Details](https://developer.apple.com/app-store/app-privacy-details/). diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/AnimationContainer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/AnimationContainer.swift new file mode 100644 index 0000000..46a864a --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/AnimationContainer.swift @@ -0,0 +1,216 @@ +// +// AnimationContainer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/24/19. +// + +import Foundation +import QuartzCore + +/** + The base animation container. + + This layer holds a single composition container and allows for animation of + the currentFrame property. + */ +final class AnimationContainer: CALayer { + + /// The animatable Current Frame Property + @NSManaged var currentFrame: CGFloat + + var imageProvider: AnimationImageProvider { + get { + return layerImageProvider.imageProvider + } + set { + layerImageProvider.imageProvider = newValue + } + } + + func reloadImages() { + layerImageProvider.reloadImages() + } + + var renderScale: CGFloat = 1 { + didSet { + animationLayers.forEach({ $0.renderScale = renderScale }) + } + } + + public var respectAnimationFrameRate: Bool = false + + /// Forces the view to update its drawing. + func forceDisplayUpdate() { + animationLayers.forEach( { $0.displayWithFrame(frame: currentFrame, forceUpdates: true) }) + } + + func logHierarchyKeypaths() { + print("Lottie: Logging Animation Keypaths") + animationLayers.forEach({ $0.logKeypaths(for: nil) }) + } + + func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) { + for layer in animationLayers { + if let foundProperties = layer.nodeProperties(for: keypath) { + for property in foundProperties { + property.setProvider(provider: valueProvider) + } + layer.displayWithFrame(frame: presentation()?.currentFrame ?? currentFrame, forceUpdates: true) + } + } + } + + func getValue(for keypath: AnimationKeypath, atFrame: CGFloat?) -> Any? { + for layer in animationLayers { + if let foundProperties = layer.nodeProperties(for: keypath), + let first = foundProperties.first { + return first.valueProvider.value(frame: atFrame ?? currentFrame) + } + } + return nil + } + + func layer(for keypath: AnimationKeypath) -> CALayer? { + for layer in animationLayers { + if let foundLayer = layer.layer(for: keypath) { + return foundLayer + } + } + return nil + } + + func animatorNodes(for keypath: AnimationKeypath) -> [AnimatorNode]? { + var results = [AnimatorNode]() + for layer in animationLayers { + if let nodes = layer.animatorNodes(for: keypath) { + results.append(contentsOf: nodes) + } + } + if results.count == 0 { + return nil + } + return results + } + + var textProvider: AnimationTextProvider { + get { return layerTextProvider.textProvider } + set { layerTextProvider.textProvider = newValue } + } + + var fontProvider: AnimationFontProvider { + get { return layerFontProvider.fontProvider } + set { layerFontProvider.fontProvider = newValue } + } + + var animationLayers: ContiguousArray + fileprivate let layerImageProvider: LayerImageProvider + fileprivate let layerTextProvider: LayerTextProvider + fileprivate let layerFontProvider: LayerFontProvider + + init(animation: Animation, imageProvider: AnimationImageProvider, textProvider: AnimationTextProvider, fontProvider: AnimationFontProvider) { + self.layerImageProvider = LayerImageProvider(imageProvider: imageProvider, assets: animation.assetLibrary?.imageAssets) + self.layerTextProvider = LayerTextProvider(textProvider: textProvider) + self.layerFontProvider = LayerFontProvider(fontProvider: fontProvider) + self.animationLayers = [] + super.init() + bounds = animation.bounds + let layers = animation.layers.initializeCompositionLayers(assetLibrary: animation.assetLibrary, layerImageProvider: layerImageProvider, textProvider: textProvider, fontProvider: fontProvider, frameRate: CGFloat(animation.framerate)) + + var imageLayers = [ImageCompositionLayer]() + var textLayers = [TextCompositionLayer]() + + var mattedLayer: CompositionLayer? = nil + + for layer in layers.reversed() { + layer.bounds = bounds + animationLayers.append(layer) + if let imageLayer = layer as? ImageCompositionLayer { + imageLayers.append(imageLayer) + } + if let textLayer = layer as? TextCompositionLayer { + textLayers.append(textLayer) + } + if let matte = mattedLayer { + /// The previous layer requires this layer to be its matte + matte.matteLayer = layer + mattedLayer = nil + continue + } + if let matte = layer.matteType, + (matte == .add || matte == .invert) { + /// We have a layer that requires a matte. + mattedLayer = layer + } + addSublayer(layer) + } + + layerImageProvider.addImageLayers(imageLayers) + layerImageProvider.reloadImages() + layerTextProvider.addTextLayers(textLayers) + layerTextProvider.reloadTexts() + layerFontProvider.addTextLayers(textLayers) + layerFontProvider.reloadTexts() + setNeedsDisplay() + } + + /// For CAAnimation Use + public override init(layer: Any) { + self.animationLayers = [] + self.layerImageProvider = LayerImageProvider(imageProvider: BlankImageProvider(), assets: nil) + self.layerTextProvider = LayerTextProvider(textProvider: DefaultTextProvider()) + self.layerFontProvider = LayerFontProvider(fontProvider: DefaultFontProvider()) + super.init(layer: layer) + + guard let animationLayer = layer as? AnimationContainer else { return } + + currentFrame = animationLayer.currentFrame + + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: CALayer Animations + + override public class func needsDisplay(forKey key: String) -> Bool { + if key == "currentFrame" { + return true + } + return super.needsDisplay(forKey: key) + } + + override public func action(forKey event: String) -> CAAction? { + if event == "currentFrame" { + let animation = CABasicAnimation(keyPath: event) + animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) + animation.fromValue = self.presentation()?.currentFrame + return animation + } + return super.action(forKey: event) + } + + public override func display() { + guard Thread.isMainThread else { return } + var newFrame: CGFloat + if let animationKeys = self.animationKeys(), + !animationKeys.isEmpty { + newFrame = self.presentation()?.currentFrame ?? self.currentFrame + } else { + // We ignore the presentation's frame if there's no animation in the layer. + newFrame = self.currentFrame + } + if respectAnimationFrameRate { + newFrame = floor(newFrame) + } + animationLayers.forEach( { $0.displayWithFrame(frame: newFrame, forceUpdates: false) }) + } + +} + +fileprivate class BlankImageProvider: AnimationImageProvider { + func imageForAsset(asset: ImageAsset) -> CGImage? { + return nil + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/CompositionLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/CompositionLayer.swift new file mode 100644 index 0000000..e99ec5d --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/CompositionLayer.swift @@ -0,0 +1,153 @@ +// +// LayerContainer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/22/19. +// + +import Foundation +import QuartzCore + +/** + The base class for a child layer of CompositionContainer + */ +class CompositionLayer: CALayer, KeypathSearchable { + + weak var layerDelegate: CompositionLayerDelegate? + + let transformNode: LayerTransformNode + + let contentsLayer: CALayer = CALayer() + + let maskLayer: MaskContainerLayer? + + let matteType: MatteType? + + var renderScale: CGFloat = 1 { + didSet { + self.updateRenderScale() + } + } + + var matteLayer: CompositionLayer? { + didSet { + if let matte = matteLayer { + if let type = matteType, type == .invert { + mask = InvertedMatteLayer(inputMatte: matte) + } else { + mask = matte + } + } else { + mask = nil + } + } + } + + let inFrame: CGFloat + let outFrame: CGFloat + let startFrame: CGFloat + let timeStretch: CGFloat + + init(layer: LayerModel, size: CGSize) { + self.transformNode = LayerTransformNode(transform: layer.transform) + if let masks = layer.masks { + maskLayer = MaskContainerLayer(masks: masks) + } else { + maskLayer = nil + } + self.matteType = layer.matte + self.inFrame = layer.inFrame.cgFloat + self.outFrame = layer.outFrame.cgFloat + self.timeStretch = layer.timeStretch.cgFloat + self.startFrame = layer.startTime.cgFloat + self.keypathName = layer.name + self.childKeypaths = [transformNode.transformProperties] + super.init() + self.anchorPoint = .zero + self.actions = [ + "opacity" : NSNull(), + "transform" : NSNull(), + "bounds" : NSNull(), + "anchorPoint" : NSNull(), + "sublayerTransform" : NSNull() + ] + + contentsLayer.anchorPoint = .zero + contentsLayer.bounds = CGRect(origin: .zero, size: size) + contentsLayer.actions = [ + "opacity" : NSNull(), + "transform" : NSNull(), + "bounds" : NSNull(), + "anchorPoint" : NSNull(), + "sublayerTransform" : NSNull(), + "hidden" : NSNull() + ] + addSublayer(contentsLayer) + + if let maskLayer = maskLayer { + contentsLayer.mask = maskLayer + } + } + + override init(layer: Any) { + /// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init + guard let layer = layer as? CompositionLayer else { + fatalError("Wrong Layer Class") + } + self.transformNode = layer.transformNode + self.matteType = layer.matteType + self.inFrame = layer.inFrame + self.outFrame = layer.outFrame + self.timeStretch = layer.timeStretch + self.startFrame = layer.startFrame + self.keypathName = layer.keypathName + self.childKeypaths = [transformNode.transformProperties] + self.maskLayer = nil + super.init(layer: layer) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + final func displayWithFrame(frame: CGFloat, forceUpdates: Bool) { + transformNode.updateTree(frame, forceUpdates: forceUpdates) + let layerVisible = frame.isInRangeOrEqual(inFrame, outFrame) + /// Only update contents if current time is within the layers time bounds. + if layerVisible { + displayContentsWithFrame(frame: frame, forceUpdates: forceUpdates) + maskLayer?.updateWithFrame(frame: frame, forceUpdates: forceUpdates) + } + contentsLayer.transform = transformNode.globalTransform + contentsLayer.opacity = transformNode.opacity + contentsLayer.isHidden = !layerVisible + layerDelegate?.frameUpdated(frame: frame) + } + + func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) { + /// To be overridden by subclass + } + + // MARK: Keypath Searchable + + let keypathName: String + + var keypathProperties: [String : AnyNodeProperty] { + return [:] + } + + final var childKeypaths: [KeypathSearchable] + + var keypathLayer: CALayer? { + return contentsLayer + } + + func updateRenderScale() { + /// To be overridden by subclass + } +} + +protocol CompositionLayerDelegate: AnyObject { + func frameUpdated(frame: CGFloat) +} + diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/ImageCompositionLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/ImageCompositionLayer.swift new file mode 100644 index 0000000..1f51b6b --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/ImageCompositionLayer.swift @@ -0,0 +1,47 @@ +// +// ImageCompositionLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import CoreGraphics +import QuartzCore + +final class ImageCompositionLayer: CompositionLayer { + + var image: CGImage? = nil { + didSet { + if let image = image { + contentsLayer.contents = image + } else { + contentsLayer.contents = nil + } + } + } + + let imageReferenceID: String + + init(imageLayer: ImageLayerModel, size: CGSize) { + self.imageReferenceID = imageLayer.referenceID + super.init(layer: imageLayer, size: size) + contentsLayer.masksToBounds = true + contentsLayer.contentsGravity = CALayerContentsGravity.resize + } + + override init(layer: Any) { + /// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init + guard let layer = layer as? ImageCompositionLayer else { + fatalError("init(layer:) Wrong Layer Class") + } + self.imageReferenceID = layer.imageReferenceID + self.image = nil + super.init(layer: layer) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/MaskContainerLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/MaskContainerLayer.swift new file mode 100644 index 0000000..753a8db --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/MaskContainerLayer.swift @@ -0,0 +1,168 @@ +// +// MaskContainerLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import QuartzCore + +extension MaskMode { + var usableMode: MaskMode { + switch self { + case .add: + return .add + case .subtract: + return .subtract + case .intersect: + return .intersect + case .lighten: + return .add + case .darken: + return .darken + case .difference: + return .intersect + case .none: + return .none + } + } +} + +final class MaskContainerLayer: CALayer { + + init(masks: [Mask]) { + super.init() + anchorPoint = .zero + var containerLayer = CALayer() + var firstObject: Bool = true + for mask in masks { + let maskLayer = MaskLayer(mask: mask) + maskLayers.append(maskLayer) + if mask.mode.usableMode == .none { + continue + } else if mask.mode.usableMode == .add || firstObject { + firstObject = false + containerLayer.addSublayer(maskLayer) + } else { + containerLayer.mask = maskLayer + let newContainer = CALayer() + newContainer.addSublayer(containerLayer) + containerLayer = newContainer + } + } + addSublayer(containerLayer) + } + + override init(layer: Any) { + /// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init + guard let layer = layer as? MaskContainerLayer else { + fatalError("init(layer:) Wrong Layer Class") + } + super.init(layer: layer) + } + + fileprivate var maskLayers: [MaskLayer] = [] + + func updateWithFrame(frame: CGFloat, forceUpdates: Bool) { + maskLayers.forEach({ $0.updateWithFrame(frame: frame, forceUpdates: forceUpdates) }) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +extension CGRect { + static var veryLargeRect: CGRect { + return CGRect(x: -100_000_000, + y: -100_000_000, + width: 200_000_000, + height: 200_000_000) + } +} + +fileprivate class MaskLayer: CALayer { + + let properties: MaskNodeProperties? + + let maskLayer = CAShapeLayer() + + init(mask: Mask) { + self.properties = MaskNodeProperties(mask: mask) + super.init() + addSublayer(maskLayer) + anchorPoint = .zero + maskLayer.fillColor = mask.mode == .add ? CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1, 0, 0, 1]) : + CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0, 1, 0, 1]) + maskLayer.fillRule = CAShapeLayerFillRule.evenOdd + self.actions = [ + "opacity" : NSNull() + ] + + } + + override init(layer: Any) { + self.properties = nil + super.init(layer: layer) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func updateWithFrame(frame: CGFloat, forceUpdates: Bool) { + guard let properties = properties else { return } + if properties.opacity.needsUpdate(frame: frame) || forceUpdates { + properties.opacity.update(frame: frame) + self.opacity = Float(properties.opacity.value.cgFloatValue) + } + + if properties.shape.needsUpdate(frame: frame) || forceUpdates { + properties.shape.update(frame: frame) + properties.expansion.update(frame: frame) + + let shapePath = properties.shape.value.cgPath() + var path = shapePath + if properties.mode.usableMode == .subtract && !properties.inverted || + (properties.mode.usableMode == .add && properties.inverted) { + /// Add a bounds rect to invert the mask + let newPath = CGMutablePath() + newPath.addRect(CGRect.veryLargeRect) + newPath.addPath(shapePath) + path = newPath + } + maskLayer.path = path + } + + } +} + +fileprivate class MaskNodeProperties: NodePropertyMap { + + var propertyMap: [String : AnyNodeProperty] + + var properties: [AnyNodeProperty] + + init(mask: Mask) { + self.mode = mask.mode + self.inverted = mask.inverted + self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: mask.opacity.keyframes)) + self.shape = NodeProperty(provider: KeyframeInterpolator(keyframes: mask.shape.keyframes)) + self.expansion = NodeProperty(provider: KeyframeInterpolator(keyframes: mask.expansion.keyframes)) + self.propertyMap = [ + "Opacity" : opacity, + "Shape" : shape, + "Expansion" : expansion + ] + self.properties = Array(self.propertyMap.values) + } + + let mode: MaskMode + let inverted: Bool + + let opacity: NodeProperty + let shape: NodeProperty + let expansion: NodeProperty +} + diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/NullCompositionLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/NullCompositionLayer.swift new file mode 100644 index 0000000..054e245 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/NullCompositionLayer.swift @@ -0,0 +1,28 @@ +// +// NullCompositionLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation + +final class NullCompositionLayer: CompositionLayer { + + init(layer: LayerModel) { + super.init(layer: layer, size: .zero) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override init(layer: Any) { + /// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init + guard let layer = layer as? NullCompositionLayer else { + fatalError("init(layer:) Wrong Layer Class") + } + super.init(layer: layer) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/PreCompositionLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/PreCompositionLayer.swift new file mode 100644 index 0000000..a1d36a5 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/PreCompositionLayer.swift @@ -0,0 +1,105 @@ +// +// PreCompositionLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import QuartzCore + +final class PreCompositionLayer: CompositionLayer { + + let frameRate: CGFloat + let remappingNode: NodeProperty? + fileprivate var animationLayers: [CompositionLayer] + + init(precomp: PreCompLayerModel, + asset: PrecompAsset, + layerImageProvider: LayerImageProvider, + textProvider: AnimationTextProvider, + fontProvider: AnimationFontProvider, + assetLibrary: AssetLibrary?, + frameRate: CGFloat) { + self.animationLayers = [] + if let keyframes = precomp.timeRemapping?.keyframes { + self.remappingNode = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframes)) + } else { + self.remappingNode = nil + } + self.frameRate = frameRate + super.init(layer: precomp, size: CGSize(width: precomp.width, height: precomp.height)) + bounds = CGRect(origin: .zero, size: CGSize(width: precomp.width, height: precomp.height)) + contentsLayer.masksToBounds = true + contentsLayer.bounds = bounds + + let layers = asset.layers.initializeCompositionLayers(assetLibrary: assetLibrary, layerImageProvider: layerImageProvider, textProvider: textProvider, fontProvider: fontProvider, frameRate: frameRate) + + var imageLayers = [ImageCompositionLayer]() + + var mattedLayer: CompositionLayer? = nil + + for layer in layers.reversed() { + layer.bounds = bounds + animationLayers.append(layer) + if let imageLayer = layer as? ImageCompositionLayer { + imageLayers.append(imageLayer) + } + if let matte = mattedLayer { + /// The previous layer requires this layer to be its matte + matte.matteLayer = layer + mattedLayer = nil + continue + } + if let matte = layer.matteType, + (matte == .add || matte == .invert) { + /// We have a layer that requires a matte. + mattedLayer = layer + } + contentsLayer.addSublayer(layer) + } + + self.childKeypaths.append(contentsOf: layers) + + layerImageProvider.addImageLayers(imageLayers) + } + + override init(layer: Any) { + /// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init + guard let layer = layer as? PreCompositionLayer else { + fatalError("init(layer:) Wrong Layer Class") + } + self.frameRate = layer.frameRate + self.remappingNode = nil + self.animationLayers = [] + + super.init(layer: layer) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) { + let localFrame: CGFloat + if let remappingNode = remappingNode { + remappingNode.update(frame: frame) + localFrame = remappingNode.value.cgFloatValue * frameRate + } else { + localFrame = (frame - startFrame) / timeStretch + } + animationLayers.forEach( { $0.displayWithFrame(frame: localFrame, forceUpdates: forceUpdates) }) + } + + override var keypathProperties: [String : AnyNodeProperty] { + guard let remappingNode = remappingNode else { + return super.keypathProperties + } + return ["Time Remap" : remappingNode] + } + + override func updateRenderScale() { + super.updateRenderScale() + animationLayers.forEach( { $0.renderScale = renderScale } ) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/ShapeCompositionLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/ShapeCompositionLayer.swift new file mode 100644 index 0000000..7a4616d --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/ShapeCompositionLayer.swift @@ -0,0 +1,56 @@ +// +// ShapeLayerContainer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/22/19. +// + +import Foundation +import CoreGraphics + +/** + A CompositionLayer responsible for initializing and rendering shapes + */ +final class ShapeCompositionLayer: CompositionLayer { + + let rootNode: AnimatorNode? + let renderContainer: ShapeContainerLayer? + + init(shapeLayer: ShapeLayerModel) { + let results = shapeLayer.items.initializeNodeTree() + let renderContainer = ShapeContainerLayer() + self.renderContainer = renderContainer + self.rootNode = results.rootNode + super.init(layer: shapeLayer, size: .zero) + contentsLayer.addSublayer(renderContainer) + for container in results.renderContainers { + renderContainer.insertRenderLayer(container) + } + rootNode?.updateTree(0, forceUpdates: true) + self.childKeypaths.append(contentsOf: results.childrenNodes) + } + + override init(layer: Any) { + guard let layer = layer as? ShapeCompositionLayer else { + fatalError("init(layer:) wrong class.") + } + self.rootNode = nil + self.renderContainer = nil + super.init(layer: layer) + } + + override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) { + rootNode?.updateTree(frame, forceUpdates: forceUpdates) + renderContainer?.markRenderUpdates(forFrame: frame) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func updateRenderScale() { + super.updateRenderScale() + renderContainer?.renderScale = renderScale + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/SolidCompositionLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/SolidCompositionLayer.swift new file mode 100644 index 0000000..6568c35 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/SolidCompositionLayer.swift @@ -0,0 +1,48 @@ +// +// SolidCompositionLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import QuartzCore + +final class SolidCompositionLayer: CompositionLayer { + + let colorProperty: NodeProperty? + let solidShape: CAShapeLayer = CAShapeLayer() + + init(solid: SolidLayerModel) { + let components = solid.colorHex.hexColorComponents() + self.colorProperty = NodeProperty(provider: SingleValueProvider(Color(r: Double(components.red), g: Double(components.green), b: Double(components.blue), a: 1))) + + super.init(layer: solid, size: .zero) + solidShape.path = CGPath(rect: CGRect(x: 0, y: 0, width: solid.width, height: solid.height), transform: nil) + contentsLayer.addSublayer(solidShape) + } + + override init(layer: Any) { + /// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init + guard let layer = layer as? SolidCompositionLayer else { + fatalError("init(layer:) Wrong Layer Class") + } + self.colorProperty = layer.colorProperty + super.init(layer: layer) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) { + guard let colorProperty = colorProperty else { return } + colorProperty.update(frame: frame) + solidShape.fillColor = colorProperty.value.cgColorValue + } + + override var keypathProperties: [String : AnyNodeProperty] { + guard let colorProperty = colorProperty else { return super.keypathProperties } + return ["Color" : colorProperty] + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/TextCompositionLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/TextCompositionLayer.swift new file mode 100644 index 0000000..8f29cc6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/TextCompositionLayer.swift @@ -0,0 +1,143 @@ +// +// TextCompositionLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import CoreGraphics +import QuartzCore +import CoreText + +/// Needed for NSMutableParagraphStyle... +#if os(OSX) +import AppKit +#else +import UIKit +#endif + +extension TextJustification { + var textAlignment: NSTextAlignment { + switch self { + case .left: + return .left + case .right: + return .right + case .center: + return .center + } + } + + var caTextAlignement: CATextLayerAlignmentMode { + switch self { + case .left: + return .left + case .right: + return .right + case .center: + return .center + } + } +} + +final class TextCompositionLayer: CompositionLayer { + + let rootNode: TextAnimatorNode? + let textDocument: KeyframeInterpolator? + + let textLayer: TextLayer = TextLayer() + var textProvider: AnimationTextProvider + var fontProvider: AnimationFontProvider + + init(textLayer: TextLayerModel, textProvider: AnimationTextProvider, fontProvider: AnimationFontProvider) { + var rootNode: TextAnimatorNode? + for animator in textLayer.animators { + rootNode = TextAnimatorNode(parentNode: rootNode, textAnimator: animator) + } + self.rootNode = rootNode + self.textDocument = KeyframeInterpolator(keyframes: textLayer.text.keyframes) + + self.textProvider = textProvider + self.fontProvider = fontProvider + + super.init(layer: textLayer, size: .zero) + contentsLayer.addSublayer(self.textLayer) + self.textLayer.masksToBounds = false + self.textLayer.isGeometryFlipped = true + + if let rootNode = rootNode { + childKeypaths.append(rootNode) + } + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override init(layer: Any) { + /// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init + guard let layer = layer as? TextCompositionLayer else { + fatalError("init(layer:) Wrong Layer Class") + } + self.rootNode = nil + self.textDocument = nil + + self.textProvider = DefaultTextProvider() + self.fontProvider = DefaultFontProvider() + + super.init(layer: layer) + } + + override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) { + guard let textDocument = textDocument else { return } + + textLayer.contentsScale = self.renderScale + + let documentUpdate = textDocument.hasUpdate(frame: frame) + let animatorUpdate = rootNode?.updateContents(frame, forceLocalUpdate: forceUpdates) ?? false + guard documentUpdate == true || animatorUpdate == true else { return } + + rootNode?.rebuildOutputs(frame: frame) + + // Get Text Attributes + let text = textDocument.value(frame: frame) as! TextDocument + let strokeColor = rootNode?.textOutputNode.strokeColor ?? text.strokeColorData?.cgColorValue + let strokeWidth = rootNode?.textOutputNode.strokeWidth ?? CGFloat(text.strokeWidth ?? 0) + let tracking = (CGFloat(text.fontSize) * (rootNode?.textOutputNode.tracking ?? CGFloat(text.tracking))) / 1000.0 + let matrix = rootNode?.textOutputNode.xform ?? CATransform3DIdentity + let textString = textProvider.textFor(keypathName: self.keypathName, sourceText: text.text) + let ctFont = fontProvider.fontFor(family: text.fontFamily, size: CGFloat(text.fontSize)) + + // Set all of the text layer options + textLayer.text = textString + textLayer.font = ctFont + textLayer.alignment = text.justification.textAlignment + textLayer.lineHeight = CGFloat(text.lineHeight) + textLayer.tracking = tracking + + if let fillColor = rootNode?.textOutputNode.fillColor { + textLayer.fillColor = fillColor + } else if let fillColor = text.fillColorData?.cgColorValue { + textLayer.fillColor = fillColor + } else { + textLayer.fillColor = nil + } + + textLayer.preferredSize = text.textFrameSize?.sizeValue + textLayer.strokeOnTop = text.strokeOverFill ?? false + textLayer.strokeWidth = strokeWidth + textLayer.strokeColor = strokeColor + textLayer.sizeToFit() + + textLayer.opacity = Float(rootNode?.textOutputNode.opacity ?? 1) + textLayer.transform = CATransform3DIdentity + textLayer.position = text.textFramePosition?.pointValue ?? CGPoint.zero + textLayer.transform = matrix + } + + override func updateRenderScale() { + super.updateRenderScale() + textLayer.contentsScale = self.renderScale + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/CompositionLayersInitializer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/CompositionLayersInitializer.swift new file mode 100644 index 0000000..de69bef --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/CompositionLayersInitializer.swift @@ -0,0 +1,81 @@ +// +// CompositionLayersInitializer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import CoreGraphics + +extension Array where Element == LayerModel { + + func initializeCompositionLayers(assetLibrary: AssetLibrary?, + layerImageProvider: LayerImageProvider, + textProvider: AnimationTextProvider, + fontProvider: AnimationFontProvider, + frameRate: CGFloat) -> [CompositionLayer] { + var compositionLayers = [CompositionLayer]() + var layerMap = [Int : CompositionLayer]() + + /// Organize the assets into a dictionary of [ID : ImageAsset] + var childLayers = [LayerModel]() + + for layer in self { + if layer.hidden == true { + let genericLayer = NullCompositionLayer(layer: layer) + compositionLayers.append(genericLayer) + layerMap[layer.index] = genericLayer + } else if let shapeLayer = layer as? ShapeLayerModel { + let shapeContainer = ShapeCompositionLayer(shapeLayer: shapeLayer) + compositionLayers.append(shapeContainer) + layerMap[layer.index] = shapeContainer + } else if let solidLayer = layer as? SolidLayerModel { + let solidContainer = SolidCompositionLayer(solid: solidLayer) + compositionLayers.append(solidContainer) + layerMap[layer.index] = solidContainer + } else if let precompLayer = layer as? PreCompLayerModel, + let assetLibrary = assetLibrary, + let precompAsset = assetLibrary.precompAssets[precompLayer.referenceID] { + let precompContainer = PreCompositionLayer(precomp: precompLayer, + asset: precompAsset, + layerImageProvider: layerImageProvider, + textProvider: textProvider, + fontProvider: fontProvider, + assetLibrary: assetLibrary, + frameRate: frameRate) + compositionLayers.append(precompContainer) + layerMap[layer.index] = precompContainer + } else if let imageLayer = layer as? ImageLayerModel, + let assetLibrary = assetLibrary, + let imageAsset = assetLibrary.imageAssets[imageLayer.referenceID] { + let imageContainer = ImageCompositionLayer(imageLayer: imageLayer, size: CGSize(width: imageAsset.width, height: imageAsset.height)) + compositionLayers.append(imageContainer) + layerMap[layer.index] = imageContainer + } else if let textLayer = layer as? TextLayerModel { + let textContainer = TextCompositionLayer(textLayer: textLayer, textProvider: textProvider, fontProvider: fontProvider) + compositionLayers.append(textContainer) + layerMap[layer.index] = textContainer + } else { + let genericLayer = NullCompositionLayer(layer: layer) + compositionLayers.append(genericLayer) + layerMap[layer.index] = genericLayer + } + if layer.parent != nil { + childLayers.append(layer) + } + } + + /// Now link children with their parents + for layerModel in childLayers { + if let parentID = layerModel.parent { + let childLayer = layerMap[layerModel.index] + let parentLayer = layerMap[parentID] + childLayer?.transformNode.parentNode = parentLayer?.transformNode + } + } + + return compositionLayers + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/InvertedMatteLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/InvertedMatteLayer.swift new file mode 100644 index 0000000..17e7921 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/InvertedMatteLayer.swift @@ -0,0 +1,57 @@ +// +// InvertedMatteLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/28/19. +// + +import Foundation +import QuartzCore + +/** + A layer that inverses the alpha output of its input layer. + + WARNING: This is experimental and probably not very performant. + */ +final class InvertedMatteLayer: CALayer, CompositionLayerDelegate { + + let inputMatte: CompositionLayer? + let wrapperLayer = CALayer() + + init(inputMatte: CompositionLayer) { + self.inputMatte = inputMatte + super.init() + inputMatte.layerDelegate = self + self.anchorPoint = .zero + self.bounds = inputMatte.bounds + self.setNeedsDisplay() + } + + override init(layer: Any) { + guard let layer = layer as? InvertedMatteLayer else { + fatalError("init(layer:) wrong class.") + } + self.inputMatte = nil + super.init(layer: layer) + } + + func frameUpdated(frame: CGFloat) { + self.setNeedsDisplay() + self.displayIfNeeded() + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func draw(in ctx: CGContext) { + guard let inputMatte = inputMatte else { return } + guard let fillColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0, 0, 0, 1]) + else { return } + ctx.setFillColor(fillColor) + ctx.fill(bounds) + ctx.setBlendMode(.destinationOut) + inputMatte.render(in: ctx) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerFontProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerFontProvider.swift new file mode 100644 index 0000000..39e7336 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerFontProvider.swift @@ -0,0 +1,37 @@ +// +// LayerFontProvider.swift +// Lottie +// +// Created by Brandon Withrow on 8/5/20. +// Copyright © 2020 YurtvilleProds. All rights reserved. +// + +import Foundation + +/// Connects a LottieFontProvider to a group of text layers +final class LayerFontProvider { + + var fontProvider: AnimationFontProvider { + didSet { + reloadTexts() + } + } + + fileprivate(set) var textLayers: [TextCompositionLayer] + + init(fontProvider: AnimationFontProvider) { + self.fontProvider = fontProvider + self.textLayers = [] + reloadTexts() + } + + func addTextLayers(_ layers: [TextCompositionLayer]) { + textLayers += layers + } + + func reloadTexts() { + textLayers.forEach { + $0.fontProvider = fontProvider + } + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerImageProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerImageProvider.swift new file mode 100644 index 0000000..cb9bdb9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerImageProvider.swift @@ -0,0 +1,49 @@ +// +// LayerImageProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation + +/// Connects a LottieImageProvider to a group of image layers +final class LayerImageProvider { + + var imageProvider: AnimationImageProvider { + didSet { + reloadImages() + } + } + + fileprivate(set) var imageLayers: [ImageCompositionLayer] + let imageAssets: [String : ImageAsset] + + init(imageProvider: AnimationImageProvider, assets: [String : ImageAsset]?) { + self.imageProvider = imageProvider + self.imageLayers = [ImageCompositionLayer]() + if let assets = assets { + self.imageAssets = assets + } else { + self.imageAssets = [:] + } + reloadImages() + } + + func addImageLayers(_ layers: [ImageCompositionLayer]) { + for layer in layers { + if imageAssets[layer.imageReferenceID] != nil { + /// Found a linking asset in our asset library. Add layer + imageLayers.append(layer) + } + } + } + + func reloadImages() { + for imageLayer in imageLayers { + if let asset = imageAssets[imageLayer.imageReferenceID] { + imageLayer.image = imageProvider.imageForAsset(asset: asset) + } + } + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerTextProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerTextProvider.swift new file mode 100644 index 0000000..3435abb --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerTextProvider.swift @@ -0,0 +1,36 @@ +// +// LayerTextProvider.swift +// lottie-ios-iOS +// +// Created by Alexandr Goncharov on 07/06/2019. +// + +import Foundation + +/// Connects a LottieTextProvider to a group of text layers +final class LayerTextProvider { + + var textProvider: AnimationTextProvider { + didSet { + reloadTexts() + } + } + + fileprivate(set) var textLayers: [TextCompositionLayer] + + init(textProvider: AnimationTextProvider) { + self.textProvider = textProvider + self.textLayers = [] + reloadTexts() + } + + func addTextLayers(_ layers: [TextCompositionLayer]) { + textLayers += layers + } + + func reloadTexts() { + textLayers.forEach { + $0.textProvider = textProvider + } + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerTransformNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerTransformNode.swift new file mode 100644 index 0000000..dd95294 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/LayerTransformNode.swift @@ -0,0 +1,128 @@ +// +// LayerTransformPropertyMap.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +import CoreGraphics +import QuartzCore + +final class LayerTransformProperties: NodePropertyMap, KeypathSearchable { + + init(transform: Transform) { + + self.anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.anchorPoint.keyframes)) + self.scale = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.scale.keyframes)) + self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotation.keyframes)) + self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.opacity.keyframes)) + + var propertyMap: [String: AnyNodeProperty] = [ + "Anchor Point" : anchor, + "Scale" : scale, + "Rotation" : rotation, + "Opacity" : opacity + ] + + if let positionKeyframesX = transform.positionX?.keyframes, + let positionKeyframesY = transform.positionY?.keyframes { + let xPosition: NodeProperty = NodeProperty(provider: KeyframeInterpolator(keyframes: positionKeyframesX)) + let yPosition: NodeProperty = NodeProperty(provider: KeyframeInterpolator(keyframes: positionKeyframesY)) + propertyMap["X Position"] = xPosition + propertyMap["Y Position"] = yPosition + self.positionX = xPosition + self.positionY = yPosition + self.position = nil + } else if let positionKeyframes = transform.position?.keyframes { + let position: NodeProperty = NodeProperty(provider: KeyframeInterpolator(keyframes: positionKeyframes)) + propertyMap["Position"] = position + self.position = position + self.positionX = nil + self.positionY = nil + } else { + self.position = nil + self.positionY = nil + self.positionX = nil + } + + self.keypathProperties = propertyMap + self.properties = Array(propertyMap.values) + } + + let keypathProperties: [String : AnyNodeProperty] + var keypathName: String = "Transform" + + var childKeypaths: [KeypathSearchable] { + return [] + } + + let properties: [AnyNodeProperty] + + let anchor: NodeProperty + let scale: NodeProperty + let rotation: NodeProperty + let position: NodeProperty? + let positionX: NodeProperty? + let positionY: NodeProperty? + let opacity: NodeProperty + +} + +class LayerTransformNode: AnimatorNode { + let outputNode: NodeOutput = PassThroughOutputNode(parent: nil) + + init(transform: Transform) { + self.transformProperties = LayerTransformProperties(transform: transform) + } + + let transformProperties: LayerTransformProperties + + // MARK: Animator Node Protocol + + var propertyMap: NodePropertyMap & KeypathSearchable { + return transformProperties + } + + var parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true + + func shouldRebuildOutputs(frame: CGFloat) -> Bool { + return hasLocalUpdates || hasUpstreamUpdates + } + + func rebuildOutputs(frame: CGFloat) { + opacity = Float(transformProperties.opacity.value.cgFloatValue) * 0.01 + + let position: CGPoint + if let point = transformProperties.position?.value.pointValue { + position = point + } else if let xPos = transformProperties.positionX?.value.cgFloatValue, + let yPos = transformProperties.positionY?.value.cgFloatValue { + position = CGPoint(x: xPos, y: yPos) + } else { + position = .zero + } + + localTransform = CATransform3D.makeTransform(anchor: transformProperties.anchor.value.pointValue, + position: position, + scale: transformProperties.scale.value.sizeValue, + rotation: transformProperties.rotation.value.cgFloatValue, + skew: nil, + skewAxis: nil) + + if let parentNode = parentNode as? LayerTransformNode { + globalTransform = CATransform3DConcat(localTransform, parentNode.globalTransform) + } else { + globalTransform = localTransform + } + } + + var opacity: Float = 1 + var localTransform: CATransform3D = CATransform3DIdentity + var globalTransform: CATransform3D = CATransform3DIdentity + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/TextLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/TextLayer.swift new file mode 100644 index 0000000..5b949ff --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/Utility/TextLayer.swift @@ -0,0 +1,306 @@ +// +// TextLayer.swift +// Pods +// +// Created by Brandon Withrow on 8/3/20. +// + +import Foundation +import CoreText +import QuartzCore +import CoreGraphics +/// Needed for NSMutableParagraphStyle... +#if os(OSX) +import AppKit +#else +import UIKit +#endif + +final class TextLayer: CALayer { + + public var text: String? { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var font: CTFont? { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var alignment: NSTextAlignment = .left { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var lineHeight: CGFloat = 0 { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var tracking: CGFloat = 0 { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var fillColor: CGColor? { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var strokeColor: CGColor? { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var strokeWidth: CGFloat = 0 { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var strokeOnTop: Bool = false { + didSet { + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public var preferredSize: CGSize? { + didSet { + needsContentUpdate = true + self.setNeedsLayout() + self.setNeedsDisplay() + } + } + + public func sizeToFit() { + updateTextContent() + bounds = drawingRect + anchorPoint = drawingAnchor + self.setNeedsLayout() + self.setNeedsDisplay() + } + + override func action(forKey event: String) -> CAAction? { + return nil + } + + // Draws Debug colors for the font alignment. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + private func drawDebug(_ ctx: CGContext) { + if let font = font { + let ascent = CTFontGetAscent(font) + let descent = CTFontGetDescent(font) + let capHeight = CTFontGetCapHeight(font) + let leading = CTFontGetLeading(font) + + // Ascent Red + ctx.setFillColor(CGColor(srgbRed: 1, green: 0, blue: 0, alpha: 0.5)) + ctx.fill(CGRect(x:0, y:0, width:drawingRect.width, height:ascent)) + + // Descent Blue + ctx.setFillColor(CGColor(srgbRed: 0, green: 0, blue: 1, alpha: 0.5)) + ctx.fill(CGRect(x:0, y:ascent, width:drawingRect.width, height:descent)) + + // Leading Yellow + ctx.setFillColor(CGColor(srgbRed: 1, green: 1, blue: 0, alpha: 0.5)) + ctx.fill(CGRect(x:0, y:ascent+descent, width:drawingRect.width, height:leading)) + + // Cap height Green + ctx.setFillColor(CGColor(srgbRed: 0, green: 1, blue: 0, alpha: 0.5)) + ctx.fill(CGRect(x:0, y:ascent - capHeight, width:drawingRect.width, height:capHeight)) + + if drawingRect.height - ascent+descent+leading > 0 { + // Remainder + ctx.setFillColor(CGColor(srgbRed: 0, green: 1, blue: 1, alpha: 0.5)) + ctx.fill(CGRect(x:0, y:ascent+descent+leading, width:drawingRect.width, height:drawingRect.height - ascent+descent+leading)) + } + } + } + + override func draw(in ctx: CGContext) { + guard let attributedString = attributedString else { return } + updateTextContent() + guard fillFrameSetter != nil || strokeFrameSetter != nil else { return } + + ctx.textMatrix = .identity + ctx.setAllowsAntialiasing(true) + ctx.setAllowsFontSmoothing(true) + ctx.setAllowsFontSubpixelPositioning(true) + ctx.setAllowsFontSubpixelQuantization(true) + + ctx.setShouldAntialias(true) + ctx.setShouldSmoothFonts(true) + ctx.setShouldSubpixelPositionFonts(true) + ctx.setShouldSubpixelQuantizeFonts(true) + + if self.contentsAreFlipped() { + ctx.translateBy(x: 0, y: drawingRect.height) + ctx.scaleBy(x: 1.0, y: -1.0) + } + + let drawingPath = CGPath(rect: drawingRect, transform: nil) + + let fillFrame: CTFrame? + if let setter = fillFrameSetter { + fillFrame = CTFramesetterCreateFrame(setter, CFRangeMake(0, attributedString.length), drawingPath, nil) + } else { + fillFrame = nil + } + + let strokeFrame: CTFrame? + if let setter = strokeFrameSetter { + strokeFrame = CTFramesetterCreateFrame(setter, CFRangeMake(0, attributedString.length), drawingPath, nil) + } else { + strokeFrame = nil + } + + + if !strokeOnTop, let strokeFrame = strokeFrame { + CTFrameDraw(strokeFrame, ctx) + } + + if let fillFrame = fillFrame { + CTFrameDraw(fillFrame, ctx) + } + + if strokeOnTop, let strokeFrame = strokeFrame { + CTFrameDraw(strokeFrame, ctx) + } + } + + private var drawingRect: CGRect = .zero + private var drawingAnchor: CGPoint = .zero + private var fillFrameSetter: CTFramesetter? + private var attributedString: NSAttributedString? + private var strokeFrameSetter: CTFramesetter? + private var needsContentUpdate: Bool = false + + private func updateTextContent() { + guard needsContentUpdate else { return } + needsContentUpdate = false + guard let font = font, let text = text, text.count > 0, (fillColor != nil || strokeColor != nil) else { + drawingRect = .zero + drawingAnchor = .zero + attributedString = nil + fillFrameSetter = nil + strokeFrameSetter = nil + return + } + + // Get Font properties + let ascent = CTFontGetAscent(font) + let descent = CTFontGetDescent(font) + let capHeight = CTFontGetCapHeight(font) + let leading = CTFontGetLeading(font) + let minLineHeight = -(ascent + descent + leading) + + // Calculate line spacing + let lineSpacing = max(CGFloat(minLineHeight) + lineHeight, CGFloat(minLineHeight)) + // Build Attributes + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineSpacing = lineSpacing + paragraphStyle.lineHeightMultiple = 1 + paragraphStyle.maximumLineHeight = ascent+descent+leading + paragraphStyle.alignment = alignment + paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping + var attributes: [NSAttributedString.Key : Any] = [ + NSAttributedString.Key.ligature: 0, + NSAttributedString.Key.font: font, + NSAttributedString.Key.kern: tracking, + NSAttributedString.Key.paragraphStyle: paragraphStyle + ] + + if let fillColor = fillColor { + attributes[NSAttributedString.Key.foregroundColor] = fillColor + } + + let attrString = NSAttributedString(string: text, attributes: attributes) + attributedString = attrString + + if fillColor != nil { + let setter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString) + fillFrameSetter = setter + } else { + fillFrameSetter = nil + } + + if let strokeColor = strokeColor { + attributes[NSAttributedString.Key.foregroundColor] = nil + attributes[NSAttributedString.Key.strokeWidth] = strokeWidth + attributes[NSAttributedString.Key.strokeColor] = strokeColor + let strokeAttributedString = NSAttributedString(string: text, attributes: attributes) + strokeFrameSetter = CTFramesetterCreateWithAttributedString(strokeAttributedString as CFAttributedString) + } else { + strokeFrameSetter = nil + strokeWidth = 0 + } + + guard let setter = fillFrameSetter ?? strokeFrameSetter else { + return + } + + // Calculate drawing size and anchor offset + let textAnchor: CGPoint + if let preferredSize = preferredSize { + drawingRect = CGRect(origin: .zero, size: preferredSize) + drawingRect.size.height += (ascent - capHeight) + drawingRect.size.height += descent + textAnchor = CGPoint(x: 0, y: (ascent-capHeight)) + } else { + let size = CTFramesetterSuggestFrameSizeWithConstraints( + setter, + CFRange(location: 0, length: attrString.length), + nil, + CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), + nil + ) + switch alignment { + case .left: + textAnchor = CGPoint(x: 0, y: ascent) + case .right: + textAnchor = CGPoint(x: size.width, y: ascent) + case .center: + textAnchor = CGPoint(x: size.width * 0.5, y: ascent) + default: + textAnchor = .zero + } + drawingRect = CGRect(x: 0, y: 0, width: ceil(size.width), + height: ceil(size.height)) + } + + // Now Calculate Anchor + drawingAnchor = CGPoint(x: textAnchor.x.remap(fromLow: 0, fromHigh: drawingRect.size.width, toLow: 0, toHigh: 1), + y: textAnchor.y.remap(fromLow: 0, fromHigh: drawingRect.size.height, toLow: 0, toHigh: 1)) + + if fillFrameSetter != nil && strokeFrameSetter != nil { + drawingRect.size.width += strokeWidth + drawingRect.size.height += strokeWidth + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Animation.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Animation.swift new file mode 100644 index 0000000..2ba1032 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Animation.swift @@ -0,0 +1,107 @@ +// +// Animation.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/7/19. +// + +import Foundation + +public enum CoordinateSpace: Int, Codable { + case type2d + case type3d +} + +/** + The `Animation` model is the top level model object in Lottie. + + An `Animation` holds all of the animation data backing a Lottie Animation. + Codable, see JSON schema [here](https://github.com/airbnb/lottie-web/tree/master/docs/json). + */ +public final class Animation: Codable { + + /// The version of the JSON Schema. + let version: String + + /// The coordinate space of the composition. + let type: CoordinateSpace + + /// The start time of the composition in frameTime. + public let startFrame: AnimationFrameTime + + /// The end time of the composition in frameTime. + public let endFrame: AnimationFrameTime + + /// The frame rate of the composition. + public let framerate: Double + + /// The height of the composition in points. + let width: Int + + /// The width of the composition in points. + let height: Int + + /// The list of animation layers + let layers: [LayerModel] + + /// The list of glyphs used for text rendering + let glyphs: [Glyph]? + + /// The list of fonts used for text rendering + let fonts: FontList? + + /// Asset Library + let assetLibrary: AssetLibrary? + + /// Markers + let markers: [Marker]? + let markerMap: [String : Marker]? + + /// Return all marker names, in order, or an empty list if none are specified + public var markerNames: [String] { + guard let markers = markers else { return [] } + return markers.map { $0.name } + } + + enum CodingKeys : String, CodingKey { + case version = "v" + case type = "ddd" + case startFrame = "ip" + case endFrame = "op" + case framerate = "fr" + case width = "w" + case height = "h" + case layers = "layers" + case glyphs = "chars" + case fonts = "fonts" + case assetLibrary = "assets" + case markers = "markers" + } + + required public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Animation.CodingKeys.self) + self.version = try container.decode(String.self, forKey: .version) + self.type = try container.decodeIfPresent(CoordinateSpace.self, forKey: .type) ?? .type2d + self.startFrame = try container.decode(AnimationFrameTime.self, forKey: .startFrame) + self.endFrame = try container.decode(AnimationFrameTime.self, forKey: .endFrame) + self.framerate = try container.decode(Double.self, forKey: .framerate) + self.width = try container.decode(Int.self, forKey: .width) + self.height = try container.decode(Int.self, forKey: .height) + self.layers = try container.decode([LayerModel].self, ofFamily: LayerType.self, forKey: .layers) + self.glyphs = try container.decodeIfPresent([Glyph].self, forKey: .glyphs) + self.fonts = try container.decodeIfPresent(FontList.self, forKey: .fonts) + self.assetLibrary = try container.decodeIfPresent(AssetLibrary.self, forKey: .assetLibrary) + self.markers = try container.decodeIfPresent([Marker].self, forKey: .markers) + + if let markers = markers { + var markerMap: [String : Marker] = [:] + for marker in markers { + markerMap[marker.name] = marker + } + self.markerMap = markerMap + } else { + self.markerMap = nil + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/Asset.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/Asset.swift new file mode 100644 index 0000000..85d47f8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/Asset.swift @@ -0,0 +1,27 @@ +// +// Asset.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +public class Asset: Codable { + + /// The ID of the asset + public let id: String + + private enum CodingKeys : String, CodingKey { + case id = "id" + } + + required public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Asset.CodingKeys.self) + if let id = try? container.decode(String.self, forKey: .id) { + self.id = id + } else { + self.id = String(try container.decode(Int.self, forKey: .id)) + } + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/AssetLibrary.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/AssetLibrary.swift new file mode 100644 index 0000000..d9dbf90 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/AssetLibrary.swift @@ -0,0 +1,48 @@ +// +// AssetLibrary.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +final class AssetLibrary: Codable { + + /// The Assets + let assets: [String : Asset] + + let imageAssets: [String : ImageAsset] + let precompAssets: [String : PrecompAsset] + + required init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + var containerForKeys = container + + var decodedAssets = [String : Asset]() + + var imageAssets = [String : ImageAsset]() + var precompAssets = [String : PrecompAsset]() + + while !container.isAtEnd { + let keyContainer = try containerForKeys.nestedContainer(keyedBy: PrecompAsset.CodingKeys.self) + if keyContainer.contains(.layers) { + let precompAsset = try container.decode(PrecompAsset.self) + decodedAssets[precompAsset.id] = precompAsset + precompAssets[precompAsset.id] = precompAsset + } else { + let imageAsset = try container.decode(ImageAsset.self) + decodedAssets[imageAsset.id] = imageAsset + imageAssets[imageAsset.id] = imageAsset + } + } + self.assets = decodedAssets + self.precompAssets = precompAssets + self.imageAssets = imageAssets + } + + func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(contentsOf: Array(assets.values)) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/ImageAsset.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/ImageAsset.swift new file mode 100644 index 0000000..aeff137 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/ImageAsset.swift @@ -0,0 +1,48 @@ +// +// ImageAsset.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +public final class ImageAsset: Asset { + + /// Image name + public let name: String + + /// Image Directory + public let directory: String + + /// Image Size + public let width: Double + + public let height: Double + + enum CodingKeys : String, CodingKey { + case name = "p" + case directory = "u" + case width = "w" + case height = "h" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: ImageAsset.CodingKeys.self) + self.name = try container.decode(String.self, forKey: .name) + self.directory = try container.decode(String.self, forKey: .directory) + self.width = try container.decode(Double.self, forKey: .width) + self.height = try container.decode(Double.self, forKey: .height) + try super.init(from: decoder) + } + + override public func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(directory, forKey: .directory) + try container.encode(width, forKey: .width) + try container.encode(height, forKey: .height) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/PrecompAsset.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/PrecompAsset.swift new file mode 100644 index 0000000..963e0bb --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/PrecompAsset.swift @@ -0,0 +1,30 @@ +// +// PrecompAsset.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +final class PrecompAsset: Asset { + + /// Layers of the precomp + let layers: [LayerModel] + + enum CodingKeys : String, CodingKey { + case layers = "layers" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: PrecompAsset.CodingKeys.self) + self.layers = try container.decode([LayerModel].self, ofFamily: LayerType.self, forKey: .layers) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(layers, forKey: .layers) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Extensions/KeyedDecodingContainerExtensions.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Extensions/KeyedDecodingContainerExtensions.swift new file mode 100644 index 0000000..29fe104 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Extensions/KeyedDecodingContainerExtensions.swift @@ -0,0 +1,40 @@ +// From: https://medium.com/@kewindannerfjordremeczki/swift-4-0-decodable-heterogeneous-collections-ecc0e6b468cf + +import Foundation + +/// To support a new class family, create an enum that conforms to this protocol and contains the different types. +protocol ClassFamily: Decodable { + /// The discriminator key. + static var discriminator: Discriminator { get } + + /// Returns the class type of the object corresponding to the value. + func getType() -> AnyObject.Type +} + +/// Discriminator key enum used to retrieve discriminator fields in JSON payloads. +enum Discriminator: String, CodingKey { + case type = "ty" +} + +extension KeyedDecodingContainer { + + /// Decode a heterogeneous list of objects for a given family. + /// - Parameters: + /// - heterogeneousType: The decodable type of the list. + /// - family: The ClassFamily enum for the type family. + /// - key: The CodingKey to look up the list in the current container. + /// - Returns: The resulting list of heterogeneousType elements. + func decode(_ heterogeneousType: [T].Type, ofFamily family: U.Type, forKey key: K) throws -> [T] { + var container = try self.nestedUnkeyedContainer(forKey: key) + var list = [T]() + var tmpContainer = container + while !container.isAtEnd { + let typeContainer = try container.nestedContainer(keyedBy: Discriminator.self) + let family: U = try typeContainer.decode(U.self, forKey: U.discriminator) + if let type = family.getType() as? T.Type { + list.append(try tmpContainer.decode(type)) + } + } + return list + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Keyframes/Keyframe.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Keyframes/Keyframe.swift new file mode 100644 index 0000000..c88065b --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Keyframes/Keyframe.swift @@ -0,0 +1,128 @@ +// +// Keyframe.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/7/19. +// + +import Foundation +import CoreGraphics + +/** + Keyframe represents a point in time and is the container for datatypes. + Note: This is a parent class and should not be used directly. + */ +final class Keyframe { + + /// The value of the keyframe + let value: T + /// The time in frames of the keyframe. + let time: CGFloat + /// A hold keyframe freezes interpolation until the next keyframe that is not a hold. + let isHold: Bool + /// The in tangent for the time interpolation curve. + let inTangent: Vector2D? + /// The out tangent for the time interpolation curve. + let outTangent: Vector2D? + + /// The spacial in tangent of the vector. + let spatialInTangent: Vector3D? + /// The spacial out tangent of the vector. + let spatialOutTangent: Vector3D? + + /// Initialize a value-only keyframe with no time data. + init(_ value: T, + spatialInTangent: Vector3D? = nil, + spatialOutTangent: Vector3D? = nil) { + self.value = value + self.time = 0 + self.isHold = true + self.inTangent = nil + self.outTangent = nil + self.spatialInTangent = spatialInTangent + self.spatialOutTangent = spatialOutTangent + } + + /// Initialize a keyframe + init(value: T, + time: Double, + isHold: Bool, + inTangent: Vector2D?, + outTangent: Vector2D?, + spatialInTangent: Vector3D? = nil, + spatialOutTangent: Vector3D? = nil) { + self.value = value + self.time = CGFloat(time) + self.isHold = isHold + self.outTangent = outTangent + self.inTangent = inTangent + self.spatialInTangent = spatialInTangent + self.spatialOutTangent = spatialOutTangent + } + +} + +/** + A generic class used to parse and remap keyframe json. + + Keyframe json has a couple of different variations and formats depending on the + type of keyframea and also the version of the JSON. By parsing the raw data + we can reconfigure it into a constant format. + */ +final class KeyframeData: Codable { + + /// The start value of the keyframe + let startValue: T? + /// The End value of the keyframe. Note: Newer versions animation json do not have this field. + let endValue: T? + /// The time in frames of the keyframe. + let time: Double? + /// A hold keyframe freezes interpolation until the next keyframe that is not a hold. + let hold: Int? + + /// The in tangent for the time interpolation curve. + let inTangent: Vector2D? + /// The out tangent for the time interpolation curve. + let outTangent: Vector2D? + + /// The spacial in tangent of the vector. + let spatialInTangent: Vector3D? + /// The spacial out tangent of the vector. + let spatialOutTangent:Vector3D? + + init(startValue: T?, + endValue: T?, + time: Double?, + hold: Int?, + inTangent: Vector2D?, + outTangent: Vector2D?, + spatialInTangent: Vector3D?, + spatialOutTangent: Vector3D?) { + self.startValue = startValue + self.endValue = endValue + self.time = time + self.hold = hold + self.inTangent = inTangent + self.outTangent = outTangent + self.spatialInTangent = spatialInTangent + self.spatialOutTangent = spatialOutTangent + } + + enum CodingKeys : String, CodingKey { + case startValue = "s" + case endValue = "e" + case time = "t" + case hold = "h" + case inTangent = "i" + case outTangent = "o" + case spatialInTangent = "ti" + case spatialOutTangent = "to" + } + + var isHold: Bool { + if let hold = hold { + return hold > 0 + } + return false + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Keyframes/KeyframeGroup.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Keyframes/KeyframeGroup.swift new file mode 100644 index 0000000..f64adc0 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Keyframes/KeyframeGroup.swift @@ -0,0 +1,108 @@ +// +// KeyframeGroup.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/14/19. +// + +import Foundation + +/** + Used for coding/decoding a group of Keyframes by type. + + Keyframe data is wrapped in a dictionary { "k" : KeyframeData }. + The keyframe data can either be an array of keyframes or, if no animation is present, the raw value. + This helper object is needed to properly decode the json. + */ + +final class KeyframeGroup: Codable where T: Codable, T: Interpolatable { + + let keyframes: ContiguousArray> + + private enum KeyframeWrapperKey: String, CodingKey { + case keyframeData = "k" + } + + init(keyframes: ContiguousArray>) { + self.keyframes = keyframes + } + + init(_ value: T) { + self.keyframes = [Keyframe(value)] + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: KeyframeWrapperKey.self) + + if let keyframeData: T = try? container.decode(T.self, forKey: .keyframeData) { + /// Try to decode raw value; No keyframe data. + self.keyframes = [Keyframe(keyframeData)] + } else { + /** + Decode and array of keyframes. + + Body Movin and Lottie deal with keyframes in different ways. + + A keyframe object in Body movin defines a span of time with a START + and an END, from the current keyframe time to the next keyframe time. + + A keyframe object in Lottie defines a singular point in time/space. + This point has an in-tangent and an out-tangent. + + To properly decode this we must iterate through keyframes while holding + reference to the previous keyframe. + */ + + var keyframesContainer = try container.nestedUnkeyedContainer(forKey: .keyframeData) + var keyframes = ContiguousArray>() + var previousKeyframeData: KeyframeData? + while(!keyframesContainer.isAtEnd) { + // Ensure that Time and Value are present. + + let keyframeData = try keyframesContainer.decode(KeyframeData.self) + + guard let value: T = keyframeData.startValue ?? previousKeyframeData?.endValue, + let time = keyframeData.time else { + /// Missing keyframe data. JSON must be corrupt. + throw DecodingError.dataCorruptedError(forKey: KeyframeWrapperKey.keyframeData, in: container, debugDescription: "Missing keyframe data.") + } + + keyframes.append(Keyframe(value: value, + time: time, + isHold: keyframeData.isHold, + inTangent: previousKeyframeData?.inTangent, + outTangent: keyframeData.outTangent, + spatialInTangent: previousKeyframeData?.spatialInTangent, + spatialOutTangent: keyframeData.spatialOutTangent)) + previousKeyframeData = keyframeData + } + self.keyframes = keyframes + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: KeyframeWrapperKey.self) + + if keyframes.count == 1 { + let keyframe = keyframes[0] + try container.encode(keyframe.value, forKey: .keyframeData) + } else { + var keyframeContainer = container.nestedUnkeyedContainer(forKey: .keyframeData) + + for i in 1..(startValue: keyframe.value, + endValue: nextKeyframe.value, + time: Double(keyframe.time), + hold: keyframe.isHold ? 1 : nil, + inTangent: nextKeyframe.inTangent, + outTangent: keyframe.outTangent, + spatialInTangent: nil, + spatialOutTangent: nil) + try keyframeContainer.encode(keyframeData) + } + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/ImageLayerModel.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/ImageLayerModel.swift new file mode 100644 index 0000000..6961962 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/ImageLayerModel.swift @@ -0,0 +1,32 @@ +// +// ImageLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// A layer that holds an image. +final class ImageLayerModel: LayerModel { + + /// The reference ID of the image. + let referenceID: String + + private enum CodingKeys : String, CodingKey { + case referenceID = "refId" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: ImageLayerModel.CodingKeys.self) + self.referenceID = try container.decode(String.self, forKey: .referenceID) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(referenceID, forKey: .referenceID) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/LayerModel.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/LayerModel.swift new file mode 100644 index 0000000..6b2667a --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/LayerModel.swift @@ -0,0 +1,150 @@ +// +// Layer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/7/19. +// + +import Foundation + +/// Used for mapping a heterogeneous list to classes for parsing. +extension LayerType: ClassFamily { + static var discriminator: Discriminator = .type + + func getType() -> AnyObject.Type { + switch self { + case .precomp: + return PreCompLayerModel.self + case .solid: + return SolidLayerModel.self + case .image: + return ImageLayerModel.self + case .null: + return LayerModel.self + case .shape: + return ShapeLayerModel.self + case .text: + return TextLayerModel.self + } + } +} + +public enum LayerType: Int, Codable { + case precomp + case solid + case image + case null + case shape + case text + + public init(from decoder: Decoder) throws { + self = try LayerType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .null + } +} + +public enum MatteType: Int, Codable { + case none + case add + case invert + case unknown +} + +public enum BlendMode: Int, Codable { + case normal + case multiply + case screen + case overlay + case darken + case lighten + case colorDodge + case colorBurn + case hardLight + case softLight + case difference + case exclusion + case hue + case saturation + case color + case luminosity +} + +/** + A base top container for shapes, images, and other view objects. + */ +class LayerModel: Codable { + + /// The readable name of the layer + let name: String + + /// The index of the layer + let index: Int + + /// The type of the layer. + let type: LayerType + + /// The coordinate space + let coordinateSpace: CoordinateSpace + + /// The in time of the layer in frames. + let inFrame: Double + /// The out time of the layer in frames. + let outFrame: Double + + /// The start time of the layer in frames. + let startTime: Double + + /// The transform of the layer + let transform: Transform + + /// The index of the parent layer, if applicable. + let parent: Int? + + /// The blending mode for the layer + let blendMode: BlendMode + + /// An array of masks for the layer. + let masks: [Mask]? + + /// A number that stretches time by a multiplier + let timeStretch: Double + + /// The type of matte if any. + let matte: MatteType? + + let hidden: Bool + + private enum CodingKeys : String, CodingKey { + case name = "nm" + case index = "ind" + case type = "ty" + case coordinateSpace = "ddd" + case inFrame = "ip" + case outFrame = "op" + case startTime = "st" + case transform = "ks" + case parent = "parent" + case blendMode = "bm" + case masks = "masksProperties" + case timeStretch = "sr" + case matte = "tt" + case hidden = "hd" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: LayerModel.CodingKeys.self) + self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Layer" + self.index = try container.decode(Int.self, forKey: .index) + self.type = try container.decode(LayerType.self, forKey: .type) + self.coordinateSpace = try container.decodeIfPresent(CoordinateSpace.self, forKey: .coordinateSpace) ?? .type2d + self.inFrame = try container.decode(Double.self, forKey: .inFrame) + self.outFrame = try container.decode(Double.self, forKey: .outFrame) + self.startTime = try container.decode(Double.self, forKey: .startTime) + self.transform = try container.decode(Transform.self, forKey: .transform) + self.parent = try container.decodeIfPresent(Int.self, forKey: .parent) + self.blendMode = try container.decodeIfPresent(BlendMode.self, forKey: .blendMode) ?? .normal + self.masks = try container.decodeIfPresent([Mask].self, forKey: .masks) + self.timeStretch = try container.decodeIfPresent(Double.self, forKey: .timeStretch) ?? 1 + self.matte = try container.decodeIfPresent(MatteType.self, forKey: .matte) + self.hidden = try container.decodeIfPresent(Bool.self, forKey: .hidden) ?? false + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/PreCompLayerModel.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/PreCompLayerModel.swift new file mode 100644 index 0000000..e107ea1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/PreCompLayerModel.swift @@ -0,0 +1,50 @@ +// +// PreCompLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// A layer that holds another animation composition. +final class PreCompLayerModel: LayerModel { + + /// The reference ID of the precomp. + let referenceID: String + + /// A value that remaps time over time. + let timeRemapping: KeyframeGroup? + + /// Precomp Width + let width: Double + + /// Precomp Height + let height: Double + + private enum CodingKeys : String, CodingKey { + case referenceID = "refId" + case timeRemapping = "tm" + case width = "w" + case height = "h" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: PreCompLayerModel.CodingKeys.self) + self.referenceID = try container.decode(String.self, forKey: .referenceID) + self.timeRemapping = try container.decodeIfPresent(KeyframeGroup.self, forKey: .timeRemapping) + self.width = try container.decode(Double.self, forKey: .width) + self.height = try container.decode(Double.self, forKey: .height) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(referenceID, forKey: .referenceID) + try container.encode(timeRemapping, forKey: .timeRemapping) + try container.encode(width, forKey: .width) + try container.encode(height, forKey: .height) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/ShapeLayerModel.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/ShapeLayerModel.swift new file mode 100644 index 0000000..eb6299f --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/ShapeLayerModel.swift @@ -0,0 +1,32 @@ +// +// ShapeLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// A layer that holds vector shape objects. +final class ShapeLayerModel: LayerModel { + + /// A list of shape items. + let items: [ShapeItem] + + private enum CodingKeys : String, CodingKey { + case items = "shapes" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: ShapeLayerModel.CodingKeys.self) + self.items = try container.decode([ShapeItem].self, ofFamily: ShapeType.self, forKey: .items) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.items, forKey: .items) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/SolidLayerModel.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/SolidLayerModel.swift new file mode 100644 index 0000000..afa00d7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/SolidLayerModel.swift @@ -0,0 +1,44 @@ +// +// SolidLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// A layer that holds a solid color. +final class SolidLayerModel: LayerModel { + + /// The color of the solid in Hex // Change to value provider. + let colorHex: String + + /// The Width of the color layer + let width: Double + + /// The height of the color layer + let height: Double + + private enum CodingKeys : String, CodingKey { + case colorHex = "sc" + case width = "sw" + case height = "sh" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: SolidLayerModel.CodingKeys.self) + self.colorHex = try container.decode(String.self, forKey: .colorHex) + self.width = try container.decode(Double.self, forKey: .width) + self.height = try container.decode(Double.self, forKey: .height) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(colorHex, forKey: .colorHex) + try container.encode(width, forKey: .width) + try container.encode(height, forKey: .height) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/TextLayerModel.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/TextLayerModel.swift new file mode 100644 index 0000000..f08bcef --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/TextLayerModel.swift @@ -0,0 +1,44 @@ +// +// TextLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// A layer that holds text. +final class TextLayerModel: LayerModel { + + /// The text for the layer + let text: KeyframeGroup + + /// Text animators + let animators: [TextAnimator] + + private enum CodingKeys : String, CodingKey { + case textGroup = "t" + } + + private enum TextCodingKeys : String, CodingKey { + case text = "d" + case animators = "a" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: TextLayerModel.CodingKeys.self) + let textContainer = try container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup) + self.text = try textContainer.decode(KeyframeGroup.self, forKey: .text) + self.animators = try textContainer.decode([TextAnimator].self, forKey: .animators) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + var textContainer = container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup) + try textContainer.encode(text, forKey: .text) + try textContainer.encode(animators, forKey: .animators) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/DashPattern.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/DashPattern.swift new file mode 100644 index 0000000..efc7532 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/DashPattern.swift @@ -0,0 +1,24 @@ +// +// DashPattern.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/22/19. +// + +import Foundation + +enum DashElementType: String, Codable { + case offset = "o" + case dash = "d" + case gap = "g" +} + +final class DashElement: Codable { + let type: DashElementType + let value: KeyframeGroup + + enum CodingKeys : String, CodingKey { + case type = "n" + case value = "v" + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Marker.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Marker.swift new file mode 100644 index 0000000..9c9512f --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Marker.swift @@ -0,0 +1,23 @@ +// +// Marker.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +/// A time marker +final class Marker: Codable { + + /// The Marker Name + let name: String + + /// The Frame time of the marker + let frameTime: AnimationFrameTime + + enum CodingKeys : String, CodingKey { + case name = "cm" + case frameTime = "tm" + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Mask.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Mask.swift new file mode 100644 index 0000000..1b7dc49 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Mask.swift @@ -0,0 +1,48 @@ +// +// Mask.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum MaskMode: String, Codable { + case add = "a" + case subtract = "s" + case intersect = "i" + case lighten = "l" + case darken = "d" + case difference = "f" + case none = "n" +} + +final class Mask: Codable { + + let mode: MaskMode + + let opacity: KeyframeGroup + + let shape: KeyframeGroup + + let inverted: Bool + + let expansion: KeyframeGroup + + enum CodingKeys : String, CodingKey { + case mode = "mode" + case opacity = "o" + case inverted = "inv" + case shape = "pt" + case expansion = "x" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Mask.CodingKeys.self) + self.mode = try container.decodeIfPresent(MaskMode.self, forKey: .mode) ?? .add + self.opacity = try container.decodeIfPresent(KeyframeGroup.self, forKey: .opacity) ?? KeyframeGroup(Vector1D(100)) + self.shape = try container.decode(KeyframeGroup.self, forKey: .shape) + self.inverted = try container.decodeIfPresent(Bool.self, forKey: .inverted) ?? false + self.expansion = try container.decodeIfPresent(KeyframeGroup.self, forKey: .expansion) ?? KeyframeGroup(Vector1D(0)) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Transform.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Transform.swift new file mode 100644 index 0000000..c7e3834 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Objects/Transform.swift @@ -0,0 +1,105 @@ +// +// Transform.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/7/19. +// + +import Foundation + +/// The animatable transform for a layer. Controls position, rotation, scale, and opacity. +final class Transform: Codable { + + /// The anchor point of the transform. + let anchorPoint: KeyframeGroup + + /// The position of the transform. This is nil if the position data was split. + let position: KeyframeGroup? + + /// The positionX of the transform. This is nil if the position property is set. + let positionX: KeyframeGroup? + + /// The positionY of the transform. This is nil if the position property is set. + let positionY: KeyframeGroup? + + /// The scale of the transform + let scale: KeyframeGroup + + /// The rotation of the transform. Note: This is single dimensional rotation. + let rotation: KeyframeGroup + + /// The opacity of the transform. + let opacity: KeyframeGroup + + /// Should always be nil. + let rotationZ: KeyframeGroup? + + enum CodingKeys : String, CodingKey { + case anchorPoint = "a" + case position = "p" + case positionX = "px" + case positionY = "py" + case scale = "s" + case rotation = "r" + case rotationZ = "rz" + case opacity = "o" + } + + enum PositionCodingKeys : String, CodingKey { + case split = "s" + case positionX = "x" + case positionY = "y" + } + + + required init(from decoder: Decoder) throws { + /** + This manual override of decode is required because we want to throw an error + in the case that there is not position data. + */ + let container = try decoder.container(keyedBy: Transform.CodingKeys.self) + + // AnchorPoint + self.anchorPoint = try container.decodeIfPresent(KeyframeGroup.self, forKey: .anchorPoint) ?? KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) + + // Position + if container.contains(.positionX), container.contains(.positionY) { + // Position dimensions are split into two keyframe groups + self.positionX = try container.decode(KeyframeGroup.self, forKey: .positionX) + self.positionY = try container.decode(KeyframeGroup.self, forKey: .positionY) + self.position = nil + } else if let positionKeyframes = try? container.decode(KeyframeGroup.self, forKey: .position) { + // Position dimensions are a single keyframe group. + self.position = positionKeyframes + self.positionX = nil + self.positionY = nil + } else if let positionContainer = try? container.nestedContainer(keyedBy: PositionCodingKeys.self, forKey: .position), + let positionX = try? positionContainer.decode(KeyframeGroup.self, forKey: .positionX), + let positionY = try? positionContainer.decode(KeyframeGroup.self, forKey: .positionY) { + /// Position keyframes are split and nested. + self.positionX = positionX + self.positionY = positionY + self.position = nil + } else { + /// Default value. + self.position = KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) + self.positionX = nil + self.positionY = nil + } + + + // Scale + self.scale = try container.decodeIfPresent(KeyframeGroup.self, forKey: .scale) ?? KeyframeGroup(Vector3D(x: Double(100), y: 100, z: 100)) + + // Rotation + if let rotationZ = try container.decodeIfPresent(KeyframeGroup.self, forKey: .rotationZ) { + self.rotation = rotationZ + } else { + self.rotation = try container.decodeIfPresent(KeyframeGroup.self, forKey: .rotation) ?? KeyframeGroup(Vector1D(0)) + } + self.rotationZ = nil + + // Opacity + self.opacity = try container.decodeIfPresent(KeyframeGroup.self, forKey: .opacity) ?? KeyframeGroup(Vector1D(100)) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Ellipse.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Ellipse.swift new file mode 100644 index 0000000..5e6b918 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Ellipse.swift @@ -0,0 +1,50 @@ +// +// EllipseItem.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum PathDirection: Int, Codable { + case clockwise = 1 + case userSetClockwise = 2 + case counterClockwise = 3 +} + +/// An item that define an ellipse shape +final class Ellipse: ShapeItem { + + /// The direction of the ellipse. + let direction: PathDirection + + /// The position of the ellipse + let position: KeyframeGroup + + /// The size of the ellipse + let size: KeyframeGroup + + private enum CodingKeys : String, CodingKey { + case direction = "d" + case position = "p" + case size = "s" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Ellipse.CodingKeys.self) + self.direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction) ?? .clockwise + self.position = try container.decode(KeyframeGroup.self, forKey: .position) + self.size = try container.decode(KeyframeGroup.self, forKey: .size) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(direction, forKey: .direction) + try container.encode(position, forKey: .position) + try container.encode(size, forKey: .size) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/FillI.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/FillI.swift new file mode 100644 index 0000000..11aded7 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/FillI.swift @@ -0,0 +1,49 @@ +// +// FillShape.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum FillRule: Int, Codable { + case none + case nonZeroWinding + case evenOdd +} + +/// An item that defines a fill render +final class Fill: ShapeItem { + + /// The opacity of the fill + let opacity: KeyframeGroup + + /// The color keyframes for the fill + let color: KeyframeGroup + + let fillRule: FillRule + + private enum CodingKeys : String, CodingKey { + case opacity = "o" + case color = "c" + case fillRule = "r" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Fill.CodingKeys.self) + self.opacity = try container.decode(KeyframeGroup.self, forKey: .opacity) + self.color = try container.decode(KeyframeGroup.self, forKey: .color) + self.fillRule = try container.decodeIfPresent(FillRule.self, forKey: .fillRule) ?? .nonZeroWinding + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(opacity, forKey: .opacity) + try container.encode(color, forKey: .color) + try container.encode(fillRule, forKey: .fillRule) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/GradientFill.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/GradientFill.swift new file mode 100644 index 0000000..05627c8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/GradientFill.swift @@ -0,0 +1,86 @@ +// +// GradientFill.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum GradientType: Int, Codable { + case none + case linear + case radial +} + +/// An item that define a gradient fill +final class GradientFill: ShapeItem { + + /// The opacity of the fill + let opacity: KeyframeGroup + + /// The start of the gradient + let startPoint: KeyframeGroup + + /// The end of the gradient + let endPoint: KeyframeGroup + + /// The type of gradient + let gradientType: GradientType + + /// Gradient Highlight Length. Only if type is Radial + let highlightLength: KeyframeGroup? + + /// Highlight Angle. Only if type is Radial + let highlightAngle: KeyframeGroup? + + /// The number of color points in the gradient + let numberOfColors: Int + + /// The Colors of the gradient. + let colors: KeyframeGroup<[Double]> + + private enum CodingKeys : String, CodingKey { + case opacity = "o" + case startPoint = "s" + case endPoint = "e" + case gradientType = "t" + case highlightLength = "h" + case highlightAngle = "a" + case colors = "g" + } + + private enum GradientDataKeys : String, CodingKey { + case numberOfColors = "p" + case colors = "k" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: GradientFill.CodingKeys.self) + self.opacity = try container.decode(KeyframeGroup.self, forKey: .opacity) + self.startPoint = try container.decode(KeyframeGroup.self, forKey: .startPoint) + self.endPoint = try container.decode(KeyframeGroup.self, forKey: .endPoint) + self.gradientType = try container.decode(GradientType.self, forKey: .gradientType) + self.highlightLength = try container.decodeIfPresent(KeyframeGroup.self, forKey: .highlightLength) + self.highlightAngle = try container.decodeIfPresent(KeyframeGroup.self, forKey: .highlightAngle) + let colorsContainer = try container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors) + self.colors = try colorsContainer.decode(KeyframeGroup<[Double]>.self, forKey: .colors) + self.numberOfColors = try colorsContainer.decode(Int.self, forKey: .numberOfColors) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(opacity, forKey: .opacity) + try container.encode(startPoint, forKey: .startPoint) + try container.encode(endPoint, forKey: .endPoint) + try container.encode(gradientType, forKey: .gradientType) + try container.encodeIfPresent(highlightLength, forKey: .highlightLength) + try container.encodeIfPresent(highlightAngle, forKey: .highlightAngle) + var colorsContainer = container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors) + try colorsContainer.encode(numberOfColors, forKey: .numberOfColors) + try colorsContainer.encode(colors, forKey: .colors) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/GradientStroke.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/GradientStroke.swift new file mode 100644 index 0000000..163a612 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/GradientStroke.swift @@ -0,0 +1,125 @@ +// +// GradientStroke.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum LineCap: Int, Codable { + case none + case butt + case round + case square +} + +enum LineJoin: Int, Codable { + case none + case miter + case round + case bevel +} + +/// An item that define an ellipse shape +final class GradientStroke: ShapeItem { + + /// The opacity of the fill + let opacity: KeyframeGroup + + /// The start of the gradient + let startPoint: KeyframeGroup + + /// The end of the gradient + let endPoint: KeyframeGroup + + /// The type of gradient + let gradientType: GradientType + + /// Gradient Highlight Length. Only if type is Radial + let highlightLength: KeyframeGroup? + + /// Highlight Angle. Only if type is Radial + let highlightAngle: KeyframeGroup? + + /// The number of color points in the gradient + let numberOfColors: Int + + /// The Colors of the gradient. + let colors: KeyframeGroup<[Double]> + + /// The width of the stroke + let width: KeyframeGroup + + /// Line Cap + let lineCap: LineCap + + /// Line Join + let lineJoin: LineJoin + + /// Miter Limit + let miterLimit: Double + + /// The dash pattern of the stroke + let dashPattern: [DashElement]? + + private enum CodingKeys : String, CodingKey { + case opacity = "o" + case startPoint = "s" + case endPoint = "e" + case gradientType = "t" + case highlightLength = "h" + case highlightAngle = "a" + case colors = "g" + case width = "w" + case lineCap = "lc" + case lineJoin = "lj" + case miterLimit = "ml" + case dashPattern = "d" + } + + private enum GradientDataKeys : String, CodingKey { + case numberOfColors = "p" + case colors = "k" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: GradientStroke.CodingKeys.self) + self.opacity = try container.decode(KeyframeGroup.self, forKey: .opacity) + self.startPoint = try container.decode(KeyframeGroup.self, forKey: .startPoint) + self.endPoint = try container.decode(KeyframeGroup.self, forKey: .endPoint) + self.gradientType = try container.decode(GradientType.self, forKey: .gradientType) + self.highlightLength = try container.decodeIfPresent(KeyframeGroup.self, forKey: .highlightLength) + self.highlightAngle = try container.decodeIfPresent(KeyframeGroup.self, forKey: .highlightAngle) + self.width = try container.decode(KeyframeGroup.self, forKey: .width) + self.lineCap = try container.decodeIfPresent(LineCap.self, forKey: .lineCap) ?? .round + self.lineJoin = try container.decodeIfPresent(LineJoin.self, forKey: .lineJoin) ?? .round + self.miterLimit = try container.decodeIfPresent(Double.self, forKey: .miterLimit) ?? 4 + // TODO Decode Color Objects instead of array. + let colorsContainer = try container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors) + self.colors = try colorsContainer.decode(KeyframeGroup<[Double]>.self, forKey: .colors) + self.numberOfColors = try colorsContainer.decode(Int.self, forKey: .numberOfColors) + self.dashPattern = try container.decodeIfPresent([DashElement].self, forKey: .dashPattern) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(opacity, forKey: .opacity) + try container.encode(startPoint, forKey: .startPoint) + try container.encode(endPoint, forKey: .endPoint) + try container.encode(gradientType, forKey: .gradientType) + try container.encodeIfPresent(highlightLength, forKey: .highlightLength) + try container.encodeIfPresent(highlightAngle, forKey: .highlightAngle) + try container.encode(width, forKey: .width) + try container.encode(lineCap, forKey: .lineCap) + try container.encode(lineJoin, forKey: .lineJoin) + try container.encode(miterLimit, forKey: .miterLimit) + var colorsContainer = container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors) + try colorsContainer.encode(numberOfColors, forKey: .numberOfColors) + try colorsContainer.encode(colors, forKey: .colors) + try container.encodeIfPresent(dashPattern, forKey: .dashPattern) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Group.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Group.swift new file mode 100644 index 0000000..c676d04 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Group.swift @@ -0,0 +1,32 @@ +// +// GroupItem.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// An item that define an ellipse shape +final class Group: ShapeItem { + + /// A list of shape items. + let items: [ShapeItem] + + private enum CodingKeys : String, CodingKey { + case items = "it" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Group.CodingKeys.self) + self.items = try container.decode([ShapeItem].self, ofFamily: ShapeType.self, forKey: .items) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(items, forKey: .items) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Merge.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Merge.swift new file mode 100644 index 0000000..3143bb5 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Merge.swift @@ -0,0 +1,41 @@ +// +// Merge.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum MergeMode: Int, Codable { + case none + case merge + case add + case subtract + case intersect + case exclude +} + +/// An item that define an ellipse shape +final class Merge: ShapeItem { + + /// The mode of the merge path + let mode: MergeMode + + private enum CodingKeys : String, CodingKey { + case mode = "mm" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Merge.CodingKeys.self) + self.mode = try container.decode(MergeMode.self, forKey: .mode) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(mode, forKey: .mode) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Rectangle.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Rectangle.swift new file mode 100644 index 0000000..b880e75 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Rectangle.swift @@ -0,0 +1,50 @@ +// +// Rectangle.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// An item that define an ellipse shape +final class Rectangle: ShapeItem { + + /// The direction of the rect. + let direction: PathDirection + + /// The position + let position: KeyframeGroup + + /// The size + let size: KeyframeGroup + + /// The Corner radius of the rectangle + let cornerRadius: KeyframeGroup + + private enum CodingKeys : String, CodingKey { + case direction = "d" + case position = "p" + case size = "s" + case cornerRadius = "r" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Rectangle.CodingKeys.self) + self.direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction) ?? .clockwise + self.position = try container.decode(KeyframeGroup.self, forKey: .position) + self.size = try container.decode(KeyframeGroup.self, forKey: .size) + self.cornerRadius = try container.decode(KeyframeGroup.self, forKey: .cornerRadius) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(direction, forKey: .direction) + try container.encode(position, forKey: .position) + try container.encode(size, forKey: .size) + try container.encode(cornerRadius, forKey: .cornerRadius) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Repeater.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Repeater.swift new file mode 100644 index 0000000..e8780f4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Repeater.swift @@ -0,0 +1,80 @@ +// +// Repeater.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// An item that define an ellipse shape +final class Repeater: ShapeItem { + + /// The number of copies to repeat + let copies: KeyframeGroup + + /// The offset of each copy + let offset: KeyframeGroup + + /// Start Opacity + let startOpacity: KeyframeGroup + + /// End opacity + let endOpacity: KeyframeGroup + + /// The rotation + let rotation: KeyframeGroup + + /// Anchor Point + let anchorPoint: KeyframeGroup + + /// Position + let position: KeyframeGroup + + /// Scale + let scale: KeyframeGroup + + private enum CodingKeys : String, CodingKey { + case copies = "c" + case offset = "o" + case transform = "tr" + } + + private enum TransformKeys : String, CodingKey { + case rotation = "r" + case startOpacity = "so" + case endOpacity = "eo" + case anchorPoint = "a" + case position = "p" + case scale = "s" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Repeater.CodingKeys.self) + self.copies = try container.decodeIfPresent(KeyframeGroup.self, forKey: .copies) ?? KeyframeGroup(Vector1D(0)) + self.offset = try container.decodeIfPresent(KeyframeGroup.self, forKey: .offset) ?? KeyframeGroup(Vector1D(0)) + let transformContainer = try container.nestedContainer(keyedBy: TransformKeys.self, forKey: .transform) + self.startOpacity = try transformContainer.decodeIfPresent(KeyframeGroup.self, forKey: .startOpacity) ?? KeyframeGroup(Vector1D(100)) + self.endOpacity = try transformContainer.decodeIfPresent(KeyframeGroup.self, forKey: .endOpacity) ?? KeyframeGroup(Vector1D(100)) + self.rotation = try transformContainer.decodeIfPresent(KeyframeGroup.self, forKey: .rotation) ?? KeyframeGroup(Vector1D(0)) + self.position = try transformContainer.decodeIfPresent(KeyframeGroup.self, forKey: .position) ?? KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) + self.anchorPoint = try transformContainer.decodeIfPresent(KeyframeGroup.self, forKey: .anchorPoint) ?? KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) + self.scale = try transformContainer.decodeIfPresent(KeyframeGroup.self, forKey: .scale) ?? KeyframeGroup(Vector3D(x: Double(100), y: 100, z: 100)) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(copies, forKey: .copies) + try container.encode(offset, forKey: .offset) + var transformContainer = container.nestedContainer(keyedBy: TransformKeys.self, forKey: .transform) + try transformContainer.encode(startOpacity, forKey: .startOpacity) + try transformContainer.encode(endOpacity, forKey: .endOpacity) + try transformContainer.encode(rotation, forKey: .rotation) + try transformContainer.encode(position, forKey: .position) + try transformContainer.encode(anchorPoint, forKey: .anchorPoint) + try transformContainer.encode(scale, forKey: .scale) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Shape.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Shape.swift new file mode 100644 index 0000000..e2681e6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Shape.swift @@ -0,0 +1,37 @@ +// +// VectorShape.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// An item that define an ellipse shape +final class Shape: ShapeItem { + + /// The Path + let path: KeyframeGroup + + let direction: PathDirection? + + private enum CodingKeys : String, CodingKey { + case path = "ks" + case direction = "d" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Shape.CodingKeys.self) + self.path = try container.decode(KeyframeGroup.self, forKey: .path) + self.direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(path, forKey: .path) + try container.encodeIfPresent(direction, forKey: .direction) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/ShapeItem.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/ShapeItem.swift new file mode 100644 index 0000000..0444361 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/ShapeItem.swift @@ -0,0 +1,95 @@ +// +// ShapeItem.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// Used for mapping a heterogeneous list to classes for parsing. +extension ShapeType: ClassFamily { + + static var discriminator: Discriminator = .type + + func getType() -> AnyObject.Type { + switch self { + case .ellipse: + return Ellipse.self + case .fill: + return Fill.self + case .gradientFill: + return GradientFill.self + case .group: + return Group.self + case .gradientStroke: + return GradientStroke.self + case .merge: + return Merge.self + case .rectangle: + return Rectangle.self + case .repeater: + return Repeater.self + case .shape: + return Shape.self + case .star: + return Star.self + case .stroke: + return Stroke.self + case .trim: + return Trim.self + case .transform: + return ShapeTransform.self + default: + return ShapeItem.self + } + } +} + +enum ShapeType: String, Codable { + case ellipse = "el" + case fill = "fl" + case gradientFill = "gf" + case group = "gr" + case gradientStroke = "gs" + case merge = "mm" + case rectangle = "rc" + case repeater = "rp" + case round = "rd" + case shape = "sh" + case star = "sr" + case stroke = "st" + case trim = "tm" + case transform = "tr" + case unknown + + public init(from decoder: Decoder) throws { + self = try ShapeType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .unknown + } +} + +/// An item belonging to a Shape Layer +class ShapeItem: Codable { + + /// The name of the shape + let name: String + + /// The type of shape + let type: ShapeType + + let hidden: Bool + + private enum CodingKeys : String, CodingKey { + case name = "nm" + case type = "ty" + case hidden = "hd" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: ShapeItem.CodingKeys.self) + self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Layer" + self.type = try container.decode(ShapeType.self, forKey: .type) + self.hidden = try container.decodeIfPresent(Bool.self, forKey: .hidden) ?? false + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/ShapeTransform.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/ShapeTransform.swift new file mode 100644 index 0000000..5fba165 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/ShapeTransform.swift @@ -0,0 +1,68 @@ +// +// TransformItem.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// An item that define an ellipse shape +final class ShapeTransform: ShapeItem { + + /// Anchor Point + let anchor: KeyframeGroup + + /// Position + let position: KeyframeGroup + + /// Scale + let scale: KeyframeGroup + + /// Rotation + let rotation: KeyframeGroup + + /// opacity + let opacity: KeyframeGroup + + /// Skew + let skew: KeyframeGroup + + /// Skew Axis + let skewAxis: KeyframeGroup + + private enum CodingKeys : String, CodingKey { + case anchor = "a" + case position = "p" + case scale = "s" + case rotation = "r" + case opacity = "o" + case skew = "sk" + case skewAxis = "sa" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: ShapeTransform.CodingKeys.self) + self.anchor = try container.decodeIfPresent(KeyframeGroup.self, forKey: .anchor) ?? KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) + self.position = try container.decodeIfPresent(KeyframeGroup.self, forKey: .position) ?? KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) + self.scale = try container.decodeIfPresent(KeyframeGroup.self, forKey: .scale) ?? KeyframeGroup(Vector3D(x: Double(100), y: 100, z: 100)) + self.rotation = try container.decodeIfPresent(KeyframeGroup.self, forKey: .rotation) ?? KeyframeGroup(Vector1D(0)) + self.opacity = try container.decodeIfPresent(KeyframeGroup.self, forKey: .opacity) ?? KeyframeGroup(Vector1D(100)) + self.skew = try container.decodeIfPresent(KeyframeGroup.self, forKey: .skew) ?? KeyframeGroup(Vector1D(0)) + self.skewAxis = try container.decodeIfPresent(KeyframeGroup.self, forKey: .skewAxis) ?? KeyframeGroup(Vector1D(0)) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(anchor, forKey: .anchor) + try container.encode(position, forKey: .position) + try container.encode(scale, forKey: .scale) + try container.encode(rotation, forKey: .rotation) + try container.encode(opacity, forKey: .opacity) + try container.encode(skew, forKey: .skew) + try container.encode(skewAxis, forKey: .skewAxis) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Star.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Star.swift new file mode 100644 index 0000000..b280441 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Star.swift @@ -0,0 +1,86 @@ +// +// Star.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum StarType: Int, Codable { + case none + case star + case polygon +} + +/// An item that define an ellipse shape +final class Star: ShapeItem { + + /// The direction of the star. + let direction: PathDirection + + /// The position of the star + let position: KeyframeGroup + + /// The outer radius of the star + let outerRadius: KeyframeGroup + + /// The outer roundness of the star + let outerRoundness: KeyframeGroup + + /// The outer radius of the star + let innerRadius: KeyframeGroup? + + /// The outer roundness of the star + let innerRoundness: KeyframeGroup? + + /// The rotation of the star + let rotation: KeyframeGroup + + /// The number of points on the star + let points: KeyframeGroup + + /// The type of star + let starType: StarType + + private enum CodingKeys : String, CodingKey { + case direction = "d" + case position = "p" + case outerRadius = "or" + case outerRoundness = "os" + case innerRadius = "ir" + case innerRoundness = "is" + case rotation = "r" + case points = "pt" + case starType = "sy" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Star.CodingKeys.self) + self.direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction) ?? .clockwise + self.position = try container.decode(KeyframeGroup.self, forKey: .position) + self.outerRadius = try container.decode(KeyframeGroup.self, forKey: .outerRadius) + self.outerRoundness = try container.decode(KeyframeGroup.self, forKey: .outerRoundness) + self.innerRadius = try container.decodeIfPresent(KeyframeGroup.self, forKey: .innerRadius) + self.innerRoundness = try container.decodeIfPresent(KeyframeGroup.self, forKey: .innerRoundness) + self.rotation = try container.decode(KeyframeGroup.self, forKey: .rotation) + self.points = try container.decode(KeyframeGroup.self, forKey: .points) + self.starType = try container.decode(StarType.self, forKey: .starType) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(direction, forKey: .direction) + try container.encode(position, forKey: .position) + try container.encode(outerRadius, forKey: .outerRadius) + try container.encode(outerRoundness, forKey: .outerRoundness) + try container.encode(innerRadius, forKey: .innerRadius) + try container.encode(innerRoundness, forKey: .innerRoundness) + try container.encode(rotation, forKey: .rotation) + try container.encode(points, forKey: .points) + try container.encode(starType, forKey: .starType) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Stroke.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Stroke.swift new file mode 100644 index 0000000..5e043ed --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Stroke.swift @@ -0,0 +1,67 @@ +// +// Stroke.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +/// An item that define an ellipse shape +final class Stroke: ShapeItem { + + /// The opacity of the stroke + let opacity: KeyframeGroup + + /// The Color of the stroke + let color: KeyframeGroup + + /// The width of the stroke + let width: KeyframeGroup + + /// Line Cap + let lineCap: LineCap + + /// Line Join + let lineJoin: LineJoin + + /// Miter Limit + let miterLimit: Double + + /// The dash pattern of the stroke + let dashPattern: [DashElement]? + + private enum CodingKeys : String, CodingKey { + case opacity = "o" + case color = "c" + case width = "w" + case lineCap = "lc" + case lineJoin = "lj" + case miterLimit = "ml" + case dashPattern = "d" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Stroke.CodingKeys.self) + self.opacity = try container.decode(KeyframeGroup.self, forKey: .opacity) + self.color = try container.decode(KeyframeGroup.self, forKey: .color) + self.width = try container.decode(KeyframeGroup.self, forKey: .width) + self.lineCap = try container.decodeIfPresent(LineCap.self, forKey: .lineCap) ?? .round + self.lineJoin = try container.decodeIfPresent(LineJoin.self, forKey: .lineJoin) ?? .round + self.miterLimit = try container.decodeIfPresent(Double.self, forKey: .miterLimit) ?? 4 + self.dashPattern = try container.decodeIfPresent([DashElement].self, forKey: .dashPattern) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(opacity, forKey: .opacity) + try container.encode(color, forKey: .color) + try container.encode(width, forKey: .width) + try container.encode(lineCap, forKey: .lineCap) + try container.encode(lineJoin, forKey: .lineJoin) + try container.encode(miterLimit, forKey: .miterLimit) + try container.encodeIfPresent(dashPattern, forKey: .dashPattern) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Trim.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Trim.swift new file mode 100644 index 0000000..dba3d67 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Trim.swift @@ -0,0 +1,53 @@ +// +// Trim.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation + +enum TrimType: Int, Codable { + case simultaneously = 1 + case individually = 2 +} +/// An item that define an ellipse shape +final class Trim: ShapeItem { + + /// The start of the trim + let start: KeyframeGroup + + /// The end of the trim + let end: KeyframeGroup + + /// The offset of the trim + let offset: KeyframeGroup + + let trimType: TrimType + + private enum CodingKeys : String, CodingKey { + case start = "s" + case end = "e" + case offset = "o" + case trimType = "m" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Trim.CodingKeys.self) + self.start = try container.decode(KeyframeGroup.self, forKey: .start) + self.end = try container.decode(KeyframeGroup.self, forKey: .end) + self.offset = try container.decode(KeyframeGroup.self, forKey: .offset) + self.trimType = try container.decode(TrimType.self, forKey: .trimType) + try super.init(from: decoder) + } + + override func encode(to encoder: Encoder) throws { + try super.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(start, forKey: .start) + try container.encode(end, forKey: .end) + try container.encode(offset, forKey: .offset) + try container.encode(trimType, forKey: .trimType) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/Font.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/Font.swift new file mode 100644 index 0000000..54d7540 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/Font.swift @@ -0,0 +1,35 @@ +// +// Font.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +final class Font: Codable { + + let name: String + let familyName: String + let style: String + let ascent: Double + + private enum CodingKeys: String, CodingKey { + case name = "fName" + case familyName = "fFamily" + case style = "fStyle" + case ascent = "ascent" + } + +} + +/// A list of fonts +final class FontList: Codable { + + let fonts: [Font] + + enum CodingKeys : String, CodingKey { + case fonts = "list" + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/Glyph.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/Glyph.swift new file mode 100644 index 0000000..755f00a --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/Glyph.swift @@ -0,0 +1,72 @@ +// +// Glyph.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +/// A model that holds a vector character +final class Glyph: Codable { + + /// The character + let character: String + + /// The font size of the character + let fontSize: Double + + /// The font family of the character + let fontFamily: String + + /// The Style of the character + let fontStyle: String + + /// The Width of the character + let width: Double + + /// The Shape Data of the Character + let shapes: [ShapeItem] + + private enum CodingKeys: String, CodingKey { + case character = "ch" + case fontSize = "size" + case fontFamily = "fFamily" + case fontStyle = "style" + case width = "w" + case shapeWrapper = "data" + } + + private enum ShapeKey: String, CodingKey { + case shapes = "shapes" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Glyph.CodingKeys.self) + self.character = try container.decode(String.self, forKey: .character) + self.fontSize = try container.decode(Double.self, forKey: .fontSize) + self.fontFamily = try container.decode(String.self, forKey: .fontFamily) + self.fontStyle = try container.decode(String.self, forKey: .fontStyle) + self.width = try container.decode(Double.self, forKey: .width) + if container.contains(.shapeWrapper), + let shapeContainer = try? container.nestedContainer(keyedBy: ShapeKey.self, forKey: .shapeWrapper), + shapeContainer.contains(.shapes) { + self.shapes = try shapeContainer.decode([ShapeItem].self, ofFamily: ShapeType.self, forKey: .shapes) + } else { + self.shapes = [] + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(character, forKey: .character) + try container.encode(fontSize, forKey: .fontSize) + try container.encode(fontFamily, forKey: .fontFamily) + try container.encode(fontStyle, forKey: .fontStyle) + try container.encode(width, forKey: .width) + + var shapeContainer = container.nestedContainer(keyedBy: ShapeKey.self, forKey: .shapeWrapper) + try shapeContainer.encode(shapes, forKey: .shapes) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/TextAnimator.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/TextAnimator.swift new file mode 100644 index 0000000..dd93cdf --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/TextAnimator.swift @@ -0,0 +1,99 @@ +// +// TextAnimator.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +final class TextAnimator: Codable { + + let name: String + + /// Anchor + let anchor: KeyframeGroup? + + /// Position + let position: KeyframeGroup? + + /// Scale + let scale: KeyframeGroup? + + /// Skew + let skew: KeyframeGroup? + + /// Skew Axis + let skewAxis: KeyframeGroup? + + /// Rotation + let rotation: KeyframeGroup? + + /// Opacity + let opacity: KeyframeGroup? + + /// Stroke Color + let strokeColor: KeyframeGroup? + + /// Fill Color + let fillColor: KeyframeGroup? + + /// Stroke Width + let strokeWidth: KeyframeGroup? + + /// Tracking + let tracking: KeyframeGroup? + + private enum CodingKeys: String, CodingKey { +// case textSelector = "s" TODO + case textAnimator = "a" + case name = "nm" + } + + private enum TextSelectorKeys: String, CodingKey { + case start = "s" + case end = "e" + case offset = "o" + } + + private enum TextAnimatorKeys: String, CodingKey { + case fillColor = "fc" + case strokeColor = "sc" + case strokeWidth = "sw" + case tracking = "t" + case anchor = "a" + case position = "p" + case scale = "s" + case skew = "sk" + case skewAxis = "sa" + case rotation = "r" + case opacity = "o" + } + + required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: TextAnimator.CodingKeys.self) + self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "" + let animatorContainer = try container.nestedContainer(keyedBy: TextAnimatorKeys.self, forKey: .textAnimator) + self.fillColor = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .fillColor) + self.strokeColor = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .strokeColor) + self.strokeWidth = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .strokeWidth) + self.tracking = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .tracking) + self.anchor = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .anchor) + self.position = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .position) + self.scale = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .scale) + self.skew = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .skew) + self.skewAxis = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .skewAxis) + self.rotation = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .rotation) + self.opacity = try animatorContainer.decodeIfPresent(KeyframeGroup.self, forKey: .opacity) + + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + var animatorContainer = container.nestedContainer(keyedBy: TextAnimatorKeys.self, forKey: .textAnimator) + try animatorContainer.encodeIfPresent(fillColor, forKey: .fillColor) + try animatorContainer.encodeIfPresent(strokeColor, forKey: .strokeColor) + try animatorContainer.encodeIfPresent(strokeWidth, forKey: .strokeWidth) + try animatorContainer.encodeIfPresent(tracking, forKey: .tracking) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/TextDocument.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/TextDocument.swift new file mode 100644 index 0000000..016fd76 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Model/Text/TextDocument.swift @@ -0,0 +1,70 @@ +// +// TextDocument.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/9/19. +// + +import Foundation + +enum TextJustification: Int, Codable { + case left + case right + case center +} + +final class TextDocument: Codable { + + /// The Text + let text: String + + /// The Font size + let fontSize: Double + + /// The Font Family + let fontFamily: String + + /// Justification + let justification: TextJustification + + /// Tracking + let tracking: Int + + /// Line Height + let lineHeight: Double + + /// Baseline + let baseline: Double? + + /// Fill Color data + let fillColorData: Color? + + /// Scroke Color data + let strokeColorData: Color? + + /// Stroke Width + let strokeWidth: Double? + + /// Stroke Over Fill + let strokeOverFill: Bool? + + let textFramePosition: Vector3D? + + let textFrameSize: Vector3D? + + private enum CodingKeys : String, CodingKey { + case text = "t" + case fontSize = "s" + case fontFamily = "f" + case justification = "j" + case tracking = "tr" + case lineHeight = "lh" + case baseline = "ls" + case fillColorData = "fc" + case strokeColorData = "sc" + case strokeWidth = "sw" + case strokeOverFill = "of" + case textFramePosition = "ps" + case textFrameSize = "sz" + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Extensions/ItemsExtension.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Extensions/ItemsExtension.swift new file mode 100644 index 0000000..9220a63 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Extensions/ItemsExtension.swift @@ -0,0 +1,95 @@ +// +// ItemsExtension.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/18/19. +// + +import Foundation + +final class NodeTree { + var rootNode: AnimatorNode? = nil + var transform: ShapeTransform? = nil + var renderContainers: [ShapeContainerLayer] = [] + var paths: [PathOutputNode] = [] + var childrenNodes: [AnimatorNode] = [] +} + +extension Array where Element == ShapeItem { + func initializeNodeTree() -> NodeTree { + + let nodeTree = NodeTree() + + for item in self { + guard item.hidden == false, item.type != .unknown else { continue } + if let fill = item as? Fill { + let node = FillNode(parentNode: nodeTree.rootNode, fill: fill) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let stroke = item as? Stroke { + let node = StrokeNode(parentNode: nodeTree.rootNode, stroke: stroke) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let gradientFill = item as? GradientFill { + let node = GradientFillNode(parentNode: nodeTree.rootNode, gradientFill: gradientFill) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let gradientStroke = item as? GradientStroke { + let node = GradientStrokeNode(parentNode: nodeTree.rootNode, gradientStroke: gradientStroke) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let ellipse = item as? Ellipse { + let node = EllipseNode(parentNode: nodeTree.rootNode, ellipse: ellipse) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let rect = item as? Rectangle { + let node = RectangleNode(parentNode: nodeTree.rootNode, rectangle: rect) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let star = item as? Star { + switch star.starType { + case .none: + continue + case .polygon: + let node = PolygonNode(parentNode: nodeTree.rootNode, star: star) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + case .star: + let node = StarNode(parentNode: nodeTree.rootNode, star: star) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } + } else if let shape = item as? Shape { + let node = ShapeNode(parentNode: nodeTree.rootNode, shape: shape) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let trim = item as? Trim { + let node = TrimPathNode(parentNode: nodeTree.rootNode, trim: trim, upstreamPaths: nodeTree.paths) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + } else if let xform = item as? ShapeTransform { + nodeTree.transform = xform + continue + } else if let group = item as? Group { + + let tree = group.items.initializeNodeTree() + let node = GroupNode(name: group.name, parentNode: nodeTree.rootNode, tree: tree) + nodeTree.rootNode = node + nodeTree.childrenNodes.append(node) + /// Now add all child paths to current tree + nodeTree.paths.append(contentsOf: tree.paths) + nodeTree.renderContainers.append(node.container) + } + + if let pathNode = nodeTree.rootNode as? PathNode { + //// Add path container to the node tree + nodeTree.paths.append(pathNode.pathOutput) + } + + if let renderNode = nodeTree.rootNode as? RenderNode { + nodeTree.renderContainers.append(ShapeRenderLayer(renderer: renderNode.renderer)) + } + } + return nodeTree + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/NodeProperty.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/NodeProperty.swift new file mode 100644 index 0000000..5e10481 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/NodeProperty.swift @@ -0,0 +1,47 @@ +// +// NodeProperty.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics + +/// A node property that holds a reference to a T ValueProvider and a T ValueContainer. +class NodeProperty: AnyNodeProperty { + + var valueType: Any.Type { return T.self } + + var value: T { + return typedContainer.outputValue + } + + var valueContainer: AnyValueContainer { + return typedContainer + } + + var valueProvider: AnyValueProvider + + init(provider: AnyValueProvider) { + self.valueProvider = provider + self.typedContainer = ValueContainer(provider.value(frame: 0) as! T) + self.typedContainer.setNeedsUpdate() + } + + func needsUpdate(frame: CGFloat) -> Bool { + return valueContainer.needsUpdate || valueProvider.hasUpdate(frame: frame) + } + + func setProvider(provider: AnyValueProvider) { + guard provider.valueType == valueType else { return } + self.valueProvider = provider + valueContainer.setNeedsUpdate() + } + + func update(frame: CGFloat) { + typedContainer.setValue(valueProvider.value(frame: frame), forFrame: frame) + } + + fileprivate var typedContainer: ValueContainer +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyNodeProperty.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyNodeProperty.swift new file mode 100644 index 0000000..7691f39 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyNodeProperty.swift @@ -0,0 +1,44 @@ +// +// AnyNodeProperty.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics +/// A property of a node. The node property holds a provider and a container +protocol AnyNodeProperty { + + /// Returns true if the property needs to recompute its stored value + func needsUpdate(frame: CGFloat) -> Bool + + /// Updates the property for the frame + func update(frame: CGFloat) + + /// The stored value container for the property + var valueContainer: AnyValueContainer { get } + + /// The value provider for the property + var valueProvider: AnyValueProvider { get } + + /// The Type of the value provider + var valueType: Any.Type { get } + + /// Sets the value provider for the property. + func setProvider(provider: AnyValueProvider) +} + +extension AnyNodeProperty { + + /// Returns the most recently computed value for the keypath, returns nil if property wasn't found + func getValueOfType() -> T? { + return valueContainer.value as? T + } + + /// Returns the most recently computed value for the keypath, returns nil if property wasn't found + func getValue() -> Any? { + return valueContainer.value + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyValueContainer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyValueContainer.swift new file mode 100644 index 0000000..96def0b --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/AnyValueContainer.swift @@ -0,0 +1,26 @@ +// +// AnyValueContainer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics + +/// The container for the value of a property. +protocol AnyValueContainer: AnyObject { + + /// The stored value of the container + var value: Any { get } + + /// Notifies the provider that it should update its container + func setNeedsUpdate() + + /// When true the container needs to have its value updated by its provider + var needsUpdate: Bool { get } + + /// The frame time of the last provided update + var lastUpdateFrame: CGFloat { get } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/KeypathSearchable.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/KeypathSearchable.swift new file mode 100644 index 0000000..a0dbf20 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/KeypathSearchable.swift @@ -0,0 +1,24 @@ +// +// KeypathSettable.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +import QuartzCore + +/// Protocol that provides keypath search functionality. Returns all node properties associated with a keypath. +protocol KeypathSearchable { + + /// The name of the Keypath + var keypathName: String { get } + + /// A list of properties belonging to the keypath. + var keypathProperties: [String : AnyNodeProperty] { get } + + /// Children Keypaths + var childKeypaths: [KeypathSearchable] { get } + + var keypathLayer: CALayer? { get } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/NodePropertyMap.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/NodePropertyMap.swift new file mode 100644 index 0000000..0fdc178 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/Protocols/NodePropertyMap.swift @@ -0,0 +1,42 @@ +// +// NodePropertyMap.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/21/19. +// + +import Foundation +import QuartzCore + +protocol NodePropertyMap { + var properties: [AnyNodeProperty] { get } +} + +extension NodePropertyMap { + + var childKeypaths: [KeypathSearchable] { + return [] + } + + var keypathLayer: CALayer? { + return nil + } + + /// Checks if the node's local contents need to be rebuilt. + func needsLocalUpdate(frame: CGFloat) -> Bool { + for property in properties { + if property.needsUpdate(frame: frame) { + return true + } + } + return false + } + + /// Rebuilds only the local nodes that have an update for the frame + func updateNodeProperties(frame: CGFloat) { + properties.forEach { (property) in + property.update(frame: frame) + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueContainer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueContainer.swift new file mode 100644 index 0000000..7f13644 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueContainer.swift @@ -0,0 +1,43 @@ +// +// ValueContainer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics + +/// A container for a node value that is Typed to T. +class ValueContainer: AnyValueContainer { + + private(set) var lastUpdateFrame: CGFloat = CGFloat.infinity + + func setValue(_ value: Any, forFrame: CGFloat) { + if let typedValue = value as? T { + needsUpdate = false + lastUpdateFrame = forFrame + outputValue = typedValue + } + } + + func setNeedsUpdate() { + needsUpdate = true + } + + var value: Any { + return outputValue as Any + } + + var outputValue: T { + didSet { + needsUpdate = false + } + } + + init(_ value: T) { + self.outputValue = value + } + + fileprivate(set) var needsUpdate: Bool = true +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/GroupInterpolator.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/GroupInterpolator.swift new file mode 100644 index 0000000..9470cd6 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/GroupInterpolator.swift @@ -0,0 +1,33 @@ +// +// KeyframeGroupInterpolator.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/22/19. +// + +import Foundation +import CoreGraphics + +/// A value provider that produces an array of values from an array of Keyframe Interpolators +final class GroupInterpolator: AnyValueProvider where ValueType: Interpolatable { + var valueType: Any.Type { + return [ValueType].self + } + + func hasUpdate(frame: CGFloat) -> Bool { + let updated = keyframeInterpolators.first(where: {$0.hasUpdate(frame: frame)}) + return updated != nil + } + + func value(frame: CGFloat) -> Any { + let output = keyframeInterpolators.map({$0.value(frame: frame) as! ValueType}) + return output + } + + /// Initialize with an array of array of keyframes. + init(keyframeGroups: ContiguousArray>>) { + self.keyframeInterpolators = ContiguousArray(keyframeGroups.map({KeyframeInterpolator(keyframes: $0)})) + } + let keyframeInterpolators: ContiguousArray> + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/KeyframeInterpolator.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/KeyframeInterpolator.swift new file mode 100644 index 0000000..baf46fe --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/KeyframeInterpolator.swift @@ -0,0 +1,233 @@ +// +// KeyframeInterpolator.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/15/19. +// + +import Foundation +import CoreGraphics + +/// A value provider that produces a value at Time from a group of keyframes +final class KeyframeInterpolator: AnyValueProvider where ValueType: Interpolatable { + + init(keyframes: ContiguousArray>) { + self.keyframes = keyframes + } + let keyframes: ContiguousArray> + + var valueType: Any.Type { + return ValueType.self + } + + /** + Returns true to trigger a frame update for this interpolator. + + An interpolator will be asked if it needs to update every frame. + If the interpolator needs updating it will be asked to compute its value for + the given frame. + + Cases a keyframe should not be updated: + - If time is in span and leading keyframe is hold + - If time is after the last keyframe. + - If time is before the first keyframe + + Cases for updating a keyframe: + - If time is in the span, and is not a hold + - If time is outside of the span, and there are more keyframes + - If a value delegate is set + - If leading and trailing are both nil. + */ + func hasUpdate(frame: CGFloat) -> Bool { + if lastUpdatedFrame == nil { + return true + } + + if let leading = leadingKeyframe, + trailingKeyframe == nil, + leading.time < frame { + /// Frame is after bounds of keyframes + return false + } + if let trailing = trailingKeyframe, + leadingKeyframe == nil, + frame < trailing.time { + /// Frame is before bounds of keyframes + return false + } + if let leading = leadingKeyframe, + let trailing = trailingKeyframe, + leading.isHold, + leading.time < frame, + frame < trailing.time { + return false + } + return true + } + + fileprivate var lastUpdatedFrame: CGFloat? + + @discardableResult + func value(frame: CGFloat) -> Any { + // First set the keyframe span for the frame. + updateSpanIndices(frame: frame) + lastUpdatedFrame = frame + // If only one keyframe return its value + let progress: CGFloat + let value: ValueType + + if let leading = leadingKeyframe, + let trailing = trailingKeyframe { + /// We have leading and trailing keyframe. + progress = leading.interpolatedProgress(trailing, keyTime: frame) + value = leading.interpolate(trailing, progress: progress) + } else if let leading = leadingKeyframe { + progress = 0 + value = leading.value + } else if let trailing = trailingKeyframe { + progress = 1 + value = trailing.value + } else { + /// Satisfy the compiler. + progress = 0 + value = keyframes[0].value + } + return value + } + + fileprivate var leadingIndex: Int? = nil + fileprivate var trailingIndex: Int? = nil + fileprivate var leadingKeyframe: Keyframe? = nil + fileprivate var trailingKeyframe: Keyframe? = nil + + /// Finds the appropriate Leading and Trailing keyframe index for the given time. + fileprivate func updateSpanIndices(frame: CGFloat) { + guard keyframes.count > 0 else { + leadingIndex = nil + trailingIndex = nil + leadingKeyframe = nil + trailingKeyframe = nil + return + } + + /** + This function searches through the array to find the span of two keyframes + that contain the current time. + + We could use Array.first(where:) but that would search through the entire array + each frame. + Instead we track the last used index and search either forwards or + backwards from there. This reduces the iterations and complexity from + + O(n), where n is the length of the sequence to + O(n), where n is the number of items after or before the last used index. + + */ + + if keyframes.count == 1 { + /// Only one keyframe. Set it as first and move on. + leadingIndex = 0 + trailingIndex = nil + leadingKeyframe = keyframes[0] + trailingKeyframe = nil + return + } + + /// Sets the initial keyframes. This is often only needed for the first check. + if leadingIndex == nil && + trailingIndex == nil { + if frame < keyframes[0].time { + /// Time is before the first keyframe. Set it as the trailing. + trailingIndex = 0 + } else { + /// Time is after the first keyframe. Set the keyframe and the trailing. + leadingIndex = 0 + trailingIndex = 1 + } + } + + if let currentTrailing = trailingIndex, + keyframes[currentTrailing].time <= frame { + /// Time is after the current span. Iterate forward. + var newLeading = currentTrailing + var keyframeFound: Bool = false + while !keyframeFound { + + leadingIndex = newLeading + trailingIndex = keyframes.validIndex(newLeading + 1) + + guard let trailing = trailingIndex else { + /// We have reached the end of our keyframes. Time is after the last keyframe. + keyframeFound = true + continue + } + if frame < keyframes[trailing].time { + /// Keyframe in current span. + keyframeFound = true + continue + } + /// Advance the array. + newLeading = trailing + } + + } else if let currentLeading = leadingIndex, + frame < keyframes[currentLeading].time { + + /// Time is before the current span. Iterate backwards + var newTrailing = currentLeading + + var keyframeFound: Bool = false + while !keyframeFound { + + leadingIndex = keyframes.validIndex(newTrailing - 1) + trailingIndex = newTrailing + + guard let leading = leadingIndex else { + /// We have reached the end of our keyframes. Time is after the last keyframe. + keyframeFound = true + continue + } + if keyframes[leading].time <= frame { + /// Keyframe in current span. + keyframeFound = true + continue + } + /// Step back + newTrailing = leading + } + } + if let keyFrame = leadingIndex { + leadingKeyframe = keyframes[keyFrame] + } else { + leadingKeyframe = nil + } + + if let keyFrame = trailingIndex { + trailingKeyframe = keyframes[keyFrame] + } else { + trailingKeyframe = nil + } + } +} + +fileprivate extension Array { + + func validIndex(_ index: Int) -> Int? { + if 0 <= index, index < endIndex { + return index + } + return nil + } + +} + +fileprivate extension ContiguousArray { + + func validIndex(_ index: Int) -> Int? { + if 0 <= index, index < endIndex { + return index + } + return nil + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/SingleValueProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/SingleValueProvider.swift new file mode 100644 index 0000000..ba24402 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/ValueProviders/SingleValueProvider.swift @@ -0,0 +1,38 @@ +// +// SingleValueProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import QuartzCore + +/// Returns a value for every frame. +final class SingleValueProvider: AnyValueProvider { + + var value: ValueType { + didSet { + hasUpdate = true + } + } + + init(_ value: ValueType) { + self.value = value + } + + var valueType: Any.Type { + return ValueType.self + } + + func hasUpdate(frame: CGFloat) -> Bool { + return hasUpdate + } + + func value(frame: CGFloat) -> Any { + hasUpdate = false + return value + } + + private var hasUpdate: Bool = true +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/ModifierNodes/TrimPathNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/ModifierNodes/TrimPathNode.swift new file mode 100644 index 0000000..3a1ab24 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/ModifierNodes/TrimPathNode.swift @@ -0,0 +1,247 @@ +// +// TrimPathNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/23/19. +// + +import Foundation +import QuartzCore + +final class TrimPathProperties: NodePropertyMap, KeypathSearchable { + + init(trim: Trim) { + self.keypathName = trim.name + self.start = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.start.keyframes)) + self.end = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.end.keyframes)) + self.offset = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.offset.keyframes)) + self.type = trim.trimType + self.keypathProperties = [ + "Start" : start, + "End" : end, + "Offset" : offset + ] + self.properties = Array(keypathProperties.values) + } + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + let keypathName: String + + let start: NodeProperty + let end: NodeProperty + let offset: NodeProperty + let type: TrimType +} + +final class TrimPathNode: AnimatorNode { + + let properties: TrimPathProperties + + fileprivate let upstreamPaths: [PathOutputNode] + + init(parentNode: AnimatorNode?, trim: Trim, upstreamPaths: [PathOutputNode]) { + self.outputNode = PassThroughOutputNode(parent: parentNode?.outputNode) + self.parentNode = parentNode + self.properties = TrimPathProperties(trim: trim) + self.upstreamPaths = upstreamPaths + } + + // MARK: Animator Node + var propertyMap: NodePropertyMap & KeypathSearchable { + return properties + } + + let parentNode: AnimatorNode? + let outputNode: NodeOutput + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true + + func forceUpstreamOutputUpdates() -> Bool { + return hasLocalUpdates || hasUpstreamUpdates + } + + func rebuildOutputs(frame: CGFloat) { + /// Make sure there is a trim. + let startValue = properties.start.value.cgFloatValue * 0.01 + let endValue = properties.end.value.cgFloatValue * 0.01 + let start = min(startValue, endValue) + let end = max(startValue, endValue) + + let offset = properties.offset.value.cgFloatValue.truncatingRemainder(dividingBy: 360) / 360 + + /// No need to trim, it's a full path + if start == 0, end == 1 { + return + } + + /// All paths are empty. + if start == end { + for pathContainer in upstreamPaths { + pathContainer.removePaths(updateFrame: frame) + } + return + } + + if properties.type == .simultaneously { + /// Just trim each path + for pathContainer in upstreamPaths { + let pathObjects = pathContainer.removePaths(updateFrame: frame) + for path in pathObjects { + // We are treating each compount path as an individual path. Its subpaths are treated as a whole. + pathContainer.appendPath(path.trim(fromPosition: start, toPosition: end, offset: offset, trimSimultaneously: false), updateFrame: frame) + } + } + return + } + + /// Individual path trimming. + + /// Brace yourself for the below code. + + /// Normalize lengths with offset. + var startPosition = (start+offset).truncatingRemainder(dividingBy: 1) + var endPosition = (end+offset).truncatingRemainder(dividingBy: 1) + + if startPosition < 0 { + startPosition = 1 + startPosition + } + + if endPosition < 0 { + endPosition = 1 + endPosition + } + if startPosition == 1 { + startPosition = 0 + } + if endPosition == 0 { + endPosition = 1 + } + + + /// First get the total length of all paths. + var totalLength: CGFloat = 0 + upstreamPaths.forEach({ totalLength = totalLength + $0.totalLength }) + + /// Now determine the start and end cut lengths + let startLength = startPosition * totalLength + let endLength = endPosition * totalLength + var pathStart: CGFloat = 0 + + /// Now loop through all path containers + for pathContainer in upstreamPaths { + + let pathEnd = pathStart + pathContainer.totalLength + + if !startLength.isInRange(pathStart, pathEnd) && + endLength.isInRange(pathStart, pathEnd) { + // pathStart|=======E----------------------|pathEnd + // Cut path components, removing after end. + + let pathCutLength = endLength - pathStart + let subpaths = pathContainer.removePaths(updateFrame: frame) + var subpathStart: CGFloat = 0 + for path in subpaths { + let subpathEnd = subpathStart + path.length + if pathCutLength < subpathEnd { + /// This is the subpath that needs to be cut. + let cutLength = pathCutLength - subpathStart + let newPath = path.trim(fromPosition: 0, toPosition: cutLength / path.length, offset: 0, trimSimultaneously: false) + pathContainer.appendPath(newPath, updateFrame: frame) + break + } else { + /// Add to container and move on + pathContainer.appendPath(path, updateFrame: frame) + } + if pathCutLength == subpathEnd { + /// Right on the end. The next subpath is not included. Break. + break + } + subpathStart = subpathEnd + } + + } else if !endLength.isInRange(pathStart, pathEnd) && + startLength.isInRange(pathStart, pathEnd) { + // pathStart|-------S======================|pathEnd + // + + // Cut path components, removing before beginning. + let pathCutLength = startLength - pathStart + // Clear paths from container + let subpaths = pathContainer.removePaths(updateFrame: frame) + var subpathStart: CGFloat = 0 + for path in subpaths { + let subpathEnd = subpathStart + path.length + + if subpathStart < pathCutLength, pathCutLength < subpathEnd { + /// This is the subpath that needs to be cut. + let cutLength = pathCutLength - subpathStart + let newPath = path.trim(fromPosition: cutLength / path.length, toPosition: 1, offset: 0, trimSimultaneously: false) + pathContainer.appendPath(newPath, updateFrame: frame) + } else if pathCutLength <= subpathStart { + pathContainer.appendPath(path, updateFrame: frame) + } + subpathStart = subpathEnd + } + } else if endLength.isInRange(pathStart, pathEnd) && + startLength.isInRange(pathStart, pathEnd) { + // pathStart|-------S============E---------|endLength + // pathStart|=====E----------------S=======|endLength + // trim from path beginning to endLength. + + // Cut path components, removing before beginnings. + let startCutLength = startLength - pathStart + let endCutLength = endLength - pathStart + // Clear paths from container + let subpaths = pathContainer.removePaths(updateFrame: frame) + var subpathStart: CGFloat = 0 + for path in subpaths { + + let subpathEnd = subpathStart + path.length + + if !startCutLength.isInRange(subpathStart, subpathEnd) && + !endCutLength.isInRange(subpathStart, subpathEnd) { + // The whole path is included. Add + // S|==============================|E + pathContainer.appendPath(path, updateFrame: frame) + + } else if startCutLength.isInRange(subpathStart, subpathEnd) && + !endCutLength.isInRange(subpathStart, subpathEnd) { + /// The start of the path needs to be trimmed + // |-------S======================|E + let cutLength = startCutLength - subpathStart + let newPath = path.trim(fromPosition: cutLength / path.length, toPosition: 1, offset: 0, trimSimultaneously: false) + pathContainer.appendPath(newPath, updateFrame: frame) + } else if !startCutLength.isInRange(subpathStart, subpathEnd) && + endCutLength.isInRange(subpathStart, subpathEnd) { + // S|=======E----------------------| + let cutLength = endCutLength - subpathStart + let newPath = path.trim(fromPosition: 0, toPosition: cutLength / path.length, offset: 0, trimSimultaneously: false) + pathContainer.appendPath(newPath, updateFrame: frame) + break + } else if startCutLength.isInRange(subpathStart, subpathEnd) && + endCutLength.isInRange(subpathStart, subpathEnd) { + // |-------S============E---------| + let cutFromLength = startCutLength - subpathStart + let cutToLength = endCutLength - subpathStart + let newPath = path.trim(fromPosition: cutFromLength / path.length, toPosition: cutToLength / path.length, offset: 0, trimSimultaneously: false) + pathContainer.appendPath(newPath, updateFrame: frame) + break + } + + subpathStart = subpathEnd + } + } else if (endLength <= pathStart && pathEnd <= startLength) || + (startLength <= pathStart && endLength <= pathStart) || + (pathEnd <= startLength && pathEnd <= endLength) { + /// The Path needs to be cleared + pathContainer.removePaths(updateFrame: frame) + } + + pathStart = pathEnd + } + + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/GroupOutputNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/GroupOutputNode.swift new file mode 100644 index 0000000..2f48762 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/GroupOutputNode.swift @@ -0,0 +1,70 @@ +// +// TransformNodeOutput.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics +import QuartzCore + +class GroupOutputNode: NodeOutput { + + init(parent: NodeOutput?, rootNode: NodeOutput?) { + self.parent = parent + self.rootNode = rootNode + } + + let parent: NodeOutput? + let rootNode: NodeOutput? + var isEnabled: Bool = true + + private(set) var outputPath: CGPath? = nil + private(set) var transform: CATransform3D = CATransform3DIdentity + + func setTransform(_ xform: CATransform3D, forFrame: CGFloat) { + transform = xform + outputPath = nil + } + + func hasOutputUpdates(_ forFrame: CGFloat) -> Bool { + guard isEnabled else { + let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false + outputPath = parent?.outputPath + return upstreamUpdates + } + + let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false + if upstreamUpdates { + outputPath = nil + } + let rootUpdates = rootNode?.hasOutputUpdates(forFrame) ?? false + if rootUpdates { + outputPath = nil + } + + var localUpdates: Bool = false + if outputPath == nil { + localUpdates = true + + let newPath = CGMutablePath() + if let parentNode = parent, let parentPath = parentNode.outputPath { + /// First add parent path. + newPath.addPath(parentPath) + } + var xform = CATransform3DGetAffineTransform(transform) + if let rootNode = rootNode, + let rootPath = rootNode.outputPath, + let xformedPath = rootPath.copy(using: &xform) { + /// Now add root path. Note root path is transformed. + newPath.addPath(xformedPath) + } + + outputPath = newPath + } + + return upstreamUpdates || localUpdates + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PassThroughOutputNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PassThroughOutputNode.swift new file mode 100644 index 0000000..8a911db --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PassThroughOutputNode.swift @@ -0,0 +1,43 @@ +// +// PassThroughOutputNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics + +class PassThroughOutputNode: NodeOutput { + + init(parent: NodeOutput?) { + self.parent = parent + } + + let parent: NodeOutput? + + var hasUpdate: Bool = false + var isEnabled: Bool = true + + func hasOutputUpdates(_ forFrame: CGFloat) -> Bool { + /// Changes to this node do not affect downstream nodes. + let parentUpdate = parent?.hasOutputUpdates(forFrame) ?? false + /// Changes to upstream nodes do, however, affect this nodes state. + hasUpdate = hasUpdate || parentUpdate + return parentUpdate + } + + var outputPath: CGPath? { + if let parent = parent { + return parent.outputPath + } + return nil + } + + func hasRenderUpdates(_ forFrame: CGFloat) -> Bool { + /// Return true if there are upstream updates or if this node has updates + let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false + hasUpdate = hasUpdate || upstreamUpdates + return hasUpdate + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PathOutputNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PathOutputNode.swift new file mode 100644 index 0000000..f71655b --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PathOutputNode.swift @@ -0,0 +1,88 @@ +// +// PathNodeOutput.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics + +/// A node that has an output of a BezierPath +class PathOutputNode: NodeOutput { + + init(parent: NodeOutput?) { + self.parent = parent + } + + let parent: NodeOutput? + + fileprivate(set) var outputPath: CGPath? = nil + + var lastUpdateFrame: CGFloat? = nil + var lastPathBuildFrame: CGFloat? = nil + var isEnabled: Bool = true + + func hasOutputUpdates(_ forFrame: CGFloat) -> Bool { + guard isEnabled else { + let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false + outputPath = parent?.outputPath + return upstreamUpdates + } + + /// Ask if parent was updated + let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false + + /// If parent was updated and the path hasn't been built for this frame, clear the path. + if upstreamUpdates && lastPathBuildFrame != forFrame { + outputPath = nil + } + + if outputPath == nil { + /// If the path is clear, build the new path. + lastPathBuildFrame = forFrame + let newPath = CGMutablePath() + if let parentNode = parent, let parentPath = parentNode.outputPath { + newPath.addPath(parentPath) + } + for path in pathObjects { + for subPath in path.paths { + newPath.addPath(subPath.cgPath()) + } + } + outputPath = newPath + } + + /// Return true if there were upstream updates or if this node was updated. + return upstreamUpdates || (lastUpdateFrame == forFrame) + } + + // MARK: Internal + + fileprivate(set) var totalLength: CGFloat = 0 + fileprivate(set) var pathObjects: [CompoundBezierPath] = [] + + @discardableResult func removePaths(updateFrame: CGFloat?) -> [CompoundBezierPath] { + lastUpdateFrame = updateFrame + let returnPaths = pathObjects + outputPath = nil + totalLength = 0 + pathObjects = [] + return returnPaths + } + + func setPath(_ path: BezierPath, updateFrame: CGFloat) { + lastUpdateFrame = updateFrame + outputPath = nil + totalLength = path.length + pathObjects = [CompoundBezierPath(path: path)] + } + + func appendPath(_ path: CompoundBezierPath, updateFrame: CGFloat) { + lastUpdateFrame = updateFrame + outputPath = nil + totalLength = totalLength + path.length + pathObjects.append(path) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/FillRenderer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/FillRenderer.swift new file mode 100644 index 0000000..dc78121 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/FillRenderer.swift @@ -0,0 +1,72 @@ +// +// FillRenderer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import QuartzCore +import CoreGraphics + +extension FillRule { + var cgFillRule: CGPathFillRule { + switch self { + case .evenOdd: + return .evenOdd + default: + return .winding + } + } + + var caFillRule: CAShapeLayerFillRule { + switch self { + case .evenOdd: + return CAShapeLayerFillRule.evenOdd + default: + return CAShapeLayerFillRule.nonZero + } + } +} + +/// A rendered for a Path Fill +final class FillRenderer: PassThroughOutputNode, Renderable { + + let shouldRenderInContext: Bool = false + + func updateShapeLayer(layer: CAShapeLayer) { + layer.fillColor = color + layer.opacity = Float(opacity) + layer.fillRule = fillRule.caFillRule + hasUpdate = false + } + + var color: CGColor? { + didSet { + hasUpdate = true + } + } + + var opacity: CGFloat = 0 { + didSet { + hasUpdate = true + } + } + + var fillRule: FillRule = .none { + didSet { + hasUpdate = true + } + } + + func render(_ inContext: CGContext) { + guard inContext.path != nil && inContext.path!.isEmpty == false else { + return + } + guard let color = color else { return } + hasUpdate = false + inContext.setAlpha(opacity * 0.01) + inContext.setFillColor(color) + inContext.fillPath(using: fillRule.cgFillRule) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientFillRenderer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientFillRenderer.swift new file mode 100644 index 0000000..cd54a28 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientFillRenderer.swift @@ -0,0 +1,126 @@ +// +// GradientFillRenderer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import QuartzCore + +/// A rendered for a Path Fill +final class GradientFillRenderer: PassThroughOutputNode, Renderable { + + var shouldRenderInContext: Bool = true + + func updateShapeLayer(layer: CAShapeLayer) { + // Not applicable + } + + func render(_ inContext: CGContext) { + guard inContext.path != nil && inContext.path!.isEmpty == false else { + return + } + hasUpdate = false + var alphaColors = [CGColor]() + var alphaLocations = [CGFloat]() + + var gradientColors = [CGColor]() + var colorLocations = [CGFloat]() + let colorSpace = CGColorSpaceCreateDeviceRGB() + let maskColorSpace = CGColorSpaceCreateDeviceGray() + for i in 0.. ix, let color = CGColor(colorSpace: colorSpace, components: [colors[ix + 1], colors[ix + 2], colors[ix + 3], 1]) { + gradientColors.append(color) + colorLocations.append(colors[ix]) + } + } + + var drawMask = false + for i in stride(from: (numberOfColors * 4), to: colors.endIndex, by: 2) { + let alpha = colors[i + 1] + if alpha < 1 { + drawMask = true + } + if let color = CGColor(colorSpace: maskColorSpace, components: [alpha, 1]) { + alphaLocations.append(colors[i]) + alphaColors.append(color) + } + } + + inContext.setAlpha(opacity) + inContext.clip() + + /// First draw a mask is necessary. + if drawMask { + guard let maskGradient = CGGradient(colorsSpace: maskColorSpace, + colors: alphaColors as CFArray, + locations: alphaLocations), + let maskContext = CGContext(data: nil, + width: inContext.width, + height: inContext.height, + bitsPerComponent: 8, + bytesPerRow: inContext.width, + space: maskColorSpace, + bitmapInfo: 0) else { return } + let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(maskContext.height)) + maskContext.concatenate(flipVertical) + maskContext.concatenate(inContext.ctm) + if type == .linear { + maskContext.drawLinearGradient(maskGradient, start: start, end: end, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation]) + } else { + maskContext.drawRadialGradient(maskGradient, startCenter: start, startRadius: 0, endCenter: start, endRadius: start.distanceTo(end), options: [.drawsAfterEndLocation, .drawsBeforeStartLocation]) + } + /// Clips the gradient + if let alphaMask = maskContext.makeImage() { + inContext.clip(to: inContext.boundingBoxOfClipPath, mask: alphaMask) + } + } + + /// Now draw the gradient + guard let gradient = CGGradient(colorsSpace: colorSpace, colors: gradientColors as CFArray, locations: colorLocations) else { return } + if type == .linear { + inContext.drawLinearGradient(gradient, start: start, end: end, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation]) + } else { + inContext.drawRadialGradient(gradient, startCenter: start, startRadius: 0, endCenter: start, endRadius: start.distanceTo(end), options: [.drawsAfterEndLocation, .drawsBeforeStartLocation]) + } + } + + var start: CGPoint = .zero { + didSet { + hasUpdate = true + } + } + + var numberOfColors: Int = 0 { + didSet { + hasUpdate = true + } + } + + var colors: [CGFloat] = [] { + didSet { + hasUpdate = true + } + } + + var end: CGPoint = .zero { + didSet { + hasUpdate = true + } + } + + var opacity: CGFloat = 0 { + didSet { + hasUpdate = true + } + } + + var type: GradientType = .none { + didSet { + hasUpdate = true + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientStrokeRenderer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientStrokeRenderer.swift new file mode 100644 index 0000000..7639fa8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/GradientStrokeRenderer.swift @@ -0,0 +1,59 @@ +// +// GradientStrokeRenderer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import QuartzCore + +// MARK: - Renderer + +final class GradientStrokeRenderer: PassThroughOutputNode, Renderable { + + override func hasOutputUpdates(_ forFrame: CGFloat) -> Bool { + let updates = super.hasOutputUpdates(forFrame) + return updates || strokeRender.hasUpdate || gradientRender.hasUpdate + } + + var shouldRenderInContext: Bool = true + + func updateShapeLayer(layer: CAShapeLayer) { + /// Not Applicable + } + + let strokeRender: StrokeRenderer + let gradientRender: GradientFillRenderer + + override init(parent: NodeOutput?) { + self.strokeRender = StrokeRenderer(parent: nil) + self.gradientRender = GradientFillRenderer(parent: nil) + self.strokeRender.color = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1, 1, 1, 1]) + super.init(parent: parent) + } + + func render(_ inContext: CGContext) { + guard inContext.path != nil && inContext.path!.isEmpty == false else { + return + } + + strokeRender.hasUpdate = false + hasUpdate = false + gradientRender.hasUpdate = false + + strokeRender.setupForStroke(inContext) + + inContext.replacePathWithStrokedPath() + + /// Now draw the gradient. + gradientRender.render(inContext) + + } + + func renderBoundsFor(_ boundingBox: CGRect) -> CGRect { + return strokeRender.renderBoundsFor(boundingBox) + } + + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/StrokeRenderer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/StrokeRenderer.swift new file mode 100644 index 0000000..e8d0e8f --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/Renderables/StrokeRenderer.swift @@ -0,0 +1,162 @@ +// +// StrokeRenderer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import QuartzCore + +extension LineJoin { + var cgLineJoin: CGLineJoin { + switch self { + case .bevel: + return .bevel + case .none: + return .miter + case .miter: + return .miter + case .round: + return .round + } + } + + var caLineJoin: CAShapeLayerLineJoin { + switch self { + case .none: + return CAShapeLayerLineJoin.miter + case .miter: + return CAShapeLayerLineJoin.miter + case .round: + return CAShapeLayerLineJoin.round + case .bevel: + return CAShapeLayerLineJoin.bevel + } + } +} + +extension LineCap { + var cgLineCap: CGLineCap { + switch self { + case .none: + return .butt + case .butt: + return .butt + case .round: + return .round + case .square: + return .square + } + } + + var caLineCap: CAShapeLayerLineCap { + switch self { + case .none: + return CAShapeLayerLineCap.butt + case .butt: + return CAShapeLayerLineCap.butt + case .round: + return CAShapeLayerLineCap.round + case .square: + return CAShapeLayerLineCap.square + } + } +} + +// MARK: - Renderer + +/// A rendered that renders a stroke on a path. +final class StrokeRenderer: PassThroughOutputNode, Renderable { + + var shouldRenderInContext: Bool = false + + var color: CGColor? { + didSet { + hasUpdate = true + } + } + + var opacity: CGFloat = 0 { + didSet { + hasUpdate = true + } + } + + var width: CGFloat = 0 { + didSet { + hasUpdate = true + } + } + + var miterLimit: CGFloat = 0 { + didSet { + hasUpdate = true + } + } + + var lineCap: LineCap = .none { + didSet { + hasUpdate = true + } + } + + var lineJoin: LineJoin = .none { + didSet { + hasUpdate = true + } + } + + var dashPhase: CGFloat? { + didSet { + hasUpdate = true + } + } + + var dashLengths: [CGFloat]? { + didSet { + hasUpdate = true + } + } + + func renderBoundsFor(_ boundingBox: CGRect) -> CGRect { + return boundingBox.insetBy(dx: -width, dy: -width) + } + + func setupForStroke(_ inContext: CGContext) { + inContext.setLineWidth(width) + inContext.setMiterLimit(miterLimit) + inContext.setLineCap(lineCap.cgLineCap) + inContext.setLineJoin(lineJoin.cgLineJoin) + if let dashPhase = dashPhase, let lengths = dashLengths { + inContext.setLineDash(phase: dashPhase, lengths: lengths) + } else { + inContext.setLineDash(phase: 0, lengths: []) + } + } + + func render(_ inContext: CGContext) { + guard inContext.path != nil && inContext.path!.isEmpty == false else { + return + } + guard let color = color else { return } + hasUpdate = false + setupForStroke(inContext) + inContext.setAlpha(opacity) + inContext.setStrokeColor(color) + inContext.strokePath() + } + + func updateShapeLayer(layer: CAShapeLayer) { + layer.strokeColor = color + layer.opacity = Float(opacity) + layer.lineWidth = width + layer.lineJoin = lineJoin.caLineJoin + layer.lineCap = lineCap.caLineCap + layer.lineDashPhase = dashPhase ?? 0 + layer.fillColor = nil + if let dashPattern = dashLengths { + layer.lineDashPattern = dashPattern.map({ NSNumber(value: Double($0)) }) + } + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/EllipseNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/EllipseNode.swift new file mode 100644 index 0000000..bc68e44 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/EllipseNode.swift @@ -0,0 +1,109 @@ +// +// EllipseNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/17/19. +// + +import Foundation +import QuartzCore + +final class EllipseNodeProperties: NodePropertyMap, KeypathSearchable { + + var keypathName: String + + init(ellipse: Ellipse) { + self.keypathName = ellipse.name + self.direction = ellipse.direction + self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: ellipse.position.keyframes)) + self.size = NodeProperty(provider: KeyframeInterpolator(keyframes: ellipse.size.keyframes)) + self.keypathProperties = [ + "Position" : position, + "Size" : size + ] + self.properties = Array(keypathProperties.values) + } + + let direction: PathDirection + let position: NodeProperty + let size: NodeProperty + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] +} + +final class EllipseNode: AnimatorNode, PathNode { + + let pathOutput: PathOutputNode + + let properties: EllipseNodeProperties + + init(parentNode: AnimatorNode?, ellipse: Ellipse) { + self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) + self.properties = EllipseNodeProperties(ellipse: ellipse) + self.parentNode = parentNode + } + + // MARK: Animator Node + + var propertyMap: NodePropertyMap & KeypathSearchable { + return properties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet{ + self.pathOutput.isEnabled = self.isEnabled + } + } + + func rebuildOutputs(frame: CGFloat) { + let ellipseSize = properties.size.value.sizeValue + let center = properties.position.value.pointValue + + // Unfortunately we HAVE to manually build out the ellipse. + // Every Apple method constructs an ellipse from the 3 o-clock position + // After effects constructs from the Noon position. + // After effects does clockwise, but also has a flag for reversed. + + var half = ellipseSize * 0.5 + if properties.direction == .counterClockwise { + half.width = half.width * -1 + } + + + let q1 = CGPoint(x: center.x, y: center.y - half.height) + let q2 = CGPoint(x: center.x + half.width, y: center.y) + let q3 = CGPoint(x: center.x, y: center.y + half.height) + let q4 = CGPoint(x: center.x - half.width, y: center.y) + + let cp = half * EllipseNode.ControlPointConstant + + var path = BezierPath(startPoint: CurveVertex(point: q1, + inTangentRelative: CGPoint(x: -cp.width, y: 0), + outTangentRelative: CGPoint(x: cp.width, y: 0))) + path.addVertex(CurveVertex(point: q2, + inTangentRelative: CGPoint(x: 0, y: -cp.height), + outTangentRelative: CGPoint(x: 0, y: cp.height))) + + path.addVertex(CurveVertex(point: q3, + inTangentRelative: CGPoint(x: cp.width, y: 0), + outTangentRelative: CGPoint(x: -cp.width, y: 0))) + + path.addVertex(CurveVertex(point: q4, + inTangentRelative: CGPoint(x: 0, y: cp.height), + outTangentRelative: CGPoint(x: 0, y: -cp.height))) + + path.addVertex(CurveVertex(point: q1, + inTangentRelative: CGPoint(x: -cp.width, y: 0), + outTangentRelative: CGPoint(x: cp.width, y: 0))) + path.close() + pathOutput.setPath(path, updateFrame: frame) + } + + static let ControlPointConstant: CGFloat = 0.55228 + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/PolygonNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/PolygonNode.swift new file mode 100644 index 0000000..b3663e8 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/PolygonNode.swift @@ -0,0 +1,132 @@ +// +// PolygonNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/21/19. +// + +import Foundation +import QuartzCore + +final class PolygonNodeProperties: NodePropertyMap, KeypathSearchable { + + var keypathName: String + + var childKeypaths: [KeypathSearchable] = [] + + init(star: Star) { + self.keypathName = star.name + self.direction = star.direction + self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes)) + self.outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes)) + self.outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes)) + self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes)) + self.points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes)) + self.keypathProperties = [ + "Position" : position, + "Outer Radius" : outerRadius, + "Outer Roundedness" : outerRoundedness, + "Rotation" : rotation, + "Points" : points + ] + self.properties = Array(keypathProperties.values) + } + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + + let direction: PathDirection + let position: NodeProperty + let outerRadius: NodeProperty + let outerRoundedness: NodeProperty + let rotation: NodeProperty + let points: NodeProperty +} + +final class PolygonNode: AnimatorNode, PathNode { + + let properties: PolygonNodeProperties + + let pathOutput: PathOutputNode + + init(parentNode: AnimatorNode?, star: Star) { + self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) + self.properties = PolygonNodeProperties(star: star) + self.parentNode = parentNode + } + + // MARK: Animator Node + + var propertyMap: NodePropertyMap & KeypathSearchable { + return properties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet{ + self.pathOutput.isEnabled = self.isEnabled + } + } + + /// Magic number needed for constructing path. + static let PolygonConstant: CGFloat = 0.25 + + func rebuildOutputs(frame: CGFloat) { + let outerRadius = properties.outerRadius.value.cgFloatValue + let outerRoundedness = properties.outerRoundedness.value.cgFloatValue * 0.01 + let numberOfPoints = properties.points.value.cgFloatValue + let rotation = properties.rotation.value.cgFloatValue + let position = properties.position.value.pointValue + + var currentAngle = (rotation - 90).toRadians() + let anglePerPoint = ((2 * CGFloat.pi) / numberOfPoints) + + var point = CGPoint(x: (outerRadius * cos(currentAngle)), + y: (outerRadius * sin(currentAngle))) + var vertices = [CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero)] + + var previousPoint = point + currentAngle += anglePerPoint; + for _ in 0.. + let size: NodeProperty + let cornerRadius: NodeProperty + +} + +final class RectangleNode: AnimatorNode, PathNode { + + let properties: RectNodeProperties + + let pathOutput: PathOutputNode + + init(parentNode: AnimatorNode?, rectangle: Rectangle) { + self.properties = RectNodeProperties(rectangle: rectangle) + self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) + self.parentNode = parentNode + } + + // MARK: Animator Node + + var propertyMap: NodePropertyMap & KeypathSearchable { + return properties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet{ + self.pathOutput.isEnabled = self.isEnabled + } + } + + func rebuildOutputs(frame: CGFloat) { + + let size = properties.size.value.sizeValue * 0.5 + let radius = min(min(properties.cornerRadius.value.cgFloatValue, size.width) , size.height) + let position = properties.position.value.pointValue + var bezierPath = BezierPath() + let points: [CurveVertex] + + if radius <= 0 { + /// No Corners + points = [ + /// Lead In + CurveVertex(point: CGPoint(x: size.width, y: -size.height), + inTangentRelative: .zero, + outTangentRelative: .zero) + .translated(position), + /// Corner 1 + CurveVertex(point: CGPoint(x: size.width, y: size.height), + inTangentRelative: .zero, + outTangentRelative: .zero) + .translated(position), + /// Corner 2 + CurveVertex(point: CGPoint(x: -size.width, y: size.height), + inTangentRelative: .zero, + outTangentRelative: .zero) + .translated(position), + /// Corner 3 + CurveVertex(point: CGPoint(x: -size.width, y: -size.height), + inTangentRelative: .zero, + outTangentRelative: .zero) + .translated(position), + /// Corner 4 + CurveVertex(point: CGPoint(x: size.width, y: -size.height), + inTangentRelative: .zero, + outTangentRelative: .zero) + .translated(position), + ] + } else { + let controlPoint = radius * EllipseNode.ControlPointConstant + points = [ + /// Lead In + CurveVertex( + CGPoint(x: radius, y: 0), + CGPoint(x: radius, y: 0), + CGPoint(x: radius, y: 0)) + .translated(CGPoint(x: -radius, y: radius)) + .translated(CGPoint(x: size.width, y: -size.height)) + .translated(position), + /// Corner 1 + CurveVertex( + CGPoint(x: radius, y: 0), // In tangent + CGPoint(x: radius, y: 0), // Point + CGPoint(x: radius, y: controlPoint)) + .translated(CGPoint(x: -radius, y: -radius)) + .translated(CGPoint(x: size.width, y: size.height)) + .translated(position), + CurveVertex( + CGPoint(x: controlPoint, y: radius), // In tangent + CGPoint(x: 0, y: radius), // Point + CGPoint(x: 0, y: radius)) // Out Tangent + .translated(CGPoint(x: -radius, y: -radius)) + .translated(CGPoint(x: size.width, y: size.height)) + .translated(position), + /// Corner 2 + CurveVertex( + CGPoint(x: 0, y: radius), // In tangent + CGPoint(x: 0, y: radius), // Point + CGPoint(x: -controlPoint, y: radius))// Out tangent + .translated(CGPoint(x: radius, y: -radius)) + .translated(CGPoint(x: -size.width, y: size.height)) + .translated(position), + CurveVertex( + CGPoint(x: -radius, y: controlPoint), // In tangent + CGPoint(x: -radius, y: 0), // Point + CGPoint(x: -radius, y: 0)) // Out tangent + .translated(CGPoint(x: radius, y: -radius)) + .translated(CGPoint(x: -size.width, y: size.height)) + .translated(position), + /// Corner 3 + CurveVertex( + CGPoint(x: -radius, y: 0), // In tangent + CGPoint(x: -radius, y: 0), // Point + CGPoint(x: -radius, y: -controlPoint)) // Out tangent + .translated(CGPoint(x: radius, y: radius)) + .translated(CGPoint(x: -size.width, y: -size.height)) + .translated(position), + CurveVertex( + CGPoint(x: -controlPoint, y: -radius), // In tangent + CGPoint(x: 0, y: -radius), // Point + CGPoint(x: 0, y: -radius)) // Out tangent + .translated(CGPoint(x: radius, y: radius)) + .translated(CGPoint(x: -size.width, y: -size.height)) + .translated(position), + /// Corner 4 + CurveVertex( + CGPoint(x: 0, y: -radius), // In tangent + CGPoint(x: 0, y: -radius), // Point + CGPoint(x: controlPoint, y: -radius)) // Out tangent + .translated(CGPoint(x: -radius, y: radius)) + .translated(CGPoint(x: size.width, y: -size.height)) + .translated(position), + CurveVertex( + CGPoint(x: radius, y: -controlPoint), // In tangent + CGPoint(x: radius, y: 0), // Point + CGPoint(x: radius, y: 0)) // Out tangent + .translated(CGPoint(x: -radius, y: radius)) + .translated(CGPoint(x: size.width, y: -size.height)) + .translated(position), + ] + } + let reversed = properties.direction == .counterClockwise + let pathPoints = reversed ? points.reversed() : points + for point in pathPoints { + bezierPath.addVertex(reversed ? point.reversed() : point) + } + bezierPath.close() + pathOutput.setPath(bezierPath, updateFrame: frame) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift new file mode 100644 index 0000000..ea9383b --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift @@ -0,0 +1,61 @@ +// +// PathNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/16/19. +// + +import Foundation +import CoreGraphics + +final class ShapeNodeProperties: NodePropertyMap, KeypathSearchable { + + var keypathName: String + + init(shape: Shape) { + self.keypathName = shape.name + self.path = NodeProperty(provider: KeyframeInterpolator(keyframes: shape.path.keyframes)) + self.keypathProperties = [ + "Path" : path + ] + self.properties = Array(keypathProperties.values) + } + + let path: NodeProperty + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + +} + +final class ShapeNode: AnimatorNode, PathNode { + + let properties: ShapeNodeProperties + + let pathOutput: PathOutputNode + + init(parentNode: AnimatorNode?, shape: Shape) { + self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) + self.properties = ShapeNodeProperties(shape: shape) + self.parentNode = parentNode + } + + // MARK: Animator Node + var propertyMap: NodePropertyMap & KeypathSearchable { + return properties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet{ + self.pathOutput.isEnabled = self.isEnabled + } + } + + func rebuildOutputs(frame: CGFloat) { + pathOutput.setPath(properties.path.value, updateFrame: frame) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/StarNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/StarNode.swift new file mode 100644 index 0000000..c305029 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/StarNode.swift @@ -0,0 +1,183 @@ +// +// StarNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/21/19. +// + +import Foundation +import QuartzCore + +final class StarNodeProperties: NodePropertyMap, KeypathSearchable { + + var keypathName: String + + init(star: Star) { + self.keypathName = star.name + self.direction = star.direction + self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes)) + self.outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes)) + self.outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes)) + if let innerRadiusKeyframes = star.innerRadius?.keyframes { + self.innerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: innerRadiusKeyframes)) + } else { + self.innerRadius = NodeProperty(provider: SingleValueProvider(Vector1D(0))) + } + if let innderRoundedness = star.innerRoundness?.keyframes { + self.innerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: innderRoundedness)) + } else { + self.innerRoundedness = NodeProperty(provider: SingleValueProvider(Vector1D(0))) + } + self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes)) + self.points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes)) + self.keypathProperties = [ + "Position" : position, + "Outer Radius" : outerRadius, + "Outer Roundedness" : outerRoundedness, + "Inner Radius" : innerRadius, + "Inner Roundedness" : innerRoundedness, + "Rotation" : rotation, + "Points" : points + ] + self.properties = Array(keypathProperties.values) + } + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + + let direction: PathDirection + let position: NodeProperty + let outerRadius: NodeProperty + let outerRoundedness: NodeProperty + let innerRadius: NodeProperty + let innerRoundedness: NodeProperty + let rotation: NodeProperty + let points: NodeProperty +} + +final class StarNode: AnimatorNode, PathNode { + + let properties: StarNodeProperties + + let pathOutput: PathOutputNode + + init(parentNode: AnimatorNode?, star: Star) { + self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) + self.properties = StarNodeProperties(star: star) + self.parentNode = parentNode + } + + // MARK: Animator Node + var propertyMap: NodePropertyMap & KeypathSearchable { + return properties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet{ + self.pathOutput.isEnabled = self.isEnabled + } + } + + /// Magic number needed for building path data + static let PolystarConstant: CGFloat = 0.47829 + + func rebuildOutputs(frame: CGFloat) { + let outerRadius = properties.outerRadius.value.cgFloatValue + let innerRadius = properties.innerRadius.value.cgFloatValue + let outerRoundedness = properties.outerRoundedness.value.cgFloatValue * 0.01 + let innerRoundedness = properties.innerRoundedness.value.cgFloatValue * 0.01 + let numberOfPoints = properties.points.value.cgFloatValue + let rotation = properties.rotation.value.cgFloatValue + let position = properties.position.value.pointValue + + var currentAngle = (rotation - 90).toRadians() + let anglePerPoint = (2 * CGFloat.pi) / numberOfPoints + let halfAnglePerPoint = anglePerPoint / 2.0 + let partialPointAmount = numberOfPoints - floor(numberOfPoints) + + var point: CGPoint = .zero + + var partialPointRadius: CGFloat = 0 + if partialPointAmount != 0 { + currentAngle += halfAnglePerPoint * (1 - partialPointAmount) + partialPointRadius = innerRadius + partialPointAmount * (outerRadius - innerRadius) + point.x = (partialPointRadius * cos(currentAngle)) + point.y = (partialPointRadius * sin(currentAngle)) + currentAngle += anglePerPoint * partialPointAmount / 2 + } else { + point.x = (outerRadius * cos(currentAngle)) + point.y = (outerRadius * sin(currentAngle)) + currentAngle += halfAnglePerPoint + } + + var vertices = [CurveVertex]() + vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero)) + + var previousPoint = point + var longSegment = false + let numPoints: Int = Int(ceil(numberOfPoints) * 2) + for i in 0.. + let position: NodeProperty + let scale: NodeProperty + let rotation: NodeProperty + let opacity: NodeProperty + let skew: NodeProperty + let skewAxis: NodeProperty + + var caTransform: CATransform3D { + return CATransform3D.makeTransform(anchor: anchor.value.pointValue, + position: position.value.pointValue, + scale: scale.value.sizeValue, + rotation: rotation.value.cgFloatValue, + skew: skew.value.cgFloatValue, + skewAxis: skewAxis.value.cgFloatValue) + } +} + +final class GroupNode: AnimatorNode { + + // MARK: Properties + let groupOutput: GroupOutputNode + + let properties: GroupNodeProperties + + let rootNode: AnimatorNode? + + var container: ShapeContainerLayer = ShapeContainerLayer() + + // MARK: Initializer + init(name: String, parentNode: AnimatorNode?, tree: NodeTree) { + self.parentNode = parentNode + self.keypathName = name + self.rootNode = tree.rootNode + self.properties = GroupNodeProperties(transform: tree.transform) + self.groupOutput = GroupOutputNode(parent: parentNode?.outputNode, rootNode: rootNode?.outputNode) + var childKeypaths: [KeypathSearchable] = tree.childrenNodes + childKeypaths.append(properties) + self.childKeypaths = childKeypaths + + for childContainer in tree.renderContainers { + container.insertRenderLayer(childContainer) + } + } + + // MARK: Keypath Searchable + + let keypathName: String + + let childKeypaths: [KeypathSearchable] + + var keypathLayer: CALayer? { + return container + } + + // MARK: Animator Node Protocol + + var propertyMap: NodePropertyMap & KeypathSearchable { + return properties + } + + var outputNode: NodeOutput { + return groupOutput + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet { + container.isHidden = !isEnabled + } + } + + func performAdditionalLocalUpdates(frame: CGFloat, forceLocalUpdate: Bool) -> Bool { + return rootNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false + } + + func performAdditionalOutputUpdates(_ frame: CGFloat, forceOutputUpdate: Bool) { + rootNode?.updateOutputs(frame, forceOutputUpdate: forceOutputUpdate) + } + + func rebuildOutputs(frame: CGFloat) { + container.opacity = Float(properties.opacity.value.cgFloatValue) * 0.01 + container.transform = properties.caTransform + groupOutput.setTransform(container.transform, forFrame: frame) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/FillNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/FillNode.swift new file mode 100644 index 0000000..28847bf --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/FillNode.swift @@ -0,0 +1,76 @@ +// +// FillNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/17/19. +// + +import Foundation +import CoreGraphics + +final class FillNodeProperties: NodePropertyMap, KeypathSearchable { + + var keypathName: String + + init(fill: Fill) { + self.keypathName = fill.name + self.color = NodeProperty(provider: KeyframeInterpolator(keyframes: fill.color.keyframes)) + self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: fill.opacity.keyframes)) + self.type = fill.fillRule + self.keypathProperties = [ + "Opacity" : opacity, + "Color" : color + ] + self.properties = Array(keypathProperties.values) + } + + let opacity: NodeProperty + let color: NodeProperty + let type: FillRule + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + +} + +final class FillNode: AnimatorNode, RenderNode { + + let fillRender: FillRenderer + var renderer: NodeOutput & Renderable { + return fillRender + } + + let fillProperties: FillNodeProperties + + init(parentNode: AnimatorNode?, fill: Fill) { + self.fillRender = FillRenderer(parent: parentNode?.outputNode) + self.fillProperties = FillNodeProperties(fill: fill) + self.parentNode = parentNode + } + + // MARK: Animator Node Protocol + + var propertyMap: NodePropertyMap & KeypathSearchable { + return fillProperties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet { + fillRender.isEnabled = isEnabled + } + } + + func localUpdatesPermeateDownstream() -> Bool { + return false + } + + func rebuildOutputs(frame: CGFloat) { + fillRender.color = fillProperties.color.value.cgColorValue + fillRender.opacity = fillProperties.opacity.value.cgFloatValue * 0.01 + fillRender.fillRule = fillProperties.type + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientFillNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientFillNode.swift new file mode 100644 index 0000000..733f235 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientFillNode.swift @@ -0,0 +1,90 @@ +// +// GradientFillNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/22/19. +// + +import Foundation +import QuartzCore + +final class GradientFillProperties: NodePropertyMap, KeypathSearchable { + + init(gradientfill: GradientFill) { + self.keypathName = gradientfill.name + self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.opacity.keyframes)) + self.startPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.startPoint.keyframes)) + self.endPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.endPoint.keyframes)) + self.colors = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.colors.keyframes)) + self.gradientType = gradientfill.gradientType + self.numberOfColors = gradientfill.numberOfColors + self.keypathProperties = [ + "Opacity" : opacity, + "Start Point" : startPoint, + "End Point" : endPoint, + "Colors" : colors + ] + self.properties = Array(keypathProperties.values) + } + + var keypathName: String + + let opacity: NodeProperty + let startPoint: NodeProperty + let endPoint: NodeProperty + let colors: NodeProperty<[Double]> + + let gradientType: GradientType + let numberOfColors: Int + + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + +} + +final class GradientFillNode: AnimatorNode, RenderNode { + + let fillRender: GradientFillRenderer + + var renderer: NodeOutput & Renderable { + return fillRender + } + + let fillProperties: GradientFillProperties + + init(parentNode: AnimatorNode?, gradientFill: GradientFill) { + self.fillRender = GradientFillRenderer(parent: parentNode?.outputNode) + self.fillProperties = GradientFillProperties(gradientfill: gradientFill) + self.parentNode = parentNode + } + + // MARK: Animator Node Protocol + + var propertyMap: NodePropertyMap & KeypathSearchable { + return fillProperties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet { + fillRender.isEnabled = isEnabled + } + } + + func localUpdatesPermeateDownstream() -> Bool { + return false + } + + func rebuildOutputs(frame: CGFloat) { + fillRender.start = fillProperties.startPoint.value.pointValue + fillRender.end = fillProperties.endPoint.value.pointValue + fillRender.opacity = fillProperties.opacity.value.cgFloatValue * 0.01 + fillRender.colors = fillProperties.colors.value.map { CGFloat($0) } + fillRender.type = fillProperties.gradientType + fillRender.numberOfColors = fillProperties.numberOfColors + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientStrokeNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientStrokeNode.swift new file mode 100644 index 0000000..eacc1d2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/GradientStrokeNode.swift @@ -0,0 +1,143 @@ +// +// GradientStrokeNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/23/19. +// + +import Foundation +import CoreGraphics + +// MARK: - Properties + +final class GradientStrokeProperties: NodePropertyMap, KeypathSearchable { + + var keypathName: String + + init(gradientStroke: GradientStroke) { + self.keypathName = gradientStroke.name + self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.opacity.keyframes)) + self.startPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.startPoint.keyframes)) + self.endPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.endPoint.keyframes)) + self.colors = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.colors.keyframes)) + self.gradientType = gradientStroke.gradientType + self.numberOfColors = gradientStroke.numberOfColors + self.width = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.width.keyframes)) + self.miterLimit = CGFloat(gradientStroke.miterLimit) + self.lineCap = gradientStroke.lineCap + self.lineJoin = gradientStroke.lineJoin + + if let dashes = gradientStroke.dashPattern { + var dashPatterns = ContiguousArray>>() + var dashPhase = ContiguousArray>() + for dash in dashes { + if dash.type == .offset { + dashPhase = dash.value.keyframes + } else { + dashPatterns.append(dash.value.keyframes) + } + } + self.dashPattern = NodeProperty(provider: GroupInterpolator(keyframeGroups: dashPatterns)) + self.dashPhase = NodeProperty(provider: KeyframeInterpolator(keyframes: dashPhase)) + } else { + self.dashPattern = NodeProperty(provider: SingleValueProvider([Vector1D]())) + self.dashPhase = NodeProperty(provider: SingleValueProvider(Vector1D(0))) + } + self.keypathProperties = [ + "Opacity" : opacity, + "Start Point" : startPoint, + "End Point" : endPoint, + "Colors" : colors, + "Stroke Width" : width, + "Dashes" : dashPattern, + "Dash Phase" : dashPhase + ] + self.properties = Array(keypathProperties.values) + } + + let opacity: NodeProperty + let startPoint: NodeProperty + let endPoint: NodeProperty + let colors: NodeProperty<[Double]> + let width: NodeProperty + + let dashPattern: NodeProperty<[Vector1D]> + let dashPhase: NodeProperty + + let lineCap: LineCap + let lineJoin: LineJoin + let miterLimit: CGFloat + let gradientType: GradientType + let numberOfColors: Int + + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + +} + +// MARK: - Node + +final class GradientStrokeNode: AnimatorNode, RenderNode { + + let strokeRender: GradientStrokeRenderer + + var renderer: NodeOutput & Renderable { + return strokeRender + } + + let strokeProperties: GradientStrokeProperties + + init(parentNode: AnimatorNode?, gradientStroke: GradientStroke) { + self.strokeRender = GradientStrokeRenderer(parent: parentNode?.outputNode) + self.strokeProperties = GradientStrokeProperties(gradientStroke: gradientStroke) + self.parentNode = parentNode + } + + // MARK: Animator Node Protocol + + var propertyMap: NodePropertyMap & KeypathSearchable { + return strokeProperties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet { + strokeRender.isEnabled = isEnabled + } + } + + func localUpdatesPermeateDownstream() -> Bool { + return false + } + + func rebuildOutputs(frame: CGFloat) { + /// Update gradient properties + strokeRender.gradientRender.start = strokeProperties.startPoint.value.pointValue + strokeRender.gradientRender.end = strokeProperties.endPoint.value.pointValue + strokeRender.gradientRender.opacity = strokeProperties.opacity.value.cgFloatValue + strokeRender.gradientRender.colors = strokeProperties.colors.value.map { CGFloat($0) } + strokeRender.gradientRender.type = strokeProperties.gradientType + strokeRender.gradientRender.numberOfColors = strokeProperties.numberOfColors + + /// Now update stroke properties + strokeRender.strokeRender.opacity = strokeProperties.opacity.value.cgFloatValue + strokeRender.strokeRender.width = strokeProperties.width.value.cgFloatValue + strokeRender.strokeRender.miterLimit = strokeProperties.miterLimit + strokeRender.strokeRender.lineCap = strokeProperties.lineCap + strokeRender.strokeRender.lineJoin = strokeProperties.lineJoin + + /// Get dash lengths + let dashLengths = strokeProperties.dashPattern.value.map { $0.cgFloatValue } + if dashLengths.count > 0 { + strokeRender.strokeRender.dashPhase = strokeProperties.dashPhase.value.cgFloatValue + strokeRender.strokeRender.dashLengths = dashLengths + } else { + strokeRender.strokeRender.dashLengths = nil + strokeRender.strokeRender.dashPhase = nil + } + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/StrokeNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/StrokeNode.swift new file mode 100644 index 0000000..21fc39c --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderNodes/StrokeNode.swift @@ -0,0 +1,127 @@ +// +// StrokeNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/22/19. +// + +import Foundation +import QuartzCore +// MARK: - Properties + +final class StrokeNodeProperties: NodePropertyMap, KeypathSearchable { + + init(stroke: Stroke) { + self.keypathName = stroke.name + self.color = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.color.keyframes)) + self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.opacity.keyframes)) + self.width = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.width.keyframes)) + self.miterLimit = CGFloat(stroke.miterLimit) + self.lineCap = stroke.lineCap + self.lineJoin = stroke.lineJoin + + if let dashes = stroke.dashPattern { + var dashPatterns = ContiguousArray>>() + var dashPhase = ContiguousArray>() + for dash in dashes { + if dash.type == .offset { + dashPhase = dash.value.keyframes + } else { + dashPatterns.append(dash.value.keyframes) + } + } + self.dashPattern = NodeProperty(provider: GroupInterpolator(keyframeGroups: dashPatterns)) + if dashPhase.count == 0 { + self.dashPhase = NodeProperty(provider: SingleValueProvider(Vector1D(0))) + } else { + self.dashPhase = NodeProperty(provider: KeyframeInterpolator(keyframes: dashPhase)) + } + } else { + self.dashPattern = NodeProperty(provider: SingleValueProvider([Vector1D]())) + self.dashPhase = NodeProperty(provider: SingleValueProvider(Vector1D(0))) + } + self.keypathProperties = [ + "Opacity" : opacity, + "Color" : color, + "Stroke Width" : width, + "Dashes" : dashPattern, + "Dash Phase" : dashPhase + ] + self.properties = Array(keypathProperties.values) + } + + let keypathName: String + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + + let opacity: NodeProperty + let color: NodeProperty + let width: NodeProperty + + let dashPattern: NodeProperty<[Vector1D]> + let dashPhase: NodeProperty + + let lineCap: LineCap + let lineJoin: LineJoin + let miterLimit: CGFloat + +} + +// MARK: - Node + +/// Node that manages stroking a path +final class StrokeNode: AnimatorNode, RenderNode { + + let strokeRender: StrokeRenderer + var renderer: NodeOutput & Renderable { + return strokeRender + } + + let strokeProperties: StrokeNodeProperties + + init(parentNode: AnimatorNode?, stroke: Stroke) { + self.strokeRender = StrokeRenderer(parent: parentNode?.outputNode) + self.strokeProperties = StrokeNodeProperties(stroke: stroke) + self.parentNode = parentNode + } + + // MARK: Animator Node Protocol + + var propertyMap: NodePropertyMap & KeypathSearchable { + return strokeProperties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true { + didSet { + strokeRender.isEnabled = isEnabled + } + } + + func localUpdatesPermeateDownstream() -> Bool { + return false + } + + func rebuildOutputs(frame: CGFloat) { + strokeRender.color = strokeProperties.color.value.cgColorValue + strokeRender.opacity = strokeProperties.opacity.value.cgFloatValue * 0.01 + strokeRender.width = strokeProperties.width.value.cgFloatValue + strokeRender.miterLimit = strokeProperties.miterLimit + strokeRender.lineCap = strokeProperties.lineCap + strokeRender.lineJoin = strokeProperties.lineJoin + + /// Get dash lengths + let dashLengths = strokeProperties.dashPattern.value.map { $0.cgFloatValue } + if dashLengths.count > 0 { + strokeRender.dashPhase = strokeProperties.dashPhase.value.cgFloatValue + strokeRender.dashLengths = dashLengths + } else { + strokeRender.dashLengths = nil + strokeRender.dashPhase = nil + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/Text/TextAnimatorNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/Text/TextAnimatorNode.swift new file mode 100644 index 0000000..600de32 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/Text/TextAnimatorNode.swift @@ -0,0 +1,251 @@ +// +// TextAnimatorNode.swift +// lottie-ios-iOS +// +// Created by Brandon Withrow on 2/19/19. +// + +import Foundation +import CoreGraphics +import QuartzCore + +final class TextAnimatorNodeProperties: NodePropertyMap, KeypathSearchable { + + let keypathName: String + + init(textAnimator: TextAnimator) { + self.keypathName = textAnimator.name + var properties = [String : AnyNodeProperty]() + + if let keyframeGroup = textAnimator.anchor { + self.anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Anchor"] = self.anchor + } else { + self.anchor = nil + } + + if let keyframeGroup = textAnimator.position { + self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Position"] = self.position + } else { + self.position = nil + } + + if let keyframeGroup = textAnimator.scale { + self.scale = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Scale"] = self.scale + } else { + self.scale = nil + } + + if let keyframeGroup = textAnimator.skew { + self.skew = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Skew"] = self.skew + } else { + self.skew = nil + } + + if let keyframeGroup = textAnimator.skewAxis { + self.skewAxis = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Skew Axis"] = self.skewAxis + } else { + self.skewAxis = nil + } + + if let keyframeGroup = textAnimator.rotation { + self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Rotation"] = self.rotation + } else { + self.rotation = nil + } + + if let keyframeGroup = textAnimator.opacity { + self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Opacity"] = self.opacity + } else { + self.opacity = nil + } + + if let keyframeGroup = textAnimator.strokeColor { + self.strokeColor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Stroke Color"] = self.strokeColor + } else { + self.strokeColor = nil + } + + if let keyframeGroup = textAnimator.fillColor { + self.fillColor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Fill Color"] = self.fillColor + } else { + self.fillColor = nil + } + + if let keyframeGroup = textAnimator.strokeWidth { + self.strokeWidth = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Stroke Width"] = self.strokeWidth + } else { + self.strokeWidth = nil + } + + if let keyframeGroup = textAnimator.tracking { + self.tracking = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes)) + properties["Tracking"] = self.tracking + } else { + self.tracking = nil + } + + self.keypathProperties = properties + + self.properties = Array(keypathProperties.values) + } + + let anchor: NodeProperty? + let position: NodeProperty? + let scale: NodeProperty? + let skew: NodeProperty? + let skewAxis: NodeProperty? + let rotation: NodeProperty? + let opacity: NodeProperty? + let strokeColor: NodeProperty? + let fillColor: NodeProperty? + let strokeWidth: NodeProperty? + let tracking: NodeProperty? + + let keypathProperties: [String : AnyNodeProperty] + let properties: [AnyNodeProperty] + + var caTransform: CATransform3D { + return CATransform3D.makeTransform(anchor: anchor?.value.pointValue ?? .zero, + position: position?.value.pointValue ?? .zero, + scale: scale?.value.sizeValue ?? CGSize(width: 100, height: 100), + rotation: rotation?.value.cgFloatValue ?? 0, + skew: skew?.value.cgFloatValue, + skewAxis: skewAxis?.value.cgFloatValue) + } +} + +final class TextOutputNode: NodeOutput { + + var parent: NodeOutput? { + return parentTextNode + } + + var parentTextNode: TextOutputNode? + var isEnabled: Bool = true + + init(parent: TextOutputNode?) { + self.parentTextNode = parent + } + + fileprivate var _xform: CATransform3D? + fileprivate var _opacity: CGFloat? + fileprivate var _strokeColor: CGColor? + fileprivate var _fillColor: CGColor? + fileprivate var _tracking: CGFloat? + fileprivate var _strokeWidth: CGFloat? + + var xform: CATransform3D { + get { + return _xform ?? parentTextNode?.xform ?? CATransform3DIdentity + } + set { + _xform = newValue + } + } + + var opacity: CGFloat { + get { + return _opacity ?? parentTextNode?.opacity ?? 1 + } + set { + _opacity = newValue + } + } + + var strokeColor: CGColor? { + get { + return _strokeColor ?? parentTextNode?.strokeColor + } + set { + _strokeColor = newValue + } + } + + var fillColor: CGColor? { + get { + return _fillColor ?? parentTextNode?.fillColor + } + set { + _fillColor = newValue + } + } + + var tracking: CGFloat { + get { + return _tracking ?? parentTextNode?.tracking ?? 0 + } + set { + _tracking = newValue + } + } + + var strokeWidth: CGFloat { + get { + return _strokeWidth ?? parentTextNode?.strokeWidth ?? 0 + } + set { + _strokeWidth = newValue + } + } + + + func hasOutputUpdates(_ forFrame: CGFloat) -> Bool { + // TODO Fix This + return true + } + + var outputPath: CGPath? + +} + +class TextAnimatorNode: AnimatorNode { + + let textOutputNode: TextOutputNode + + var outputNode: NodeOutput { + return textOutputNode + } + + let textAnimatorProperties: TextAnimatorNodeProperties + + init(parentNode: TextAnimatorNode?, textAnimator: TextAnimator) { + self.textOutputNode = TextOutputNode(parent: parentNode?.textOutputNode) + self.textAnimatorProperties = TextAnimatorNodeProperties(textAnimator: textAnimator) + self.parentNode = parentNode + } + + // MARK: Animator Node Protocol + + var propertyMap: NodePropertyMap & KeypathSearchable { + return textAnimatorProperties + } + + let parentNode: AnimatorNode? + var hasLocalUpdates: Bool = false + var hasUpstreamUpdates: Bool = false + var lastUpdateFrame: CGFloat? = nil + var isEnabled: Bool = true + + func localUpdatesPermeateDownstream() -> Bool { + return true + } + + func rebuildOutputs(frame: CGFloat) { + textOutputNode.xform = textAnimatorProperties.caTransform + textOutputNode.opacity = (textAnimatorProperties.opacity?.value.cgFloatValue ?? 100) * 0.01 + textOutputNode.strokeColor = textAnimatorProperties.strokeColor?.value.cgColorValue + textOutputNode.fillColor = textAnimatorProperties.fillColor?.value.cgColorValue + textOutputNode.tracking = textAnimatorProperties.tracking?.value.cgFloatValue ?? 1 + textOutputNode.strokeWidth = textAnimatorProperties.strokeWidth?.value.cgFloatValue ?? 0 + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/AnimatorNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/AnimatorNode.swift new file mode 100644 index 0000000..8724700 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/AnimatorNode.swift @@ -0,0 +1,197 @@ +// +// AnimatorNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/15/19. +// + +import Foundation +import QuartzCore + +/** + Defines the basic outputs of an animator node. + + */ +protocol NodeOutput { + + /// The parent node. + var parent: NodeOutput? { get } + + /// Returns true if there are any updates upstream. OutputPath must be built before returning. + func hasOutputUpdates(_ forFrame: CGFloat) -> Bool + + var outputPath: CGPath? { get } + + var isEnabled: Bool { get set } +} + +/** + The Animator Node is the base node in the render system tree. + + It defines a single node that has an output path and option input node. + At animation time the root animation node is asked to update its contents for + the current frame. + The node reaches up its chain of nodes until the first node that does not need + updating is found. Then each node updates its contents down the render pipeline. + Each node adds its local path to its input path and passes it forward. + + An animator node holds a group of interpolators. These interpolators determine + if the node needs an update for the current frame. + + */ +protocol AnimatorNode: AnyObject, KeypathSearchable { + + /** + The available properties of the Node. + + These properties are automatically updated each frame. + These properties are also settable and gettable through the dynamic + property system. + + */ + var propertyMap: NodePropertyMap & KeypathSearchable { get } + + /// The upstream input node + var parentNode: AnimatorNode? { get } + + /// The output of the node. + var outputNode: NodeOutput { get } + + /// Update the outputs of the node. Called if local contents were update or if outputsNeedUpdate returns true. + func rebuildOutputs(frame: CGFloat) + + /// Setters for marking current node state. + var isEnabled: Bool { get set } + var hasLocalUpdates: Bool { get set } + var hasUpstreamUpdates: Bool { get set } + var lastUpdateFrame: CGFloat? { get set } + + // MARK: Optional + + /// Marks if updates to this node affect nodes downstream. + func localUpdatesPermeateDownstream() -> Bool + func forceUpstreamOutputUpdates() -> Bool + + /// Called at the end of this nodes update cycle. Always called. Optional. + func performAdditionalLocalUpdates(frame: CGFloat, forceLocalUpdate: Bool) -> Bool + func performAdditionalOutputUpdates(_ frame: CGFloat, forceOutputUpdate: Bool) + + /// The default simply returns `hasLocalUpdates` + func shouldRebuildOutputs(frame: CGFloat) -> Bool +} + +/// Basic Node Logic +extension AnimatorNode { + + func shouldRebuildOutputs(frame: CGFloat) -> Bool { + return hasLocalUpdates + } + + func localUpdatesPermeateDownstream() -> Bool { + /// Optional override + return true + } + + func forceUpstreamOutputUpdates() -> Bool { + /// Optional + return false + } + + func performAdditionalLocalUpdates(frame: CGFloat, forceLocalUpdate: Bool) -> Bool { + /// Optional + return forceLocalUpdate + } + + func performAdditionalOutputUpdates(_ frame: CGFloat, forceOutputUpdate: Bool) { + /// Optional + } + + @discardableResult func updateOutputs(_ frame: CGFloat, forceOutputUpdate: Bool) -> Bool { + guard isEnabled else { + // Disabled node, pass through. + lastUpdateFrame = frame + return parentNode?.updateOutputs(frame, forceOutputUpdate: forceOutputUpdate) ?? false + } + + if forceOutputUpdate == false && lastUpdateFrame != nil && lastUpdateFrame! == frame { + /// This node has already updated for this frame. Go ahead and return the results. + return hasUpstreamUpdates || hasLocalUpdates + } + + /// Ask if this node should force output updates upstream. + let forceUpstreamUpdates = forceOutputUpdate || forceUpstreamOutputUpdates() + + /// Perform upstream output updates. Optionally mark upstream updates if any. + hasUpstreamUpdates = (parentNode?.updateOutputs(frame, forceOutputUpdate: forceUpstreamUpdates) ?? false || hasUpstreamUpdates) + + /// Perform additional local output updates + performAdditionalOutputUpdates(frame, forceOutputUpdate: forceUpstreamUpdates) + + /// If there are local updates, or if updates have been force, rebuild outputs + if forceUpstreamUpdates || shouldRebuildOutputs(frame: frame) { + lastUpdateFrame = frame + rebuildOutputs(frame: frame) + } + return hasUpstreamUpdates || hasLocalUpdates + } + + + /// Rebuilds the content of this node, and upstream nodes if necessary. + @discardableResult func updateContents(_ frame: CGFloat, forceLocalUpdate: Bool) -> Bool { + guard isEnabled else { + // Disabled node, pass through. + return parentNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false + } + + if forceLocalUpdate == false && lastUpdateFrame != nil && lastUpdateFrame! == frame { + /// This node has already updated for this frame. Go ahead and return the results. + return localUpdatesPermeateDownstream() ? hasUpstreamUpdates || hasLocalUpdates : hasUpstreamUpdates + } + + /// Are there local updates? If so mark the node. + hasLocalUpdates = forceLocalUpdate ? forceLocalUpdate : propertyMap.needsLocalUpdate(frame: frame) + + /// Were there upstream updates? If so mark the node + hasUpstreamUpdates = parentNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false + + /// Perform property updates if necessary. + if hasLocalUpdates { + /// Rebuild local properties + propertyMap.updateNodeProperties(frame: frame) + } + + /// Ask the node to perform any other updates it might have. + hasUpstreamUpdates = performAdditionalLocalUpdates(frame: frame, forceLocalUpdate: forceLocalUpdate) || hasUpstreamUpdates + + /// If the node can update nodes downstream, notify them, otherwise pass on any upstream updates downstream. + return localUpdatesPermeateDownstream() ? hasUpstreamUpdates || hasLocalUpdates : hasUpstreamUpdates + } + + func updateTree(_ frame: CGFloat, forceUpdates: Bool = false) { + updateContents(frame, forceLocalUpdate: forceUpdates) + updateOutputs(frame, forceOutputUpdate: forceUpdates) + } + +} + +extension AnimatorNode { + /// Default implementation for Keypath searchable. + /// Forward all calls to the propertyMap. + + var keypathName: String { + return propertyMap.keypathName + } + + var keypathProperties: [String : AnyNodeProperty] { + return propertyMap.keypathProperties + } + + var childKeypaths: [KeypathSearchable] { + return propertyMap.childKeypaths + } + + var keypathLayer: CALayer? { + return nil + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/PathNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/PathNode.swift new file mode 100644 index 0000000..e7b2bfb --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/PathNode.swift @@ -0,0 +1,20 @@ +// +// PathNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/17/19. +// + +import Foundation + +protocol PathNode { + var pathOutput: PathOutputNode { get } +} + +extension PathNode where Self: AnimatorNode { + + var outputNode: NodeOutput { + return pathOutput + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/RenderNode.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/RenderNode.swift new file mode 100644 index 0000000..4738f14 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Protocols/RenderNode.swift @@ -0,0 +1,57 @@ +// +// RenderNode.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/17/19. +// + +import Foundation +import CoreGraphics +import QuartzCore + +/// A protocol that defines a node that holds render instructions +protocol RenderNode { + var renderer: Renderable & NodeOutput { get } +} + +/// A protocol that defines anything with render instructions +protocol Renderable { + + /// The last frame in which this node was updated. + var hasUpdate: Bool { get } + + func hasRenderUpdates(_ forFrame: CGFloat) -> Bool + + /** + Determines if the renderer requires a custom context for drawing. + If yes the shape layer will perform a custom drawing pass. + If no the shape layer will be a standard CAShapeLayer + */ + var shouldRenderInContext: Bool { get } + + /// Passes in the CAShapeLayer to update + func updateShapeLayer(layer: CAShapeLayer) + + /// Asks the renderer what the renderable bounds is for the given box. + func renderBoundsFor(_ boundingBox: CGRect) -> CGRect + + /// Renders the shape in a custom context + func render(_ inContext: CGContext) +} + +extension RenderNode where Self: AnimatorNode { + + var outputNode: NodeOutput { + return renderer + } + +} + +extension Renderable { + + func renderBoundsFor(_ boundingBox: CGRect) -> CGRect { + /// Optional + return boundingBox + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeContainerLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeContainerLayer.swift new file mode 100644 index 0000000..84be9a2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeContainerLayer.swift @@ -0,0 +1,72 @@ +// +// ShapeContainerLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import QuartzCore + +/** + The base layer that holds Shapes and Shape Renderers + */ +class ShapeContainerLayer: CALayer { + + private(set) var renderLayers: [ShapeContainerLayer] = [] + + override init() { + super.init() + self.actions = [ + "position" : NSNull(), + "bounds" : NSNull(), + "anchorPoint" : NSNull(), + "transform" : NSNull(), + "opacity" : NSNull(), + "hidden" : NSNull(), + ] + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override init(layer: Any) { + guard let layer = layer as? ShapeContainerLayer else { + fatalError("init(layer:) wrong class.") + } + super.init(layer: layer) + } + + var renderScale: CGFloat = 1 { + didSet { + updateRenderScale() + } + } + + func insertRenderLayer(_ layer: ShapeContainerLayer) { + renderLayers.append(layer) + insertSublayer(layer, at: 0) + } + + func markRenderUpdates(forFrame: CGFloat) { + if self.hasRenderUpdate(forFrame: forFrame) { + self.rebuildContents(forFrame: forFrame) + } + guard self.isHidden == false else { return } + renderLayers.forEach { $0.markRenderUpdates(forFrame: forFrame) } + } + + func hasRenderUpdate(forFrame: CGFloat) -> Bool { + return false + } + + func rebuildContents(forFrame: CGFloat) { + /// Override + } + + func updateRenderScale() { + renderLayers.forEach( { $0.renderScale = renderScale } ) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeRenderLayer.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeRenderLayer.swift new file mode 100644 index 0000000..af98806 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeRenderLayer.swift @@ -0,0 +1,90 @@ +// +// RenderLayer.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/18/19. +// + +import Foundation +import QuartzCore + +/** + The layer responsible for rendering shape objects + */ +final class ShapeRenderLayer: ShapeContainerLayer { + + fileprivate(set) var renderer: Renderable & NodeOutput + + let shapeLayer: CAShapeLayer = CAShapeLayer() + + init(renderer: Renderable & NodeOutput) { + self.renderer = renderer + super.init() + self.anchorPoint = .zero + self.actions = [ + "position" : NSNull(), + "bounds" : NSNull(), + "anchorPoint" : NSNull(), + "path" : NSNull(), + "transform" : NSNull(), + "opacity" : NSNull(), + "hidden" : NSNull(), + ] + shapeLayer.actions = [ + "position" : NSNull(), + "bounds" : NSNull(), + "anchorPoint" : NSNull(), + "path" : NSNull(), + "fillColor" : NSNull(), + "strokeColor" : NSNull(), + "lineWidth" : NSNull(), + "miterLimit" : NSNull(), + "lineDashPhase" : NSNull(), + "hidden" : NSNull(), + ] + addSublayer(shapeLayer) + } + + override init(layer: Any) { + guard let layer = layer as? ShapeRenderLayer else { + fatalError("init(layer:) wrong class.") + } + self.renderer = layer.renderer + super.init(layer: layer) + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func hasRenderUpdate(forFrame: CGFloat) -> Bool { + self.isHidden = !renderer.isEnabled + guard self.isHidden == false else { return false } + return renderer.hasRenderUpdates(forFrame) + } + + override func rebuildContents(forFrame: CGFloat) { + + if renderer.shouldRenderInContext { + if let newPath = renderer.outputPath { + self.bounds = renderer.renderBoundsFor(newPath.boundingBox) + } else { + self.bounds = .zero + } + self.position = bounds.origin + self.setNeedsDisplay() + } else { + shapeLayer.path = renderer.outputPath + renderer.updateShapeLayer(layer: shapeLayer) + } + } + + override func draw(in ctx: CGContext) { + if let path = renderer.outputPath { + if !path.isEmpty { + ctx.addPath(path) + } + } + renderer.render(ctx) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Debugging/AnimatorNodeDebugging.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Debugging/AnimatorNodeDebugging.swift new file mode 100644 index 0000000..3421833 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Debugging/AnimatorNodeDebugging.swift @@ -0,0 +1,25 @@ +// +// AnimatorNodeDebugging.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/18/19. +// + +import Foundation + +extension AnimatorNode { + + func printNodeTree() { + parentNode?.printNodeTree() + print(String(describing: type(of: self))) + + if let group = self as? GroupNode { + print("* |Children") + group.rootNode?.printNodeTree() + print("*") + } else { + print("|") + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Debugging/LayerDebugging.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Debugging/LayerDebugging.swift new file mode 100644 index 0000000..c0e20fd --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Debugging/LayerDebugging.swift @@ -0,0 +1,203 @@ +// +// LayerDebugging.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/24/19. +// + +import Foundation +import QuartzCore + +struct LayerDebugStyle { + let anchorColor: CGColor + let boundsColor: CGColor + let anchorWidth: CGFloat + let boundsWidth: CGFloat +} + +protocol LayerDebugging { + var debugStyle: LayerDebugStyle { get } +} + +protocol CustomLayerDebugging { + func layerForDebugging() -> CALayer +} + +class DebugLayer: CALayer { + init(style: LayerDebugStyle) { + super.init() + zPosition = 1000 + bounds = CGRect(x: 0, y: 0, width: style.anchorWidth, height: style.anchorWidth) + backgroundColor = style.anchorColor + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +public extension CALayer { + + func logLayerTree(withIndent: Int = 0) { + var string = "" + for _ in 0...withIndent { + string = string + " " + } + string = string + "|_" + String(describing: self) + print(string) + if let sublayers = sublayers { + for sublayer in sublayers { + sublayer.logLayerTree(withIndent: withIndent + 1) + } + } + } + +} + +extension CompositionLayer: CustomLayerDebugging { + func layerForDebugging() -> CALayer { + return contentsLayer + } +} + +extension CALayer { + + func setDebuggingState(visible: Bool) { + + var sublayers = self.sublayers + if let cust = self as? CustomLayerDebugging { + sublayers = cust.layerForDebugging().sublayers + } + + if let sublayers = sublayers { + for i in 0.. LayerDebugStyle { + let colorSpace = CGColorSpaceCreateDeviceRGB() + + let anchorColor = CGColor(colorSpace: colorSpace, components: [1, 0, 0, 1])! + let boundsColor = CGColor(colorSpace: colorSpace, components: [1, 1, 0, 1])! + return LayerDebugStyle(anchorColor: anchorColor, + boundsColor: boundsColor, + anchorWidth: 10, + boundsWidth: 2) + } + + static func topLayerStyle() -> LayerDebugStyle { + let colorSpace = CGColorSpaceCreateDeviceRGB() + let anchorColor = CGColor(colorSpace: colorSpace, components: [1, 0.5, 0, 0])! + let boundsColor = CGColor(colorSpace: colorSpace, components: [0, 1, 0, 1])! + + return LayerDebugStyle(anchorColor: anchorColor, + boundsColor: boundsColor, + anchorWidth: 10, + boundsWidth: 2) + } + + static func nullLayerStyle() -> LayerDebugStyle { + let colorSpace = CGColorSpaceCreateDeviceRGB() + let anchorColor = CGColor(colorSpace: colorSpace, components: [0, 0, 1, 0])! + let boundsColor = CGColor(colorSpace: colorSpace, components: [0, 1, 0, 1])! + + return LayerDebugStyle(anchorColor: anchorColor, + boundsColor: boundsColor, + anchorWidth: 10, + boundsWidth: 2) + } + + static func shapeLayerStyle() -> LayerDebugStyle { + let colorSpace = CGColorSpaceCreateDeviceRGB() + let anchorColor = CGColor(colorSpace: colorSpace, components: [0, 1, 0, 0])! + let boundsColor = CGColor(colorSpace: colorSpace, components: [0, 1, 0, 1])! + + return LayerDebugStyle(anchorColor: anchorColor, + boundsColor: boundsColor, + anchorWidth: 10, + boundsWidth: 2) + } + + static func shapeRenderLayerStyle() -> LayerDebugStyle { + let colorSpace = CGColorSpaceCreateDeviceRGB() + let anchorColor = CGColor(colorSpace: colorSpace, components: [0, 1, 1, 0])! + let boundsColor = CGColor(colorSpace: colorSpace, components: [0, 1, 0, 1])! + + return LayerDebugStyle(anchorColor: anchorColor, + boundsColor: boundsColor, + anchorWidth: 10, + boundsWidth: 2) + } +} + +extension Array where Element == LayerModel { + + var parents: [Int] { + var array = [Int]() + for layer in self { + if let parent = layer.parent { + array.append(parent) + } else { + array.append(-1) + } + } + return array + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/AnimationKeypathExtension.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/AnimationKeypathExtension.swift new file mode 100644 index 0000000..24c86d3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/AnimationKeypathExtension.swift @@ -0,0 +1,256 @@ +// +// KeypathSearchableExtension.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +import QuartzCore + +extension KeypathSearchable { + + func animatorNodes(for keyPath: AnimationKeypath) -> [AnimatorNode]? { + // Make sure there is a current key path. + guard let currentKey = keyPath.currentKey else { return nil } + + // Now try popping the keypath for wildcard / child search + guard let nextKeypath = keyPath.popKey(keypathName) else { + // We may be on the final keypath. Check for match. + if let node = self as? AnimatorNode, + currentKey.equalsKeypath(keypathName) { + // This is the final keypath and matches self. Return.s + return [node] + } + /// Nope. Stop Search + return nil + } + + var results: [AnimatorNode] = [] + + if let node = self as? AnimatorNode, + nextKeypath.currentKey == nil { + // Keypath matched self and was the final keypath. + results.append(node) + } + + for childNode in childKeypaths { + // Check if the child has any nodes matching the next keypath. + if let foundNodes = childNode.animatorNodes(for: nextKeypath) { + results.append(contentsOf: foundNodes) + } + + // In this case the current key is fuzzy, and both child and self match the next keyname. Keep digging! + if currentKey.keyPathType == .fuzzyWildcard, + let nextKeypath = keyPath.nextKeypath, + nextKeypath.equalsKeypath(childNode.keypathName), + let foundNodes = childNode.animatorNodes(for: keyPath) { + results.append(contentsOf: foundNodes) + } + } + + guard results.count > 0 else { + return nil + } + + return results + } + + func nodeProperties(for keyPath: AnimationKeypath) -> [AnyNodeProperty]? { + guard let nextKeypath = keyPath.popKey(keypathName) else { + /// Nope. Stop Search + return nil + } + + /// Keypath matches in some way. Continue the search. + var results: [AnyNodeProperty] = [] + + /// Check if we have a property keypath yet + if let propertyKey = nextKeypath.propertyKey, + let property = keypathProperties[propertyKey] { + /// We found a property! + results.append(property) + } + + if nextKeypath.nextKeypath != nil { + /// Now check child keypaths. + for child in childKeypaths { + if let childProperties = child.nodeProperties(for: nextKeypath) { + results.append(contentsOf: childProperties) + } + } + } + + guard results.count > 0 else { + return nil + } + + return results + } + + func layer(for keyPath: AnimationKeypath) -> CALayer? { + if keyPath.nextKeypath == nil, let layerKey = keyPath.currentKey, layerKey.equalsKeypath(keypathName) { + /// We found our layer! + return keypathLayer + } + guard let nextKeypath = keyPath.popKey(keypathName) else { + /// Nope. Stop Search + return nil + } + + if nextKeypath.nextKeypath != nil { + /// Now check child keypaths. + for child in childKeypaths { + if let layer = child.layer(for: keyPath) { + return layer + } + } + } + return nil + } + + func logKeypaths(for keyPath: AnimationKeypath?) { + let newKeypath: AnimationKeypath + if let previousKeypath = keyPath { + newKeypath = previousKeypath.appendingKey(keypathName) + } else { + newKeypath = AnimationKeypath(keys: [keypathName]) + } + print(newKeypath.fullPath) + for key in keypathProperties.keys { + print(newKeypath.appendingKey(key).fullPath) + } + for child in childKeypaths { + child.logKeypaths(for: newKeypath) + } + } +} + +extension AnimationKeypath { + var currentKey: String? { + return keys.first + } + + var nextKeypath: String? { + guard keys.count > 1 else { + return nil + } + return keys[1] + } + + var propertyKey: String? { + if nextKeypath == nil { + /// There are no more keypaths. This is a property key. + return currentKey + } + if keys.count == 2, currentKey?.keyPathType == .fuzzyWildcard { + /// The next keypath is the last and the current is a fuzzy key. + return nextKeypath + } + return nil + } + + // Pops the top keypath from the stack if the keyname matches. + func popKey(_ keyname: String) -> AnimationKeypath? { + guard let currentKey = currentKey, + currentKey.equalsKeypath(keyname), + keys.count > 1 else { + // Current key either doesnt match or we are on the last key. + return nil + } + + // Pop the keypath from the stack and return the new stack. + let newKeys: [String] + + if currentKey.keyPathType == .fuzzyWildcard { + /// Dont remove if current key is a fuzzy wildcard, and if the next keypath doesnt equal keypathname + if let nextKeypath = nextKeypath, + nextKeypath.equalsKeypath(keyname) { + /// Remove next two keypaths. This keypath breaks the wildcard. + var oldKeys = keys + oldKeys.remove(at: 0) + oldKeys.remove(at: 0) + newKeys = oldKeys + } else { + newKeys = keys + } + } else { + var oldKeys = keys + oldKeys.remove(at: 0) + newKeys = oldKeys + } + + return AnimationKeypath(keys: newKeys) + } + + var fullPath: String { + return keys.joined(separator: ".") + } + + func appendingKey(_ key: String) -> AnimationKeypath { + var newKeys = keys + newKeys.append(key) + return AnimationKeypath(keys: newKeys) + } +} + + + +extension String { + var keyPathType: KeyType { + switch self { + case "*": + return .wildcard + case "**": + return .fuzzyWildcard + default: + return .specific + } + } + + func equalsKeypath(_ keyname: String) -> Bool { + if keyPathType == .wildcard || keyPathType == .fuzzyWildcard { + return true + } + if self == keyname { + return true + } + if let index = self.firstIndex(of: "*") { + // Wildcard search. + let prefix = String(self.prefix(upTo: index)) + let suffix = String(self.suffix(from: self.index(after: index))) + + if prefix.count > 0 { + // Match prefix. + if keyname.count < prefix.count { + return false + } + let testPrefix = String(keyname.prefix(upTo: keyname.index(keyname.startIndex, offsetBy: prefix.count))) + if testPrefix != prefix { + // Prefix doesnt match + return false + } + } + if suffix.count > 0 { + // Match suffix. + if keyname.count < suffix.count { + // Suffix doesnt match + return false + } + let index = keyname.index(keyname.endIndex, offsetBy: -suffix.count) + let testSuffix = String(keyname.suffix(from: index)) + if testSuffix != suffix { + return false + } + } + return true + } + return false + } +} + +enum KeyType { + case specific + case wildcard + case fuzzyWildcard +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/CGFloatExtensions.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/CGFloatExtensions.swift new file mode 100644 index 0000000..b7c0d9d --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/CGFloatExtensions.swift @@ -0,0 +1,149 @@ +// +// CGFloatExtensions.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/14/19. +// + +import Foundation +import QuartzCore + +extension CGFloat { + + func isInRangeOrEqual(_ from: CGFloat, _ to: CGFloat) -> Bool { + return (from <= self && self <= to) + } + + func isInRange(_ from: CGFloat, _ to: CGFloat) -> Bool { + return (from < self && self < to) + } + + var squared: CGFloat { + return self * self + } + + var cubed: CGFloat { + return self * self * self + } + + var cubicRoot: CGFloat { + return CGFloat(pow(Double(self), 1.0 / 3.0)) + } + + fileprivate static func SolveQuadratic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat) -> CGFloat { + var result = (-b + sqrt(b.squared - 4 * a * c)) / (2 * a); + guard !result.isInRangeOrEqual(0, 1) else { + return result + } + + result = (-b - sqrt(b.squared - 4 * a * c)) / (2 * a); + guard !result.isInRangeOrEqual(0, 1) else { + return result + } + + return -1; + } + + fileprivate static func SolveCubic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat, _ d: CGFloat) -> CGFloat { + if (a == 0) { + return SolveQuadratic(b, c, d) + } + if (d == 0) { + return 0 + } + let a = a + var b = b + var c = c + var d = d + b /= a + c /= a + d /= a + var q = (3.0 * c - b.squared) / 9.0 + let r = (-27.0 * d + b * (9.0 * c - 2.0 * b.squared)) / 54.0 + let disc = q.cubed + r.squared + let term1 = b / 3.0 + + if (disc > 0) { + var s = r + sqrt(disc) + s = (s < 0) ? -((-s).cubicRoot) : s.cubicRoot + var t = r - sqrt(disc) + t = (t < 0) ? -((-t).cubicRoot) : t.cubicRoot + + let result = -term1 + s + t; + if result.isInRangeOrEqual(0, 1) { + return result + } + } else if (disc == 0) { + let r13 = (r < 0) ? -((-r).cubicRoot) : r.cubicRoot; + + var result = -term1 + 2.0 * r13; + if result.isInRangeOrEqual(0, 1) { + return result + } + + result = -(r13 + term1); + if result.isInRangeOrEqual(0, 1) { + return result + } + + } else { + q = -q; + var dum1 = q * q * q; + dum1 = acos(r / sqrt(dum1)); + let r13 = 2.0 * sqrt(q); + + var result = -term1 + r13 * cos(dum1 / 3.0); + if result.isInRangeOrEqual(0, 1) { + return result + } + result = -term1 + r13 * cos((dum1 + 2.0 * .pi) / 3.0); + if result.isInRangeOrEqual(0, 1) { + return result + } + result = -term1 + r13 * cos((dum1 + 4.0 * .pi) / 3.0); + if result.isInRangeOrEqual(0, 1) { + return result + } + } + + return -1; + } + + func cubicBezierInterpolate(_ P0: CGPoint, _ P1: CGPoint, _ P2: CGPoint, _ P3: CGPoint) -> CGFloat { + var t: CGFloat + if (self == P0.x) { + // Handle corner cases explicitly to prevent rounding errors + t = 0 + } else if (self == P3.x) { + t = 1 + } else { + // Calculate t + let a = -P0.x + 3 * P1.x - 3 * P2.x + P3.x; + let b = 3 * P0.x - 6 * P1.x + 3 * P2.x; + let c = -3 * P0.x + 3 * P1.x; + let d = P0.x - self; + let tTemp = CGFloat.SolveCubic(a, b, c, d); + if (tTemp == -1) { + return -1; + } + t = tTemp + } + + // Calculate y from t + return (1 - t).cubed * P0.y + 3 * t * (1 - t).squared * P1.y + 3 * t.squared * (1 - t) * P2.y + t.cubed * P3.y; + } + + func cubicBezier(_ t: CGFloat, _ c1: CGFloat, _ c2: CGFloat, _ end: CGFloat) -> CGFloat { + let t_ = (1.0 - t) + let tt_ = t_ * t_ + let ttt_ = t_ * t_ * t_ + let tt = t * t + let ttt = t * t * t + + return self * ttt_ + + 3.0 * c1 * tt_ * t + + 3.0 * c2 * t_ * tt + + end * ttt; + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/MathKit.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/MathKit.swift new file mode 100644 index 0000000..7a2ad29 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/MathKit.swift @@ -0,0 +1,539 @@ +// +// MathKit.swift +// UIToolBox +// +// Created by Brandon Withrow on 10/10/18. +// +// From https://github.com/buba447/UIToolBox + +import Foundation +import CoreGraphics + +extension Int { + var cgFloat: CGFloat { + return CGFloat(self) + } +} + +extension Double { + var cgFloat: CGFloat { + return CGFloat(self) + } +} + +extension CGFloat: Interpolatable { + + + /** + Interpolates the receiver to the given number by Amount. + - Parameter toNumber: The number to interpolate to. + - Parameter amount: The amount to interpolate from 0-1 + + ``` + let number = 5 + let interpolated = number.interpolateTo(10, amount: 0.5) + print(interpolated) + // Result: 7.5 + ``` + + 1. The amount can be greater than one and less than zero. The interpolation will not be clipped. + */ + func interpolateTo(_ to: CGFloat, amount: CGFloat) -> CGFloat { + return self + ((to - self) * CGFloat(amount)) + } + + func interpolateTo(_ to: CGFloat, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> CGFloat { + return interpolateTo(to, amount: amount) + } + + func remap(fromLow: CGFloat, fromHigh: CGFloat, toLow: CGFloat, toHigh: CGFloat) -> CGFloat { + guard (fromHigh - fromLow) != 0 else { + // Would produce NAN + return 0 + } + return toLow + (self - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + } + + /** + Returns a value that is clamped between the two numbers + + 1. The order of arguments does not matter. + */ + func clamp(_ a: CGFloat, _ b: CGFloat) -> CGFloat { + return CGFloat(Double(self).clamp(Double(a), Double(b))) + } + + /** + Returns the difference between the receiver and the given number. + - Parameter absolute: If *true* (Default) the returned value will always be positive. + */ + func diff(_ a: CGFloat, absolute: Bool = true) -> CGFloat { + return absolute ? abs(a - self) : a - self + } + + func toRadians() -> CGFloat { return self * .pi / 180 } + func toDegrees() -> CGFloat { return self * 180 / .pi } + +} + +extension Double: Interpolatable { + + /** + Interpolates the receiver to the given number by Amount. + - Parameter toNumber: The number to interpolate to. + - Parameter amount: The amount to interpolate from 0-1 + + ``` + let number = 5 + let interpolated = number.interpolateTo(10, amount: 0.5) + print(interpolated) + // Result: 7.5 + ``` + + 1. The amount can be greater than one and less than zero. The interpolation will not be clipped. + */ + func interpolateTo(_ to: Double, amount: CGFloat) -> Double { + return self + ((to - self) * Double(amount)) + } + + func interpolateTo(_ to: Double, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Double { + return interpolateTo(to, amount: amount) + } + + func remap(fromLow: Double, fromHigh: Double, toLow: Double, toHigh: Double) -> Double { + return toLow + (self - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + } + + /** + Returns a value that is clamped between the two numbers + + 1. The order of arguments does not matter. + */ + func clamp(_ a: Double, _ b: Double) -> Double { + let minValue = a <= b ? a : b + let maxValue = a <= b ? b : a + return max(min(self, maxValue), minValue) + } + +} + +extension CGRect { + + /// Initializes a new CGRect with a center point and size. + init(center: CGPoint, size: CGSize) { + self.init(x: center.x - (size.width * 0.5), + y: center.y - (size.height * 0.5), + width: size.width, + height: size.height) + } + + /// Returns the total area of the rect. + var area: CGFloat { + return width * height + } + + + /// The center point of the rect. Settable. + var center: CGPoint { + get { + return CGPoint(x: midX, y: midY) + } + set { + origin = CGPoint(x: newValue.x - (size.width * 0.5), + y: newValue.y - (size.height * 0.5)) + } + } + + /// The top left point of the rect. Settable. + var topLeft: CGPoint { + get { + return CGPoint(x: minX, y: minY) + } + set { + origin = CGPoint(x: newValue.x, + y: newValue.y) + } + } + + /// The bottom left point of the rect. Settable. + var bottomLeft: CGPoint { + get { + return CGPoint(x: minX, y: maxY) + } + set { + origin = CGPoint(x: newValue.x, + y: newValue.y - size.height) + } + } + + /// The top right point of the rect. Settable. + var topRight: CGPoint { + get { + return CGPoint(x: maxX, y: minY) + } + set { + origin = CGPoint(x: newValue.x - size.width, + y: newValue.y) + } + } + + /// The bottom right point of the rect. Settable. + var bottomRight: CGPoint { + get { + return CGPoint(x: maxX, y: maxY) + } + set { + origin = CGPoint(x: newValue.x - size.width, + y: newValue.y - size.height) + } + } + + /** + Interpolates the receiver to the given rect by Amount. + - Parameter to: The rect to interpolate to. + - Parameter amount: The amount to interpolate from 0-1 + + ``` + let rect = CGRect(x:0, y:0, width: 50, height: 50) + let interpolated = rect.interpolateTo(CGRect(x:100, y:100, width: 100, height: 100), amount: 0.5) + print(interpolated) + // Result: (x: 50, y: 50, width: 75, height: 75) + ``` + + 1. The amount can be greater than one and less than zero. The interpolation will not be clipped. + */ + func interpolateTo(_ to: CGRect, amount: CGFloat) -> CGRect { + return CGRect(x: origin.x.interpolateTo(to.origin.x, amount: amount), + y: origin.y.interpolateTo(to.origin.y, amount: amount), + width: width.interpolateTo(to.width, amount: amount), + height: height.interpolateTo(to.height, amount: amount)) + } + +} + +extension CGSize { + + /** + Interpolates the receiver to the given size by Amount. + - Parameter to: The size to interpolate to. + - Parameter amount: The amount to interpolate from 0-1 + + ``` + let size = CGSize(width: 50, height: 50) + let interpolated = rect.interpolateTo(CGSize(width: 100, height: 100), amount: 0.5) + print(interpolated) + // Result: (width: 75, height: 75) + ``` + + 1. The amount can be greater than one and less than zero. The interpolation will not be clipped. + */ + func interpolateTo(_ to: CGSize, amount: CGFloat) -> CGSize { + return CGSize(width: width.interpolateTo(to.width, amount: amount), + height: height.interpolateTo(to.height, amount: amount)) + } + + /// Returns the scale float that will fit the receive inside of the given size. + func scaleThatFits(_ size: CGSize) -> CGFloat { + return CGFloat.minimum(width / size.width, height / size.height) + } + + /// Adds receiver size to give size. + func add(_ size: CGSize) -> CGSize { + return CGSize(width: width + size.width, height: height + size.height) + } + + /// Subtracts given size from receiver size. + func subtract(_ size: CGSize) -> CGSize { + return CGSize(width: width - size.width, height: height - size.height) + } + + /// Multiplies receiver size by the given size. + func multiply(_ size: CGSize) -> CGSize { + return CGSize(width: width * size.width, height: height * size.height) + } + + /// Operator convenience to add sizes with + + static func +(left: CGSize, right: CGSize) -> CGSize { + return left.add(right) + } + + /// Operator convenience to subtract sizes with - + static func -(left: CGSize, right: CGSize) -> CGSize { + return left.subtract(right) + } + + /// Operator convenience to multiply sizes with * + static func *(left: CGSize, right: CGFloat) -> CGSize { + return CGSize(width: left.width * right, height: left.height * right) + } + +} + +/// A struct that defines a line segment with two CGPoints +struct CGLine { + + /// The Start of the line segment. + var start: CGPoint + /// The End of the line segment. + var end: CGPoint + + /// Initializes a line segment with start and end points + init(start: CGPoint, end: CGPoint) { + self.start = start + self.end = end + } + + /// The length of the line segment. + var length: CGFloat { + return end.distanceTo(start) + } + + /// Returns a line segment that is normalized to a length of 1 + func normalize() -> CGLine { + let len = length + guard len > 0 else { + return self + } + let relativeEnd = end - start + let relativeVector = CGPoint(x: relativeEnd.x / len, y: relativeEnd.y / len) + let absoluteVector = relativeVector + start + return CGLine(start: start, end: absoluteVector) + } + + /// Trims a line segment to the given length + func trimmedToLength(_ toLength: CGFloat) -> CGLine { + let len = length + guard len > 0 else { + return self + } + let relativeEnd = end - start + let relativeVector = CGPoint(x: relativeEnd.x / len, y: relativeEnd.y / len) + let sizedVector = CGPoint(x: relativeVector.x * toLength, y: relativeVector.y * toLength) + let absoluteVector = sizedVector + start + return CGLine(start: start, end: absoluteVector) + } + + /// Flips a line vertically and horizontally from the start point. + func flipped() -> CGLine { + let relativeEnd = end - start + let flippedEnd = CGPoint(x: relativeEnd.x * -1, y: relativeEnd.y * -1) + return CGLine(start: start, end: flippedEnd + start) + } + + /// Move the line to the new start point. + func transpose(_ toPoint: CGPoint) -> CGLine { + let diff = toPoint - start + let newEnd = end + diff + return CGLine(start: toPoint, end: newEnd) + } + +} + +infix operator +| +infix operator +- + +extension CGPoint: Interpolatable { + + /// Returns the distance between the receiver and the given point. + func distanceTo(_ a: CGPoint) -> CGFloat { + let xDist = a.x - x + let yDist = a.y - y + return CGFloat(sqrt((xDist * xDist) + (yDist * yDist))) + } + + /// Returns the length between the receiver and *CGPoint.zero* + var vectorLength: CGFloat { + return distanceTo(.zero) + } + + func rounded(decimal: CGFloat) -> CGPoint { + return CGPoint(x: (round(decimal * x) / decimal), y: (round(decimal * y) / decimal)) + } + + /** + Interpolates the receiver to the given Point by Amount. + - Parameter to: The Point to interpolate to. + - Parameter amount: The amount to interpolate from 0-1 + + ``` + let point = CGPoint(width: 50, height: 50) + let interpolated = rect.interpolateTo(CGPoint(width: 100, height: 100), amount: 0.5) + print(interpolated) + // Result: (x: 75, y: 75) + ``` + + 1. The amount can be greater than one and less than zero. The interpolation will not be clipped. + */ + + func interpolate(_ to: CGPoint, amount: CGFloat) -> CGPoint { + return CGPoint(x: x.interpolateTo(to.x, amount: amount), + y: y.interpolateTo(to.y, amount: amount)) + } + + func interpolate(_ to: CGPoint, outTangent: CGPoint, inTangent: CGPoint, amount: CGFloat, maxIterations: Int = 3, samples: Int = 20, accuracy: CGFloat = 1) -> CGPoint { + if amount == 0 { + return self + } + if amount == 1 { + return to + } + + if self.colinear(outTangent, inTangent) == true, + outTangent.colinear(inTangent, to) == true { + return interpolate(to, amount: amount) + } + + let step = 1 / CGFloat(samples) + + var points: [(point: CGPoint, distance: CGFloat)] = [(point: self, distance: 0)] + var totalLength: CGFloat = 0 + + var previousPoint = self + var previousAmount = CGFloat(0) + + var closestPoint: Int = 0 + + while previousAmount < 1 { + + previousAmount = previousAmount + step + + if previousAmount < amount { + closestPoint = closestPoint + 1 + } + + let newPoint = self.pointOnPath(to, outTangent: outTangent, inTangent: inTangent, amount: previousAmount) + let distance = previousPoint.distanceTo(newPoint) + totalLength = totalLength + distance + points.append((point: newPoint, distance: totalLength)) + previousPoint = newPoint + } + + let accurateDistance = amount * totalLength + var point = points[closestPoint] + + var foundPoint: Bool = false + + var pointAmount: CGFloat = CGFloat(closestPoint) * step + var nextPointAmount: CGFloat = pointAmount + step + + var refineIterations = 0 + while foundPoint == false { + refineIterations = refineIterations + 1 + /// First see if the next point is still less than the projected length. + let nextPoint = points[closestPoint + 1] + if nextPoint.distance < accurateDistance { + point = nextPoint + closestPoint = closestPoint + 1 + pointAmount = CGFloat(closestPoint) * step + nextPointAmount = pointAmount + step + if closestPoint == points.count { + foundPoint = true + } + continue + } + if accurateDistance < point.distance { + closestPoint = closestPoint - 1 + if closestPoint < 0 { + foundPoint = true + continue + } + point = points[closestPoint] + pointAmount = CGFloat(closestPoint) * step + nextPointAmount = pointAmount + step + continue + } + + /// Now we are certain the point is the closest point under the distance + let pointDiff = nextPoint.distance - point.distance + let proposedPointAmount = ((accurateDistance - point.distance) / pointDiff).remap(fromLow: 0, fromHigh: 1, toLow: pointAmount, toHigh: nextPointAmount) + + let newPoint = self.pointOnPath(to, outTangent: outTangent, inTangent: inTangent, amount: proposedPointAmount) + let newDistance = point.distance + point.point.distanceTo(newPoint) + pointAmount = proposedPointAmount + point = (point: newPoint, distance: newDistance) + if accurateDistance - newDistance <= accuracy || + newDistance - accurateDistance <= accuracy { + foundPoint = true + } + + if refineIterations == maxIterations { + foundPoint = true + } + } + return point.point + } + + func pointOnPath(_ to: CGPoint, outTangent: CGPoint, inTangent: CGPoint, amount: CGFloat) -> CGPoint { + let a = self.interpolate(outTangent, amount: amount) + let b = outTangent.interpolate(inTangent, amount: amount) + let c = inTangent.interpolate(to, amount: amount) + let d = a.interpolate(b, amount: amount) + let e = b.interpolate(c, amount: amount) + let f = d.interpolate(e, amount: amount) + return f + } + + func colinear(_ a: CGPoint, _ b: CGPoint) -> Bool { + let area = x * (a.y - b.y) + a.x * (b.y - y) + b.x * (y - a.y); + let accuracy: CGFloat = 0.05 + if area < accuracy && area > -accuracy { + return true + } + return false + } + + func interpolateTo(_ to: CGPoint, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> CGPoint { + guard let outTan = spatialOutTangent, + let inTan = spatialInTangent else { + return interpolate(to, amount: amount) + } + let cp1 = self + outTan + let cp2 = to + inTan + + return interpolate(to, outTangent: cp1, inTangent: cp2, amount: amount) + } + + /// Subtracts the given point from the receiving point. + func subtract(_ point: CGPoint) -> CGPoint { + return CGPoint(x: x - point.x, + y: y - point.y) + } + + /// Adds the given point from the receiving point. + func add(_ point: CGPoint) -> CGPoint { + return CGPoint(x: x + point.x, + y: y + point.y) + } + + var isZero: Bool { + return (x == 0 && y == 0) + } + + /// Operator convenience to divide points with / + static func / (lhs: CGPoint, rhs: CGFloat) -> CGPoint { + return CGPoint(x: lhs.x / CGFloat(rhs), y: lhs.y / CGFloat(rhs)) + } + + /// Operator convenience to multiply points with * + static func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint { + return CGPoint(x: lhs.x * CGFloat(rhs), y: lhs.y * CGFloat(rhs)) + } + + /// Operator convenience to add points with + + static func +(left: CGPoint, right: CGPoint) -> CGPoint { + return left.add(right) + } + + /// Operator convenience to subtract points with - + static func -(left: CGPoint, right: CGPoint) -> CGPoint { + return left.subtract(right) + } + + static func +|(left: CGPoint, right: CGFloat) -> CGPoint { + return CGPoint(x: left.x, y: left.y + right) + } + + static func +-(left: CGPoint, right: CGFloat) -> CGPoint { + return CGPoint(x: left.x + right, y: left.y) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/StringExtensions.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/StringExtensions.swift new file mode 100644 index 0000000..7ff0122 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/StringExtensions.swift @@ -0,0 +1,32 @@ +// +// StringExtensions.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import CoreGraphics + +extension String { + + func hexColorComponents() -> (red: CGFloat, green: CGFloat, blue: CGFloat) { + + var cString:String = trimmingCharacters(in: .whitespacesAndNewlines).uppercased() + + if (cString.hasPrefix("#")) { + cString.remove(at: cString.startIndex) + } + + if ((cString.count) != 6) { + return (red: 0, green: 0, blue: 0) + } + + var rgbValue:UInt32 = 0 + Scanner(string: cString).scanHexInt32(&rgbValue) + + return (red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, + green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, + blue: CGFloat(rgbValue & 0x0000FF) / 255.0) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Helpers/AnimationContext.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Helpers/AnimationContext.swift new file mode 100644 index 0000000..41ab6ab --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Helpers/AnimationContext.swift @@ -0,0 +1,65 @@ +// +// AnimationContext.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/1/19. +// + +import Foundation +import CoreGraphics +import QuartzCore + +/// A completion block for animations. `true` is passed in if the animation completed playing. +public typealias LottieCompletionBlock = (Bool) -> Void + +struct AnimationContext { + + init(playFrom: CGFloat, + playTo: CGFloat, + closure: LottieCompletionBlock?) { + self.playTo = playTo + self.playFrom = playFrom + self.closure = AnimationCompletionDelegate(completionBlock: closure) + } + + var playFrom: CGFloat + var playTo: CGFloat + var closure: AnimationCompletionDelegate + +} + +enum AnimationContextState { + case playing + case cancelled + case complete +} + +class AnimationCompletionDelegate: NSObject, CAAnimationDelegate { + + init(completionBlock: LottieCompletionBlock?) { + self.completionBlock = completionBlock + super.init() + } + + var animationLayer: AnimationContainer? + var animationKey: String? + var ignoreDelegate: Bool = false + var animationState: AnimationContextState = .playing + + let completionBlock: LottieCompletionBlock? + + public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { + guard ignoreDelegate == false else { return } + animationState = flag ? .complete : .cancelled + if let animationLayer = animationLayer, let key = animationKey { + animationLayer.removeAnimation(forKey: key) + if flag { + animationLayer.currentFrame = (anim as! CABasicAnimation).toValue as! CGFloat + } + } + if let completionBlock = completionBlock { + completionBlock(flag) + } + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Interpolatable/Interpolatable.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Interpolatable/Interpolatable.swift new file mode 100644 index 0000000..061e03c --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Interpolatable/Interpolatable.swift @@ -0,0 +1,18 @@ +// +// Interpolatable.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/14/19. +// + +import Foundation +import CoreGraphics + +protocol Interpolatable { + + func interpolateTo(_ to: Self, + amount: CGFloat, + spatialOutTangent: CGPoint?, + spatialInTangent: CGPoint?) -> Self + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Interpolatable/InterpolatableExtensions.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Interpolatable/InterpolatableExtensions.swift new file mode 100644 index 0000000..fd5d6e5 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Interpolatable/InterpolatableExtensions.swift @@ -0,0 +1,170 @@ +// +// InterpolatableExtensions.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/14/19. +// + +import Foundation +import CoreGraphics + +extension Vector1D: Interpolatable { + func interpolateTo(_ to: Vector1D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Vector1D { + return value.interpolateTo(to.value, amount: amount).vectorValue + } +} + +extension Vector2D: Interpolatable { + func interpolateTo(_ to: Vector2D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Vector2D { + return pointValue.interpolateTo(to.pointValue, amount: CGFloat(amount), spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent).vector2dValue + } + +} + +extension Vector3D: Interpolatable { + func interpolateTo(_ to: Vector3D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Vector3D { + if spatialInTangent != nil || spatialOutTangent != nil { + // TODO Support third dimension spatial interpolation + let point = pointValue.interpolateTo(to.pointValue, amount: amount, spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent) + return Vector3D(x: point.x, + y: point.y, + z: CGFloat(z.interpolateTo(to.z, amount: amount))) + } + return Vector3D(x: x.interpolateTo(to.x, amount: amount), + y: y.interpolateTo(to.y, amount: amount), + z: z.interpolateTo(to.z, amount: amount)) + } +} + +extension Color: Interpolatable { + + /// Initialize a new color with Hue Saturation and Value + init(h: Double, s: Double, v: Double, a: Double) { + + let i = floor(h * 6) + let f = h * 6 - i + let p = v * (1 - s); + let q = v * (1 - f * s) + let t = v * (1 - (1 - f) * s) + + switch (i.truncatingRemainder(dividingBy: 6)) { + case 0: + self.r = v + self.g = t + self.b = p + case 1: + self.r = q + self.g = v + self.b = p + case 2: + self.r = p + self.g = v + self.b = t + case 3: + self.r = p + self.g = q + self.b = v + case 4: + self.r = t + self.g = p + self.b = v + case 5: + self.r = v + self.g = p + self.b = q + default: + self.r = 0 + self.g = 0 + self.b = 0 + } + self.a = a + } + + /// Hue Saturation Value of the color. + var hsva: (h: Double, s: Double, v: Double, a: Double) { + let maxValue = max(r, g, b) + let minValue = min(r, g, b) + + var h: Double, s: Double, v: Double = maxValue + + let d = maxValue - minValue + s = maxValue == 0 ? 0 : d / maxValue; + + if (maxValue == minValue) { + h = 0; // achromatic + } else { + switch (maxValue) { + case r: h = (g - b) / d + (g < b ? 6 : 0) + case g: h = (b - r) / d + 2 + case b: h = (r - g) / d + 4 + default: h = maxValue + } + h = h / 6 + } + return (h: h, s: s, v: v, a: a) + } + + init(y: Double, u: Double, v: Double, a: Double) { + // From https://www.fourcc.org/fccyvrgb.php + self.r = y + 1.403 * v + self.g = y - 0.344 * u + self.b = y + 1.770 * u + self.a = a + } + + var yuv: (y: Double, u: Double, v: Double, a: Double) { + /// From https://www.fourcc.org/fccyvrgb.php + let y = 0.299 * r + 0.587 * g + 0.114 * b + let u = -0.14713 * r - 0.28886 * g + 0.436 * b + let v = 0.615 * r - 0.51499 * g - 0.10001 * b + return (y: y, u: u, v: v, a: a) + } + + func interpolateTo(_ to: Color, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Color { + return Color(r: r.interpolateTo(to.r, amount: amount), + g: g.interpolateTo(to.g, amount: amount), + b: b.interpolateTo(to.b, amount: amount), + a: a.interpolateTo(to.a, amount: amount)) + } +} + +extension CurveVertex: Interpolatable { + func interpolateTo(_ to: CurveVertex, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> CurveVertex { + return CurveVertex(point: point.interpolate(to.point, amount: amount), + inTangent: inTangent.interpolate(to.inTangent, amount: amount), + outTangent: outTangent.interpolate(to.outTangent, amount: amount)) + } +} + +extension BezierPath: Interpolatable { + func interpolateTo(_ to: BezierPath, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> BezierPath { + var newPath = BezierPath() + for i in 0.. TextDocument { + if amount == 1 { + return to + } + return self + } +} + +extension Array: Interpolatable where Element == Double { + func interpolateTo(_ to: Array, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Array { + var returnArray = [Double]() + for i in 0.. CGFloat { + let startTime = time + let endTime = to.time + if keyTime <= startTime { + return 0 + } + if endTime <= keyTime { + return 1 + } + + if isHold { + return 0 + } + + let outTanPoint = outTangent?.pointValue ?? .zero + let inTanPoint = to.inTangent?.pointValue ?? CGPoint(x: 1, y: 1) + var progress: CGFloat = keyTime.remap(fromLow: startTime, fromHigh: endTime, toLow: 0, toHigh: 1) + if !outTanPoint.isZero || !inTanPoint.equalTo(CGPoint(x: 1, y: 1)) { + /// Cubic interpolation + progress = progress.cubicBezierInterpolate(.zero, outTanPoint, inTanPoint, CGPoint(x: 1, y: 1)) + } + return progress + } + + /// Interpolates the keyframes' by a progress from 0-1 + func interpolate(_ to: Keyframe, progress: CGFloat) -> T { + return value.interpolateTo(to.value, amount: progress, spatialOutTangent: spatialOutTangent?.pointValue, spatialInTangent: to.spatialInTangent?.pointValue) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/BezierPath.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/BezierPath.swift new file mode 100644 index 0000000..a2babfc --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/BezierPath.swift @@ -0,0 +1,401 @@ +// +// Shape.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/8/19. +// + +import Foundation +import CoreGraphics + +/// A container that holds instructions for creating a single, unbroken Bezier Path. +struct BezierPath { + + /// The elements of the path + fileprivate(set) var elements: [PathElement] + + /// If the path is closed or not. + fileprivate(set) var closed: Bool + + /// The total length of the path. + fileprivate(set) var length: CGFloat + + /// Initializes a new Bezier Path. + init(startPoint: CurveVertex) { + self.elements = [PathElement(vertex: startPoint)] + self.length = 0 + self.closed = false + } + + init() { + self.elements = [] + self.length = 0 + self.closed = false + } + + mutating func moveToStartPoint(_ vertex: CurveVertex) { + self.elements = [PathElement(vertex: vertex)] + self.length = 0 + } + + mutating func addVertex(_ vertex: CurveVertex) { + guard let previous = elements.last else { + addElement(PathElement(vertex: vertex)) + return + } + addElement(previous.pathElementTo(vertex)) + } + + mutating func addCurve(toPoint: CGPoint, outTangent: CGPoint, inTangent: CGPoint) { + guard let previous = elements.last else { return } + let newVertex = CurveVertex(inTangent, toPoint, toPoint) + updateVertex(CurveVertex(previous.vertex.inTangent, previous.vertex.point, outTangent), atIndex: elements.endIndex - 1, remeasure: false) + addVertex(newVertex) + } + + mutating func addLine(toPoint: CGPoint) { + guard let previous = elements.last else { return } + let newVertex = CurveVertex(point: toPoint, inTangentRelative: .zero, outTangentRelative: .zero) + updateVertex(CurveVertex(previous.vertex.inTangent, previous.vertex.point, previous.vertex.point), atIndex: elements.endIndex - 1, remeasure: false) + addVertex(newVertex) + } + + mutating func close() { + self.closed = true + } + + mutating func addElement(_ pathElement: PathElement) { + elements.append(pathElement) + length = length + pathElement.length + } + + mutating func updateVertex(_ vertex: CurveVertex, atIndex: Int, remeasure: Bool) { + if remeasure { + var newElement: PathElement + if atIndex > 0 { + let previousElement = elements[atIndex-1] + newElement = previousElement.pathElementTo(vertex) + } else { + newElement = PathElement(vertex: vertex) + } + elements[atIndex] = newElement + + if atIndex + 1 < elements.count{ + let nextElement = elements[atIndex + 1] + elements[atIndex + 1] = newElement.pathElementTo(nextElement.vertex) + } + + } else { + let oldElement = elements[atIndex] + elements[atIndex] = oldElement.updateVertex(newVertex: vertex) + } + } + + /** + Trims a path fromLength toLength with an offset. + + Length and offset are defined in the length coordinate space. + If any argument is outside the range of this path, then it will be looped over the path from finish to start. + + Cutting the curve when fromLength is less than toLength + x x x x + ~~~~~~~~~~~~~~~ooooooooooooooooooooooooooooooooooooooooooooooooo------------------- + |Offset |fromLength toLength| | + + Cutting the curve when from Length is greater than toLength + x x x x x + oooooooooooooooooo--------------------~~~~~~~~~~~~~~~~ooooooooooooooooooooooooooooo + | toLength| |Offset |fromLength | + + */ + func trim(fromLength: CGFloat, toLength: CGFloat, offsetLength: CGFloat) -> [BezierPath] { + guard elements.count > 1 else { + return [] + } + + if fromLength == toLength { + return [] + } + + /// Normalize lengths to the curve length. + var start = (fromLength+offsetLength).truncatingRemainder(dividingBy: length) + var end = (toLength+offsetLength).truncatingRemainder(dividingBy: length) + + if start < 0 { + start = length + start + } + + if end < 0 { + end = length + end + } + + if start == length { + start = 0 + } + if end == 0 { + end = length + } + + if start == 0 && end == length || + start == end || + start == length && end == 0 { + /// The trim encompasses the entire path. Return. + return [self] + } + + if start > end { + // Start is greater than end. Two paths are returned. + return trimPathAtLengths(positions: [(start: 0, end: end), (start: start, end: length)]) + } + + return trimPathAtLengths(positions: [(start: start, end: end)]) + } + + // MARK: File Private + + /// Trims a path by a list of positions and returns the sub paths + fileprivate func trimPathAtLengths(positions: [(start: CGFloat, end: CGFloat)]) -> [BezierPath] { + guard positions.count > 0 else { + return [] + } + var remainingPositions = positions + + var trim = remainingPositions.remove(at: 0) + + var paths = [BezierPath]() + + var runningLength: CGFloat = 0 + var finishedTrimming: Bool = false + var pathElements = elements + + var currentPath = BezierPath() + var i: Int = 0 + + while !finishedTrimming { + if pathElements.count <= i { + /// Do this for rounding errors + paths.append(currentPath) + finishedTrimming = true + continue + } + /// Loop through and add elements within start->end range. + /// Get current element + let element = pathElements[i] + + /// Calculate new running length. + let newLength = runningLength + element.length + + if newLength < trim.start { + /// Element is not included in the trim, continue. + runningLength = newLength + i = i + 1 + /// Increment index, we are done with this element. + continue + } + + if newLength == trim.start { + /// Current element IS the start element. + /// For start we want to add a zero length element. + currentPath.moveToStartPoint(element.vertex) + runningLength = newLength + i = i + 1 + /// Increment index, we are done with this element. + continue + } + + if runningLength < trim.start, trim.start < newLength, currentPath.elements.count == 0 { + /// The start of the trim is between this element and the previous, trim. + /// Get previous element. + let previousElement = pathElements[i-1] + /// Trim it + let trimLength = trim.start - runningLength + let trimResults = element.splitElementAtPosition(fromElement: previousElement, atLength: trimLength) + /// Add the right span start. + currentPath.moveToStartPoint(trimResults.rightSpan.start.vertex) + + pathElements[i] = trimResults.rightSpan.end + pathElements[i-1] = trimResults.rightSpan.start + runningLength = runningLength + trimResults.leftSpan.end.length + /// Dont increment index or the current length, the end of this path can be within this span. + continue + } + + if trim.start < newLength, newLength < trim.end { + /// Element lies within the trim span. + currentPath.addElement(element) + runningLength = newLength + i = i + 1 + continue + } + + if newLength == trim.end { + /// Element is the end element. + /// The element could have a new length if it's added right after the start node. + currentPath.addElement(element) + /// We are done with this span. + runningLength = newLength + i = i + 1 + /// Allow the path to be finalized. + /// Fall through to finalize path and move to next position + } + + if runningLength < trim.end, trim.end < newLength { + /// New element must be cut for end. + /// Get previous element. + let previousElement = pathElements[i-1] + /// Trim it + let trimLength = trim.end - runningLength + let trimResults = element.splitElementAtPosition(fromElement: previousElement, atLength: trimLength) + /// Add the left span end. + + currentPath.updateVertex(trimResults.leftSpan.start.vertex, atIndex: currentPath.elements.count - 1, remeasure: false) + currentPath.addElement(trimResults.leftSpan.end) + + pathElements[i] = trimResults.rightSpan.end + pathElements[i-1] = trimResults.rightSpan.start + runningLength = runningLength + trimResults.leftSpan.end.length + /// Dont increment index or the current length, the start of the next path can be within this span. + /// We are done with this span. + /// Allow the path to be finalized. + /// Fall through to finalize path and move to next position + } + + paths.append(currentPath) + currentPath = BezierPath() + if remainingPositions.count > 0 { + trim = remainingPositions.remove(at: 0) + } else { + finishedTrimming = true + } + } + return paths + } + +} + +extension BezierPath: Codable { + + /** + The BezierPath container is encoded and decoded from the JSON format + that defines points for a lottie animation. + + { + "c" = Bool + "i" = [[Double]], + "o" = [[Double]], + "v" = [[Double]] + } + + */ + + enum CodingKeys : String, CodingKey { + case closed = "c" + case inPoints = "i" + case outPoints = "o" + case vertices = "v" + } + + init(from decoder: Decoder) throws { + let container: KeyedDecodingContainer + + if let keyedContainer = try? decoder.container(keyedBy: BezierPath.CodingKeys.self) { + container = keyedContainer + } else { + var unkeyedContainer = try decoder.unkeyedContainer() + container = try unkeyedContainer.nestedContainer(keyedBy: BezierPath.CodingKeys.self) + } + + self.closed = try container.decodeIfPresent(Bool.self, forKey: .closed) ?? true + + var vertexContainer = try container.nestedUnkeyedContainer(forKey: .vertices) + var inPointsContainer = try container.nestedUnkeyedContainer(forKey: .inPoints) + var outPointsContainer = try container.nestedUnkeyedContainer(forKey: .outPoints) + + guard vertexContainer.count == inPointsContainer.count, inPointsContainer.count == outPointsContainer.count else { + /// Will throw an error if vertex, inpoints, and outpoints are not the same length. + /// This error is to be expected. + throw DecodingError.dataCorruptedError(forKey: CodingKeys.vertices, + in: container, + debugDescription: "Vertex data does not match In Tangents and Out Tangents") + } + + guard let count = vertexContainer.count, count > 0 else { + self.length = 0 + self.elements = [] + return + } + + var decodedElements = [PathElement]() + + /// Create first point + let firstVertex = CurveVertex(point: try vertexContainer.decode(CGPoint.self), + inTangentRelative: try inPointsContainer.decode(CGPoint.self), + outTangentRelative: try outPointsContainer.decode(CGPoint.self)) + var previousElement = PathElement(vertex: firstVertex) + decodedElements.append(previousElement) + + var totalLength: CGFloat = 0 + while !vertexContainer.isAtEnd { + /// Get the next vertex data. + let vertex = CurveVertex(point: try vertexContainer.decode(CGPoint.self), + inTangentRelative: try inPointsContainer.decode(CGPoint.self), + outTangentRelative: try outPointsContainer.decode(CGPoint.self)) + let pathElement = previousElement.pathElementTo(vertex) + decodedElements.append(pathElement) + previousElement = pathElement + totalLength = totalLength + pathElement.length + } + if closed { + let closeElement = previousElement.pathElementTo(firstVertex) + decodedElements.append(closeElement) + totalLength = totalLength + closeElement.length + } + self.length = totalLength + self.elements = decodedElements + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: BezierPath.CodingKeys.self) + try container.encode(closed, forKey: .closed) + + var vertexContainer = container.nestedUnkeyedContainer(forKey: .vertices) + var inPointsContainer = container.nestedUnkeyedContainer(forKey: .inPoints) + var outPointsContainer = container.nestedUnkeyedContainer(forKey: .outPoints) + + /// If closed path, ignore the final element. + let finalIndex = closed ? self.elements.endIndex - 1 : self.elements.endIndex + for i in 0.. CGPath { + let cgPath = CGMutablePath() + + var previousElement: PathElement? + for element in elements { + if let previous = previousElement { + if previous.vertex.outTangentRelative.isZero && element.vertex.inTangentRelative.isZero { + cgPath.addLine(to: element.vertex.point) + } else { + cgPath.addCurve(to: element.vertex.point, control1: previous.vertex.outTangent, control2: element.vertex.inTangent) + } + } else { + cgPath.move(to: element.vertex.point) + } + previousElement = element + } + if self.closed { + cgPath.closeSubpath() + } + return cgPath + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/ColorExtension.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/ColorExtension.swift new file mode 100644 index 0000000..309031a --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/ColorExtension.swift @@ -0,0 +1,76 @@ +// +// Color.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/14/19. +// + +import Foundation +import CoreGraphics + +extension Color: Codable { + + public init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + + var r1: Double + if !container.isAtEnd { + r1 = try container.decode(Double.self) + } else { + r1 = 0 + } + + var g1: Double + if !container.isAtEnd { + g1 = try container.decode(Double.self) + } else { + g1 = 0 + } + + var b1: Double + if !container.isAtEnd { + b1 = try container.decode(Double.self) + } else { + b1 = 0 + } + + var a1: Double + if !container.isAtEnd { + a1 = try container.decode(Double.self) + } else { + a1 = 1 + } + if r1 > 1, g1 > 1, b1 > 1, a1 > 1 { + r1 = r1 / 255 + g1 = g1 / 255 + b1 = b1 / 255 + a1 = a1 / 255 + } + self.r = r1 + self.g = g1 + self.b = b1 + self.a = a1 + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(r) + try container.encode(g) + try container.encode(b) + try container.encode(a) + } + +} + +extension Color { + + static var clearColor: CGColor { + return CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0, 0, 0, 0])! + } + + var cgColorValue: CGColor { + // TODO: Fix color spaces + let colorspace = CGColorSpaceCreateDeviceRGB() + return CGColor(colorSpace: colorspace, components: [CGFloat(r), CGFloat(g), CGFloat(b), CGFloat(a)]) ?? Color.clearColor + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/CompoundBezierPath.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/CompoundBezierPath.swift new file mode 100644 index 0000000..068a13d --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/CompoundBezierPath.swift @@ -0,0 +1,158 @@ +// +// CompoundBezierPath.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/14/19. +// + +import Foundation +import CoreGraphics + +/** + A collection of BezierPath objects that can be trimmed and added. + + */ +struct CompoundBezierPath { + + let paths: [BezierPath] + + let length: CGFloat + + init() { + paths = [] + length = 0 + } + + init(path: BezierPath) { + self.paths = [path] + self.length = path.length + } + + init(paths: [BezierPath], length: CGFloat) { + self.paths = paths + self.length = length + } + + init(paths: [BezierPath]) { + self.paths = paths + var l: CGFloat = 0 + for path in paths { + l = l + path.length + } + self.length = l + } + + func addPath(path: BezierPath) -> CompoundBezierPath { + var newPaths = paths + newPaths.append(path) + return CompoundBezierPath(paths: newPaths, length: length + path.length) + } + + func combine(_ compoundBezier: CompoundBezierPath) -> CompoundBezierPath { + var newPaths = paths + newPaths.append(contentsOf: compoundBezier.paths) + return CompoundBezierPath(paths: newPaths, length: length + compoundBezier.length) + } + + func trim(fromPosition: CGFloat, toPosition: CGFloat, offset: CGFloat, trimSimultaneously: Bool) -> CompoundBezierPath { + if fromPosition == toPosition { + return CompoundBezierPath() + } + + if trimSimultaneously { + /// Trim each path individually. + var newPaths = [BezierPath]() + for path in paths { + newPaths.append(contentsOf: path.trim(fromLength: fromPosition * path.length, + toLength: toPosition * path.length, + offsetLength: offset * path.length)) + } + return CompoundBezierPath(paths: newPaths) + } + + /// Normalize lengths to the curve length. + var startPosition = (fromPosition+offset).truncatingRemainder(dividingBy: 1) + var endPosition = (toPosition+offset).truncatingRemainder(dividingBy: 1) + + if startPosition < 0 { + startPosition = 1 + startPosition + } + + if endPosition < 0 { + endPosition = 1 + endPosition + } + + if startPosition == 1 { + startPosition = 0 + } + if endPosition == 0 { + endPosition = 1 + } + + if startPosition == 0 && endPosition == 1 || + startPosition == endPosition || + startPosition == 1 && endPosition == 0 { + /// The trim encompasses the entire path. Return. + return self + } + + var positions: [(start: CGFloat, end: CGFloat)] + if endPosition < startPosition { + positions = [(start: 0, end: endPosition * length), + (start: startPosition * length, end: length)] + } else { + positions = [(start: startPosition * length, end: endPosition * length)] + } + + var compoundPath = CompoundBezierPath() + var trim = positions.remove(at: 0) + var pathStartPosition: CGFloat = 0 + + var finishedTrimming: Bool = false + var i: Int = 0 + + while !finishedTrimming { + if paths.count <= i { + /// Rounding errors + finishedTrimming = true + continue + } + let path = paths[i] + + let pathEndPosition = pathStartPosition + path.length + + if pathEndPosition < trim.start { + /// Path is not included in the trim, continue. + pathStartPosition = pathEndPosition + i = i + 1 + continue + + } else if trim.start <= pathStartPosition, pathEndPosition <= trim.end { + /// Full Path is inside of trim. Add full path. + compoundPath = compoundPath.addPath(path: path) + } else { + if let trimPath = path.trim(fromLength: trim.start > pathStartPosition ? (trim.start - pathStartPosition) : 0, + toLength: trim.end < pathEndPosition ? (trim.end - pathStartPosition) : path.length, + offsetLength: 0).first { + compoundPath = compoundPath.addPath(path: trimPath) + } + } + + + if trim.end <= pathEndPosition { + /// We are done with the current trim. + /// Advance trim but remain on the same path in case the next trim overlaps it. + if positions.count > 0 { + trim = positions.remove(at: 0) + } else { + finishedTrimming = true + } + } else { + pathStartPosition = pathEndPosition + i = i + 1 + } + } + return compoundPath + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/CurveVertex.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/CurveVertex.swift new file mode 100644 index 0000000..d4b5eb1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/CurveVertex.swift @@ -0,0 +1,177 @@ +// +// CurveVertex.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/11/19. +// + +import Foundation +import CoreGraphics + +/// A single vertex with an in and out tangent +struct CurveVertex { + + let point: CGPoint + + let inTangent: CGPoint + let outTangent: CGPoint + + /// Initializes a curve point with absolute values + init(_ inTangent: CGPoint, _ point: CGPoint, _ outTangent: CGPoint) { + self.point = point + self.inTangent = inTangent + self.outTangent = outTangent + } + + /// Initializes a curve point with relative values + init(point: CGPoint, inTangentRelative: CGPoint, outTangentRelative: CGPoint) { + self.point = point + self.inTangent = point.add(inTangentRelative) + self.outTangent = point.add(outTangentRelative) + } + + /// Initializes a curve point with absolute values + init(point: CGPoint, inTangent: CGPoint, outTangent: CGPoint) { + self.point = point + self.inTangent = inTangent + self.outTangent = outTangent + } + + var inTangentRelative: CGPoint { + return inTangent.subtract(point) + } + + var outTangentRelative: CGPoint { + return outTangent.subtract(point) + } + + func reversed() -> CurveVertex { + return CurveVertex(point: point, inTangent: outTangent, outTangent: inTangent) + } + + func translated(_ translation: CGPoint) -> CurveVertex { + return CurveVertex(point: point + translation, inTangent: inTangent + translation, outTangent: outTangent + translation) + } + + /** + Trims a path defined by two Vertices at a specific position, from 0 to 1 + + The path can be visualized below. + + F is fromVertex. + V is the vertex of the receiver. + P is the position from 0-1. + O is the outTangent of fromVertex. + F====O=========P=======I====V + + After trimming the curve can be visualized below. + + S is the returned Start vertex. + E is the returned End vertex. + T is the trim point. + TI and TO are the new tangents for the trimPoint + NO and NI are the new tangents for the startPoint and endPoints + S==NO=========TI==T==TO=======NI==E + */ + func splitCurve(toVertex: CurveVertex, position: CGFloat) -> + (start: CurveVertex, trimPoint: CurveVertex, end: CurveVertex) { + + /// If position is less than or equal to 0, trim at start. + if position <= 0 { + return (start: CurveVertex(point: point, inTangentRelative: inTangentRelative, outTangentRelative: .zero), + trimPoint: CurveVertex(point: point, inTangentRelative: .zero, outTangentRelative: outTangentRelative), + end: toVertex) + } + + /// If position is greater than or equal to 1, trim at end. + if position >= 1 { + return (start: self, + trimPoint: CurveVertex(point: toVertex.point, inTangentRelative: toVertex.inTangentRelative, outTangentRelative: .zero), + end: CurveVertex(point: toVertex.point, inTangentRelative: .zero, outTangentRelative: toVertex.outTangentRelative)) + } + + if outTangentRelative.isZero && toVertex.inTangentRelative.isZero { + /// If both tangents are zero, then span to be trimmed is a straight line. + let trimPoint = point.interpolate(toVertex.point, amount: position) + return (start: self, + trimPoint: CurveVertex(point: trimPoint, inTangentRelative: .zero, outTangentRelative: .zero), + end: toVertex) + } + /// Cutting by amount gives incorrect length.... + /// One option is to cut by a stride until it gets close then edge it down. + /// Measuring a percentage of the spans does not equal the same as measuring a percentage of length. + /// This is where the historical trim path bugs come from. + let a = point.interpolate(outTangent, amount: position) + let b = outTangent.interpolate(toVertex.inTangent, amount: position) + let c = toVertex.inTangent.interpolate(toVertex.point, amount: position) + let d = a.interpolate(b, amount: position) + let e = b.interpolate(c, amount: position) + let f = d.interpolate(e, amount: position) + return (start: CurveVertex(point: point, inTangent: inTangent, outTangent: a), + trimPoint: CurveVertex(point: f, inTangent: d, outTangent: e), + end: CurveVertex(point: toVertex.point, inTangent: c, outTangent: toVertex.outTangent)) + } + + /** + Trims a curve of a known length to a specific length and returns the points. + + There is not a performant yet accurate way to cut a curve to a specific length. + This calls splitCurve(toVertex: position:) to split the curve and then measures + the length of the new curve. The function then iterates through the samples, + adjusting the position of the cut for a more precise cut. + Usually a single iteration is enough to get within 0.5 points of the desired + length. + + This function should probably live in PathElement, since it deals with curve + lengths. + */ + func trimCurve(toVertex: CurveVertex, atLength: CGFloat, curveLength: CGFloat, maxSamples: Int, accuracy: CGFloat = 1) -> + (start: CurveVertex, trimPoint: CurveVertex, end: CurveVertex) { + var currentPosition = atLength / curveLength + var results = splitCurve(toVertex: toVertex, position: currentPosition) + + if maxSamples == 0 { + return results + } + + for _ in 1...maxSamples { + let length = results.start.distanceTo(results.trimPoint) + let lengthDiff = atLength - length + /// Check if length is correct. + if lengthDiff < accuracy { + return results + } + let diffPosition = max(min(((currentPosition / length) * lengthDiff), currentPosition * 0.5), currentPosition * -0.5) + currentPosition = diffPosition + currentPosition + results = splitCurve(toVertex: toVertex, position: currentPosition) + } + return results + } + + + /** + The distance from the receiver to the provided vertex. + + For lines (zeroed tangents) the distance between the two points is measured. + For curves the curve is iterated over by sample count and the points are measured. + This is ~99% accurate at a sample count of 30 + */ + func distanceTo(_ toVertex: CurveVertex, sampleCount: Int = 25) -> CGFloat { + + if outTangentRelative.isZero && toVertex.inTangentRelative.isZero { + /// Return a linear distance. + return point.distanceTo(toVertex.point) + } + + var distance: CGFloat = 0 + + var previousPoint = point + for i in 0.. PathElement { + return PathElement(length: vertex.distanceTo(toVertex), vertex: toVertex) + } + + /// Initializes a new path with length of 0 + init(vertex: CurveVertex) { + self.length = 0 + self.vertex = vertex + } + + /// Initializes a new path with length + fileprivate init(length: CGFloat, vertex: CurveVertex) { + self.length = length + self.vertex = vertex + } + + func updateVertex(newVertex: CurveVertex) -> PathElement { + return PathElement(length: length, vertex: newVertex) + } + + /// Splits an element span defined by the receiver and fromElement to a position 0-1 + func splitElementAtPosition(fromElement: PathElement, atLength: CGFloat) -> + (leftSpan: (start: PathElement, end: PathElement), rightSpan: (start: PathElement, end: PathElement)) { + /// Trim the span. Start and trim go into the first, trim and end go into second. + let trimResults = fromElement.vertex.trimCurve(toVertex: vertex, atLength: atLength, curveLength: length, maxSamples: 3) + + /// Create the elements for the break + let spanAStart = PathElement(length: fromElement.length, + vertex: CurveVertex(point: fromElement.vertex.point, + inTangent: fromElement.vertex.inTangent, + outTangent: trimResults.start.outTangent)) + /// Recalculating the length here is a waste as the trimCurve function also accurately calculates this length. + let spanAEnd = spanAStart.pathElementTo(trimResults.trimPoint) + + let spanBStart = PathElement(vertex: trimResults.trimPoint) + let spanBEnd = spanBStart.pathElementTo(trimResults.end) + return (leftSpan: (start: spanAStart, end: spanAEnd), + rightSpan: (start: spanBStart, end: spanBEnd)) + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/VectorsExtensions.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/VectorsExtensions.swift new file mode 100644 index 0000000..b8c0a39 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/VectorsExtensions.swift @@ -0,0 +1,218 @@ +// +// Vector.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/7/19. +// + +import Foundation +import CoreGraphics +import QuartzCore + +/** + Single value container. Needed because lottie sometimes wraps a Double in an array. + */ +extension Vector1D: Codable { + + public init(from decoder: Decoder) throws { + /// Try to decode an array of doubles + do { + var container = try decoder.unkeyedContainer() + self.value = try container.decode(Double.self) + } catch { + self.value = try decoder.singleValueContainer().decode(Double.self) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(value) + } + + var cgFloatValue: CGFloat { + return CGFloat(value) + } + +} + +extension Double { + var vectorValue: Vector1D { + return Vector1D(self) + } +} + +/** + Needed for decoding json {x: y:} to a CGPoint + */ +struct Vector2D: Codable { + + var x: Double + var y: Double + + init(x: Double, y: Double) { + self.x = x + self.y = y + } + + private enum CodingKeys : String, CodingKey { + case x = "x" + case y = "y" + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Vector2D.CodingKeys.self) + + do { + let xValue: [Double] = try container.decode([Double].self, forKey: .x) + self.x = xValue[0] + } catch { + self.x = try container.decode(Double.self, forKey: .x) + } + + do { + let yValue: [Double] = try container.decode([Double].self, forKey: .y) + self.y = yValue[0] + } catch { + self.y = try container.decode(Double.self, forKey: .y) + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: Vector2D.CodingKeys.self) + try container.encode(x, forKey: .x) + try container.encode(y, forKey: .y) + } + + var pointValue: CGPoint { + return CGPoint(x: x, y: y) + } +} + +extension Vector2D { + +} + +extension CGPoint { + var vector2dValue: Vector2D { + return Vector2D(x: Double(x), y: Double(y)) + } +} + +/** + A three dimensional vector. + These vectors are encoded and decoded from [Double] + */ + +extension Vector3D: Codable { + + init(x: CGFloat, y: CGFloat, z: CGFloat) { + self.x = Double(x) + self.y = Double(y) + self.z = Double(z) + } + + public init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + + if !container.isAtEnd { + self.x = try container.decode(Double.self) + } else { + self.x = 0 + } + + if !container.isAtEnd { + self.y = try container.decode(Double.self) + } else { + self.y = 0 + } + + if !container.isAtEnd { + self.z = try container.decode(Double.self) + } else { + self.z = 0 + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(x) + try container.encode(y) + try container.encode(z) + } + +} + +public extension Vector3D { + var pointValue: CGPoint { + return CGPoint(x: x, y: y) + } + + var sizeValue: CGSize { + return CGSize(width: x, height: y) + } +} + +extension CGPoint { + var vector3dValue: Vector3D { + return Vector3D(x: x, y: y, z: 0) + } +} + +extension CGSize { + var vector3dValue: Vector3D { + return Vector3D(x: width, y: height, z: 1) + } +} + +extension CATransform3D { + + func rotated(_ degrees: CGFloat) -> CATransform3D { + return CATransform3DRotate(self, degrees.toRadians(), 0, 0, 1) + } + + func translated(_ translation: CGPoint) -> CATransform3D { + return CATransform3DTranslate(self, translation.x, translation.y, 0) + } + + func scaled(_ scale: CGSize) -> CATransform3D { + return CATransform3DScale(self, scale.width, scale.height, 1) + } + + func skewed(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D { + return CATransform3DConcat(CATransform3D.makeSkew(skew: skew, skewAxis: skewAxis), self) + } + + static func makeSkew(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D { + let mCos = cos(skewAxis.toRadians()) + let mSin = sin(skewAxis.toRadians()) + let aTan = tan(skew.toRadians()) + + let transform1 = CATransform3D(m11: mCos, m12: mSin, m13: 0, m14: 0, + m21: -mSin, m22: mCos, m23: 0, m24: 0, + m31: 0, m32: 0, m33: 1, m34: 0, + m41: 0, m42: 0, m43: 0, m44: 1) + + let transform2 = CATransform3D(m11: 1, m12: 0, m13: 0, m14: 0, + m21: aTan, m22: 1, m23: 0, m24: 0, + m31: 0, m32: 0, m33: 1, m34: 0, + m41: 0, m42: 0, m43: 0, m44: 1) + + let transform3 = CATransform3D(m11: mCos, m12: -mSin, m13: 0, m14: 0, + m21: mSin, m22: mCos, m23: 0, m24: 0, + m31: 0, m32: 0, m33: 1, m34: 0, + m41: 0, m42: 0, m43: 0, m44: 1) + return CATransform3DConcat(transform3, CATransform3DConcat(transform2, transform1)) + } + + static func makeTransform(anchor: CGPoint, + position: CGPoint, + scale: CGSize, + rotation: CGFloat, + skew: CGFloat?, + skewAxis: CGFloat?) -> CATransform3D { + if let skew = skew, let skewAxis = skewAxis { + return CATransform3DMakeTranslation(position.x, position.y, 0).rotated(rotation).skewed(skew: -skew, skewAxis: skewAxis).scaled(scale * 0.01).translated(anchor * -1) + } + return CATransform3DMakeTranslation(position.x, position.y, 0).rotated(rotation).scaled(scale * 0.01).translated(anchor * -1) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationPublic.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationPublic.swift new file mode 100644 index 0000000..2f0a3c1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationPublic.swift @@ -0,0 +1,196 @@ +// +// AnimationPublic.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/5/19. +// + +import Foundation +import CoreGraphics + +public extension Animation { + + // MARK: Animation (Loading) + + /** + Loads an animation model from a bundle by its name. Returns `nil` if an animation is not found. + + - Parameter name: The name of the json file without the json extension. EG "StarAnimation" + - Parameter bundle: The bundle in which the animation is located. Defaults to `Bundle.main` + - Parameter subdirectory: A subdirectory in the bundle in which the animation is located. Optional. + - Parameter animationCache: A cache for holding loaded animations. Optional. + + - Returns: Deserialized `Animation`. Optional. + */ + static func named(_ name: String, + bundle: Bundle = Bundle.main, + subdirectory: String? = nil, + animationCache: AnimationCacheProvider? = nil) -> Animation? { + /// Create a cache key for the animation. + let cacheKey = bundle.bundlePath + (subdirectory ?? "") + "/" + name + + /// Check cache for animation + if let animationCache = animationCache, + let animation = animationCache.animation(forKey: cacheKey) { + /// If found, return the animation. + return animation + } + /// Make sure the bundle has a file at the path provided. + guard let url = bundle.url(forResource: name, withExtension: "json", subdirectory: subdirectory) else { + return nil + } + + do { + /// Decode animation. + let json = try Data(contentsOf: url) + let animation = try JSONDecoder().decode(Animation.self, from: json) + animationCache?.setAnimation(animation, forKey: cacheKey) + return animation + } catch { + /// Decoding error. + print(error) + return nil + } + } + + /** + Loads an animation from a specific filepath. + - Parameter filepath: The absolute filepath of the animation to load. EG "/User/Me/starAnimation.json" + - Parameter animationCache: A cache for holding loaded animations. Optional. + + - Returns: Deserialized `Animation`. Optional. + */ + static func filepath(_ filepath: String, + animationCache: AnimationCacheProvider? = nil) -> Animation? { + + /// Check cache for animation + if let animationCache = animationCache, + let animation = animationCache.animation(forKey: filepath) { + return animation + } + + do { + /// Decode the animation. + let json = try Data(contentsOf: URL(fileURLWithPath: filepath)) + let animation = try JSONDecoder().decode(Animation.self, from: json) + animationCache?.setAnimation(animation, forKey: filepath) + return animation + } catch { + /// Decoding Error. + return nil + } + } + + /// A closure for an Animation download. The closure is passed `nil` if there was an error. + typealias DownloadClosure = (Animation?) -> Void + + /** + Loads a Lottie animation asynchronously from the URL. + + - Parameter url: The url to load the animation from. + - Parameter closure: A closure to be called when the animation has loaded. + - Parameter animationCache: A cache for holding loaded animations. + + */ + static func loadedFrom(url: URL, + closure: @escaping Animation.DownloadClosure, + animationCache: AnimationCacheProvider?) { + + if let animationCache = animationCache, let animation = animationCache.animation(forKey: url.absoluteString) { + closure(animation) + } else { + let task = URLSession.shared.dataTask(with: url) { (data, response, error) in + guard error == nil, let jsonData = data else { + DispatchQueue.main.async { + closure(nil) + } + return + } + do { + let animation = try JSONDecoder().decode(Animation.self, from: jsonData) + DispatchQueue.main.async { + animationCache?.setAnimation(animation, forKey: url.absoluteString) + closure(animation) + } + } catch { + DispatchQueue.main.async { + closure(nil) + } + } + + } + task.resume() + } + } + + // MARK: Animation (Helpers) + + /** + Markers are a way to describe a point in time by a key name. + + Markers are encoded into animation JSON. By using markers a designer can mark + playback points for a developer to use without having to worry about keeping + track of animation frames. If the animation file is updated, the developer + does not need to update playback code. + + Returns the Progress Time for the marker named. Returns nil if no marker found. + */ + func progressTime(forMarker named: String) -> AnimationProgressTime? { + guard let markers = markerMap, let marker = markers[named] else { + return nil + } + return progressTime(forFrame: marker.frameTime) + } + + /** + Markers are a way to describe a point in time by a key name. + + Markers are encoded into animation JSON. By using markers a designer can mark + playback points for a developer to use without having to worry about keeping + track of animation frames. If the animation file is updated, the developer + does not need to update playback code. + + Returns the Frame Time for the marker named. Returns nil if no marker found. + */ + func frameTime(forMarker named: String) -> AnimationFrameTime? { + guard let markers = markerMap, let marker = markers[named] else { + return nil + } + return marker.frameTime + } + + /// Converts Frame Time (Seconds * Framerate) into Progress Time (0 to 1). + func progressTime(forFrame frameTime: AnimationFrameTime) -> AnimationProgressTime { + return ((frameTime - startFrame) / (endFrame - startFrame)).clamp(0, 1) + } + + /// Converts Progress Time (0 to 1) into Frame Time (Seconds * Framerate) + func frameTime(forProgress progressTime: AnimationProgressTime) -> AnimationFrameTime { + return ((endFrame - startFrame) * progressTime) + startFrame + } + + /// Converts Frame Time (Seconds * Framerate) into Time (Seconds) + func time(forFrame frameTime: AnimationFrameTime) -> TimeInterval { + return Double(frameTime - startFrame) / framerate + } + + /// Converts Time (Seconds) into Frame Time (Seconds * Framerate) + func frameTime(forTime time: TimeInterval) -> AnimationFrameTime { + return CGFloat(time * framerate) + startFrame + } + + /// The duration in seconds of the animation. + var duration: TimeInterval { + return Double(endFrame - startFrame) / framerate + } + + /// The natural bounds in points of the animation. + var bounds: CGRect { + return CGRect(x: 0, y: 0, width: width, height: height) + } + + /// The natural size in points of the animation. + var size: CGSize { + return CGSize(width: width, height: height) + } +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationView.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationView.swift new file mode 100644 index 0000000..7f76e5c --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationView.swift @@ -0,0 +1,1006 @@ +// +// LottieView.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/23/19. +// + +import Foundation +import QuartzCore + +/// Describes the behavior of an AnimationView when the app is moved to the background. +public enum LottieBackgroundBehavior { + /// Stop the animation and reset it to the beginning of its current play time. The completion block is called. + case stop + /// Pause the animation in its current state. The completion block is called. + case pause + /// Pause the animation and restart it when the application moves to the foreground. The completion block is stored and called when the animation completes. + case pauseAndRestore + /// Stops the animation and sets it to the end of its current play time. The completion block is called. + case forceFinish +} + +/// Defines animation loop behavior +public enum LottieLoopMode { + /// Animation is played once then stops. + case playOnce + /// Animation will loop from beginning to end until stopped. + case loop + /// Animation will play forward, then backwards and loop until stopped. + case autoReverse + /// Animation will loop from beginning to end up to defined amount of times. + case `repeat`(Float) + /// Animation will play forward, then backwards a defined amount of times. + case repeatBackwards(Float) +} + +extension LottieLoopMode: Equatable { + public static func == (lhs: LottieLoopMode, rhs: LottieLoopMode) -> Bool { + switch (lhs, rhs) { + case (.repeat(let lhsAmount), .repeat(let rhsAmount)), + (.repeatBackwards(let lhsAmount), .repeatBackwards(let rhsAmount)): + return lhsAmount == rhsAmount + case (.playOnce, .playOnce), + (.loop, .loop), + (.autoReverse, .autoReverse): + return true + default: + return false + } + } +} + +@IBDesignable +final public class AnimationView: LottieView { + + // MARK: - Public Properties + + /** + Sets the animation backing the animation view. Setting this will clear the + view's contents, completion blocks and current state. The new animation will + be loaded up and set to the beginning of its timeline. + */ + public var animation: Animation? { + didSet { + makeAnimationLayer() + } + } + + /// Set animation name from Interface Builder + @IBInspectable var animationName: String? { + didSet { + self.animation = animationName.flatMap { + Animation.named($0, animationCache: nil) + } + } + } + + /** + Describes the behavior of an AnimationView when the app is moved to the background. + + The default is `pause` which pauses the animation when the application moves to + the background. The completion block is called with `false` for completed. + */ + public var backgroundBehavior: LottieBackgroundBehavior = .pause + + /** + Sets the image provider for the animation view. An image provider provides the + animation with its required image data. + + Setting this will cause the animation to reload its image contents. + */ + public var imageProvider: AnimationImageProvider { + didSet { + animationLayer?.imageProvider = imageProvider + reloadImages() + } + } + + /** + Sets the text provider for animation view. A text provider provides the + animation with values for text layers + */ + public var textProvider: AnimationTextProvider { + didSet { + animationLayer?.textProvider = textProvider + } + } + + /** + Sets the text provider for animation view. A text provider provides the + animation with values for text layers + */ + public var fontProvider: AnimationFontProvider { + didSet { + animationLayer?.fontProvider = fontProvider + } + } + + /// Returns `true` if the animation is currently playing. + public var isAnimationPlaying: Bool { + return animationLayer?.animation(forKey: activeAnimationName) != nil + } + + /// Returns `true` if the animation will start playing when this view is added to a window. + public var isAnimationQueued: Bool { + return animationContext != nil && waitingToPlayAnimation + } + + /// Sets the loop behavior for `play` calls. Defaults to `playOnce` + public var loopMode: LottieLoopMode = .playOnce { + didSet { + updateInFlightAnimation() + } + } + + /** + When `true` the animation view will rasterize its contents when not animating. + Rasterizing will improve performance of static animations. + + Note: this will not produce crisp results at resolutions above the animations natural resolution. + + Defaults to `false` + */ + public var shouldRasterizeWhenIdle: Bool = false { + didSet { + updateRasterizationState() + } + } + + /** + Sets the current animation time with a Progress Time + + Note: Setting this will stop the current animation, if any. + Note 2: If `animation` is nil, setting this will fallback to 0 + */ + public var currentProgress: AnimationProgressTime { + set { + if let animation = animation { + currentFrame = animation.frameTime(forProgress: newValue) + } else { + currentFrame = 0 + } + } + get { + if let animation = animation { + return animation.progressTime(forFrame: currentFrame) + } else { + return 0 + } + } + } + + /** + Sets the current animation time with a time in seconds. + + Note: Setting this will stop the current animation, if any. + Note 2: If `animation` is nil, setting this will fallback to 0 + */ + public var currentTime: TimeInterval { + set { + if let animation = animation { + currentFrame = animation.frameTime(forTime: newValue) + } else { + currentFrame = 0 + } + } + get { + if let animation = animation { + return animation.time(forFrame: currentFrame) + } else { + return 0 + } + } + } + + /** + Sets the current animation time with a frame in the animations framerate. + + Note: Setting this will stop the current animation, if any. + */ + public var currentFrame: AnimationFrameTime { + set { + removeCurrentAnimation() + updateAnimationFrame(newValue) + } + get { + return animationLayer?.currentFrame ?? 0 + } + } + + /// Returns the current animation frame while an animation is playing. + public var realtimeAnimationFrame: AnimationFrameTime { + return isAnimationPlaying ? animationLayer?.presentation()?.currentFrame ?? currentFrame : currentFrame + } + + /// Returns the current animation frame while an animation is playing. + public var realtimeAnimationProgress: AnimationProgressTime { + if let animation = animation { + return animation.progressTime(forFrame: realtimeAnimationFrame) + } + return 0 + } + + /// Sets the speed of the animation playback. Defaults to 1 + public var animationSpeed: CGFloat = 1 { + didSet { + updateInFlightAnimation() + } + } + + /** + When `true` the animation will play back at the framerate encoded in the + `Animation` model. When `false` the animation will play at the framerate + of the device. + + Defaults to false + */ + public var respectAnimationFrameRate: Bool = false { + didSet { + animationLayer?.respectAnimationFrameRate = respectAnimationFrameRate + } + } + + /** + Controls the cropping of an Animation. Setting this property will crop the animation + to the current views bounds by the viewport frame. The coordinate space is specified + in the animation's coordinate space. + + Animatable. + */ + public var viewportFrame: CGRect? = nil { + didSet { + + /* + This is really ugly, but is needed to trigger a layout pass within an animation block. + Typically this happens automatically, when layout objects are UIView based. + The animation layer is a CALayer which will not implicitly grab the animation + duration of a UIView animation block. + + By setting bounds and then resetting bounds the UIView animation block's + duration and curve are captured and added to the layer. This is used in the + layout block to animate the animationLayer's position and size. + */ + let rect = bounds + self.bounds = CGRect.zero + self.bounds = rect + self.setNeedsLayout() + } + } + + // MARK: - Public Functions + + /** + Plays the animation from its current state to the end. + + - Parameter completion: An optional completion closure to be called when the animation completes playing. + */ + public func play(completion: LottieCompletionBlock? = nil) { + guard let animation = animation else { + return + } + + /// Build a context for the animation. + let context = AnimationContext(playFrom: CGFloat(animation.startFrame), + playTo: CGFloat(animation.endFrame), + closure: completion) + removeCurrentAnimation() + addNewAnimationForContext(context) + } + + /** + Plays the animation from a progress (0-1) to a progress (0-1). + + - Parameter fromProgress: The start progress of the animation. If `nil` the animation will start at the current progress. + - Parameter toProgress: The end progress of the animation. + - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used. + - Parameter completion: An optional completion closure to be called when the animation stops. + */ + public func play(fromProgress: AnimationProgressTime? = nil, + toProgress: AnimationProgressTime, + loopMode: LottieLoopMode? = nil, + completion: LottieCompletionBlock? = nil) { + guard let animation = animation else { + return + } + + removeCurrentAnimation() + if let loopMode = loopMode { + /// Set the loop mode, if one was supplied + self.loopMode = loopMode + } + let context = AnimationContext(playFrom: animation.frameTime(forProgress: fromProgress ?? currentProgress), + playTo: animation.frameTime(forProgress: toProgress), + closure: completion) + addNewAnimationForContext(context) + } + + /** + Plays the animation from a start frame to an end frame in the animation's framerate. + + - Parameter fromFrame: The start frame of the animation. If `nil` the animation will start at the current frame. + - Parameter toFrame: The end frame of the animation. + - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used. + - Parameter completion: An optional completion closure to be called when the animation stops. + */ + public func play(fromFrame: AnimationFrameTime? = nil, + toFrame: AnimationFrameTime, + loopMode: LottieLoopMode? = nil, + completion: LottieCompletionBlock? = nil) { + removeCurrentAnimation() + if let loopMode = loopMode { + /// Set the loop mode, if one was supplied + self.loopMode = loopMode + } + + let context = AnimationContext(playFrom: fromFrame ?? currentProgress, + playTo: toFrame, + closure: completion) + addNewAnimationForContext(context) + } + + /** + Plays the animation from a named marker to another marker. + + Markers are point in time that are encoded into the Animation data and assigned + a name. + + NOTE: If markers are not found the play command will exit. + + - Parameter fromMarker: The start marker for the animation playback. If `nil` the + animation will start at the current progress. + - Parameter toMarker: The end marker for the animation playback. + - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used. + - Parameter completion: An optional completion closure to be called when the animation stops. + */ + public func play(fromMarker: String? = nil, + toMarker: String, + loopMode: LottieLoopMode? = nil, + completion: LottieCompletionBlock? = nil) { + + guard let animation = animation, let markers = animation.markerMap, let to = markers[toMarker] else { + return + } + + removeCurrentAnimation() + if let loopMode = loopMode { + /// Set the loop mode, if one was supplied + self.loopMode = loopMode + } + + let fromTime: CGFloat + if let fromName = fromMarker, let from = markers[fromName] { + fromTime = CGFloat(from.frameTime) + } else { + fromTime = currentFrame + } + + let context = AnimationContext(playFrom: fromTime, + playTo: CGFloat(to.frameTime), + closure: completion) + addNewAnimationForContext(context) + } + + /** + Stops the animation and resets the view to its start frame. + + The completion closure will be called with `false` + */ + public func stop() { + removeCurrentAnimation() + currentFrame = 0 + } + + /** + Pauses the animation in its current state. + + The completion closure will be called with `false` + */ + public func pause() { + removeCurrentAnimation() + } + + /// Reloads the images supplied to the animation from the `imageProvider` + public func reloadImages() { + animationLayer?.reloadImages() + } + + /// Forces the AnimationView to redraw its contents. + public func forceDisplayUpdate() { + animationLayer?.forceDisplayUpdate() + } + + // MARK: - Public (Dynamic Properties) + + /** + + Sets a ValueProvider for the specified keypath. The value provider will be set + on all properties that match the keypath. + + Nearly all properties of a Lottie animation can be changed at runtime using a + combination of `Animation Keypaths` and `Value Providers`. + Setting a ValueProvider on a keypath will cause the animation to update its + contents and read the new Value Provider. + + A value provider provides a typed value on a frame by frame basis. + + - Parameter valueProvider: The new value provider for the properties. + - Parameter keypath: The keypath used to search for properties. + + Example: + ``` + /// A keypath that finds the color value for all `Fill 1` nodes. + let fillKeypath = AnimationKeypath(keypath: "**.Fill 1.Color") + /// A Color Value provider that returns a reddish color. + let redValueProvider = ColorValueProvider(Color(r: 1, g: 0.2, b: 0.3, a: 1)) + /// Set the provider on the animationView. + animationView.setValueProvider(redValueProvider, keypath: fillKeypath) + ``` + */ + public func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) { + animationLayer?.setValueProvider(valueProvider, keypath: keypath) + } + /** + Reads the value of a property specified by the Keypath. + Returns nil if no property is found. + + - Parameter for: The keypath used to search for the property. + - Parameter atFrame: The Frame Time of the value to query. If nil then the current frame is used. + */ + public func getValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? { + return animationLayer?.getValue(for: keypath, atFrame: atFrame) + } + + /// Logs all child keypaths. + public func logHierarchyKeypaths() { + animationLayer?.logHierarchyKeypaths() + } + + // MARK: - Public (Add Subview) + + /** + Searches for the nearest child layer to the first Keypath and adds the subview + to that layer. The subview will move and animate with the child layer. + Furthermore the subview will be in the child layers coordinate space. + + Note: if no layer is found for the keypath, then nothing happens. + + - Parameter subview: The subview to add to the found animation layer. + - Parameter keypath: The keypath used to find the animation layer. + + Example: + ``` + /// A keypath that finds `Layer 1` + let layerKeypath = AnimationKeypath(keypath: "Layer 1") + + /// Wrap the custom view in an `AnimationSubview` + let subview = AnimationSubview() + subview.addSubview(customView) + + /// Set the provider on the animationView. + animationView.addSubview(subview, forLayerAt: layerKeypath) + ``` + */ + public func addSubview(_ subview: AnimationSubview, forLayerAt keypath: AnimationKeypath) { + guard let sublayer = animationLayer?.layer(for: keypath) else { + return + } + self.setNeedsLayout() + self.layoutIfNeeded() + self.forceDisplayUpdate() + addSubview(subview) + if let subViewLayer = subview.viewLayer { + sublayer.addSublayer(subViewLayer) + } + } + + /** + Converts a CGRect from the AnimationView's coordinate space into the + coordinate space of the layer found at Keypath. + + If no layer is found, nil is returned + + - Parameter rect: The CGRect to convert. + - Parameter toLayerAt: The keypath used to find the layer. + */ + public func convert(_ rect: CGRect, toLayerAt keypath: AnimationKeypath?) -> CGRect? { + guard let animationLayer = animationLayer else { return nil } + guard let keypath = keypath else { + return viewLayer?.convert(rect, to: animationLayer) + } + guard let sublayer = animationLayer.layer(for: keypath) else { + return nil + } + self.setNeedsLayout() + self.layoutIfNeeded() + self.forceDisplayUpdate() + return animationLayer.convert(rect, to: sublayer) + } + + /** + Converts a CGPoint from the AnimationView's coordinate space into the + coordinate space of the layer found at Keypath. + + If no layer is found, nil is returned + + - Parameter point: The CGPoint to convert. + - Parameter toLayerAt: The keypath used to find the layer. + */ + public func convert(_ point: CGPoint, toLayerAt keypath: AnimationKeypath?) -> CGPoint? { + guard let animationLayer = animationLayer else { return nil } + guard let keypath = keypath else { + return viewLayer?.convert(point, to: animationLayer) + } + guard let sublayer = animationLayer.layer(for: keypath) else { + return nil + } + self.setNeedsLayout() + self.layoutIfNeeded() + self.forceDisplayUpdate() + return animationLayer.convert(point, to: sublayer) + } + + // MARK: - Public (Animation Contents) + + /** + Sets the enabled state of all animator nodes found with the keypath search. + This can be used to interactively enable / disable parts of the animation. + + - Parameter isEnabled: When true the animator nodes affect the rendering tree. When false the node is removed from the tree. + - Parameter keypath: The keypath used to find the node(s). + */ + public func setNodeIsEnabled(isEnabled: Bool, keypath: AnimationKeypath) { + guard let animationLayer = animationLayer else { return } + let nodes = animationLayer.animatorNodes(for: keypath) + if let nodes = nodes { + for node in nodes { + node.isEnabled = isEnabled + } + self.forceDisplayUpdate() + } + } + + // MARK: - Public (Markers) + + /** + Markers are a way to describe a point in time by a key name. + + Markers are encoded into animation JSON. By using markers a designer can mark + playback points for a developer to use without having to worry about keeping + track of animation frames. If the animation file is updated, the developer + does not need to update playback code. + + Returns the Progress Time for the marker named. Returns nil if no marker found. + */ + public func progressTime(forMarker named: String) -> AnimationProgressTime? { + guard let animation = animation else { + return nil + } + return animation.progressTime(forMarker: named) + } + + /** + Markers are a way to describe a point in time by a key name. + + Markers are encoded into animation JSON. By using markers a designer can mark + playback points for a developer to use without having to worry about keeping + track of animation frames. If the animation file is updated, the developer + does not need to update playback code. + + Returns the Frame Time for the marker named. Returns nil if no marker found. + */ + public func frameTime(forMarker named: String) -> AnimationFrameTime? { + guard let animation = animation else { + return nil + } + return animation.frameTime(forMarker: named) + } + + // MARK: - Public (Initializers) + + /// Initializes a LottieView with an animation. + public init( + animation: Animation?, + imageProvider: AnimationImageProvider? = nil, + textProvider: AnimationTextProvider = DefaultTextProvider(), + fontProvider: AnimationFontProvider = DefaultFontProvider()) { + self.animation = animation + self.imageProvider = imageProvider ?? BundleImageProvider(bundle: Bundle.main, searchPath: nil) + self.textProvider = textProvider + self.fontProvider = fontProvider + super.init(frame: .zero) + commonInit() + makeAnimationLayer() + if let animation = animation { + frame = animation.bounds + } + } + + public init() { + self.animation = nil + self.imageProvider = BundleImageProvider(bundle: Bundle.main, searchPath: nil) + self.textProvider = DefaultTextProvider() + self.fontProvider = DefaultFontProvider() + super.init(frame: .zero) + commonInit() + } + + public override init(frame: CGRect) { + self.animation = nil + self.imageProvider = BundleImageProvider(bundle: Bundle.main, searchPath: nil) + self.textProvider = DefaultTextProvider() + self.fontProvider = DefaultFontProvider() + super.init(frame: .zero) + commonInit() + } + + required public init?(coder aDecoder: NSCoder) { + self.imageProvider = BundleImageProvider(bundle: Bundle.main, searchPath: nil) + self.textProvider = DefaultTextProvider() + self.fontProvider = DefaultFontProvider() + super.init(coder: aDecoder) + commonInit() + } + + // MARK: - Public (UIView Overrides) + + override public var intrinsicContentSize: CGSize { + if let animation = animation { + return animation.bounds.size + } + return .zero + } + + override func layoutAnimation() { + guard let animation = animation, let animationLayer = animationLayer else { return } + var position = animation.bounds.center + let xform: CATransform3D + var shouldForceUpdates: Bool = false + + if let viewportFrame = self.viewportFrame { + shouldForceUpdates = self.contentMode == .redraw + + let compAspect = viewportFrame.size.width / viewportFrame.size.height + let viewAspect = bounds.size.width / bounds.size.height + let dominantDimension = compAspect > viewAspect ? bounds.size.width : bounds.size.height + let compDimension = compAspect > viewAspect ? viewportFrame.size.width : viewportFrame.size.height + let scale = dominantDimension / compDimension + + let viewportOffset = animation.bounds.center - viewportFrame.center + xform = CATransform3DTranslate(CATransform3DMakeScale(scale, scale, 1), viewportOffset.x, viewportOffset.y, 0) + position = bounds.center + } else { + switch contentMode { + case .scaleToFill: + position = bounds.center + xform = CATransform3DMakeScale(bounds.size.width / animation.size.width, + bounds.size.height / animation.size.height, + 1); + case .scaleAspectFit: + position = bounds.center + let compAspect = animation.size.width / animation.size.height + let viewAspect = bounds.size.width / bounds.size.height + let dominantDimension = compAspect > viewAspect ? bounds.size.width : bounds.size.height + let compDimension = compAspect > viewAspect ? animation.size.width : animation.size.height + let scale = dominantDimension / compDimension + xform = CATransform3DMakeScale(scale, scale, 1) + case .scaleAspectFill: + position = bounds.center + let compAspect = animation.size.width / animation.size.height + let viewAspect = bounds.size.width / bounds.size.height + let scaleWidth = compAspect < viewAspect + let dominantDimension = scaleWidth ? bounds.size.width : bounds.size.height + let compDimension = scaleWidth ? animation.size.width : animation.size.height + let scale = dominantDimension / compDimension + xform = CATransform3DMakeScale(scale, scale, 1) + case .redraw: + shouldForceUpdates = true + xform = CATransform3DIdentity + case .center: + position = bounds.center + xform = CATransform3DIdentity + case .top: + position.x = bounds.center.x + xform = CATransform3DIdentity + case .bottom: + position.x = bounds.center.x + position.y = bounds.maxY - animation.bounds.midY + xform = CATransform3DIdentity + case .left: + position.y = bounds.center.y + xform = CATransform3DIdentity + case .right: + position.y = bounds.center.y + position.x = bounds.maxX - animation.bounds.midX + xform = CATransform3DIdentity + case .topLeft: + xform = CATransform3DIdentity + case .topRight: + position.x = bounds.maxX - animation.bounds.midX + xform = CATransform3DIdentity + case .bottomLeft: + position.y = bounds.maxY - animation.bounds.midY + xform = CATransform3DIdentity + case .bottomRight: + position.x = bounds.maxX - animation.bounds.midX + position.y = bounds.maxY - animation.bounds.midY + xform = CATransform3DIdentity + + #if os(iOS) || os(tvOS) + @unknown default: + print("unsupported contentMode: \(contentMode.rawValue); please update lottie-ios") + xform = CATransform3DIdentity + #endif + } + } + + /* + UIView Animation does not implicitly set CAAnimation time or timing fuctions. + If layout is changed in an animation we must get the current animation duration + and timing function and then manually create a CAAnimation to match the UIView animation. + If layout is changed without animation, explicitly set animation duration to 0.0 + inside CATransaction to avoid unwanted artifacts. + */ + /// Check if any animation exist on the view's layer, and match it. + if let key = viewLayer?.animationKeys()?.first, let animation = viewLayer?.animation(forKey: key) { + // The layout is happening within an animation block. Grab the animation data. + + let positionKey = "LayoutPositionAnimation" + let transformKey = "LayoutTransformAnimation" + animationLayer.removeAnimation(forKey: positionKey) + animationLayer.removeAnimation(forKey: transformKey) + + let positionAnimation = animation.copy() as? CABasicAnimation ?? CABasicAnimation(keyPath: "position") + positionAnimation.keyPath = "position" + positionAnimation.isAdditive = false + positionAnimation.fromValue = animationLayer.position + positionAnimation.toValue = position + positionAnimation.isRemovedOnCompletion = true + + let xformAnimation = animation.copy() as? CABasicAnimation ?? CABasicAnimation(keyPath: "transform") + xformAnimation.keyPath = "transform" + xformAnimation.isAdditive = false + xformAnimation.fromValue = animationLayer.transform + xformAnimation.toValue = xform + xformAnimation.isRemovedOnCompletion = true + + animationLayer.position = position + animationLayer.transform = xform + #if os(OSX) + animationLayer.anchorPoint = layer?.anchorPoint ?? CGPoint.zero + #else + animationLayer.anchorPoint = layer.anchorPoint + #endif + animationLayer.add(positionAnimation, forKey: positionKey) + animationLayer.add(xformAnimation, forKey: transformKey) + } else { + CATransaction.begin() + CATransaction.setAnimationDuration(0.0) + CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .linear)) + animationLayer.position = position + animationLayer.transform = xform + CATransaction.commit() + } + + if shouldForceUpdates { + animationLayer.forceDisplayUpdate() + } + } + + // MARK: - Private (Properties) + + + var animationLayer: AnimationContainer? = nil + + fileprivate var animationContext: AnimationContext? + static private let animationName: String = "Lottie" + fileprivate var activeAnimationName: String = AnimationView.animationName + fileprivate var animationID: Int = 0 + + // MARK: - Private (Building Animation View) + + fileprivate func makeAnimationLayer() { + + /// Remove current animation if any + removeCurrentAnimation() + + if let oldAnimation = self.animationLayer { + oldAnimation.removeFromSuperlayer() + } + + invalidateIntrinsicContentSize() + + guard let animation = animation else { + return + } + + let animationLayer = AnimationContainer(animation: animation, imageProvider: imageProvider, textProvider: textProvider, fontProvider: fontProvider) + animationLayer.renderScale = self.screenScale + viewLayer?.addSublayer(animationLayer) + self.animationLayer = animationLayer + reloadImages() + animationLayer.setNeedsDisplay() + setNeedsLayout() + currentFrame = CGFloat(animation.startFrame) + } + + func updateRasterizationState() { + if isAnimationPlaying { + animationLayer?.shouldRasterize = false + } else { + animationLayer?.shouldRasterize = shouldRasterizeWhenIdle + } + } + + // MARK: - Private (Animation Playback) + + /// Updates the animation frame. Does not affect any current animations + func updateAnimationFrame(_ newFrame: CGFloat) { + CATransaction.begin() + CATransaction.setCompletionBlock { + self.animationLayer?.forceDisplayUpdate() + } + CATransaction.setDisableActions(true) + animationLayer?.currentFrame = newFrame + CATransaction.commit() + } + + @objc override func animationWillMoveToBackground() { + updateAnimationForBackgroundState() + } + + @objc override func animationWillEnterForeground() { + updateAnimationForForegroundState() + } + + override func animationMovedToWindow() { + /// Don't update any state if the `superview` is `nil` + /// When A viewA owns superViewB, it removes the superViewB from the window. At this point, viewA still owns superViewB and triggers the viewA method: -didmovetowindow + guard superview != nil else { return } + + if window != nil { + updateAnimationForForegroundState() + } else { + updateAnimationForBackgroundState() + } + } + + fileprivate func updateAnimationForBackgroundState() { + if let currentContext = animationContext { + switch backgroundBehavior { + case .stop: + removeCurrentAnimation() + updateAnimationFrame(currentContext.playFrom) + case .pause: + removeCurrentAnimation() + case .pauseAndRestore: + currentContext.closure.ignoreDelegate = true + removeCurrentAnimation() + /// Keep the stale context around for when the app enters the foreground. + self.animationContext = currentContext + case .forceFinish: + removeCurrentAnimation() + updateAnimationFrame(currentContext.playTo) + } + } + } + + fileprivate var waitingToPlayAnimation: Bool = false + fileprivate func updateAnimationForForegroundState() { + if let currentContext = animationContext { + if waitingToPlayAnimation { + waitingToPlayAnimation = false + self.addNewAnimationForContext(currentContext) + } else if backgroundBehavior == .pauseAndRestore { + /// Restore animation from saved state + updateInFlightAnimation() + } + } + } + + /// Stops the current in flight animation and freezes the animation in its current state. + fileprivate func removeCurrentAnimation() { + guard animationContext != nil else { return } + let pauseFrame = realtimeAnimationFrame + animationLayer?.removeAnimation(forKey: activeAnimationName) + updateAnimationFrame(pauseFrame) + self.animationContext = nil + } + + /// Updates an in flight animation. + fileprivate func updateInFlightAnimation() { + guard let animationContext = animationContext else { return } + + guard animationContext.closure.animationState != .complete else { + // Tried to re-add an already completed animation. Cancel. + self.animationContext = nil + return + } + + /// Tell existing context to ignore its closure + animationContext.closure.ignoreDelegate = true + + /// Make a new context, stealing the completion block from the previous. + let newContext = AnimationContext(playFrom: animationContext.playFrom, + playTo: animationContext.playTo, + closure: animationContext.closure.completionBlock) + + /// Remove current animation, and freeze the current frame. + let pauseFrame = realtimeAnimationFrame + animationLayer?.removeAnimation(forKey: activeAnimationName) + animationLayer?.currentFrame = pauseFrame + + addNewAnimationForContext(newContext) + } + + /// Adds animation to animation layer and sets the delegate. If animation layer or animation are nil, exits. + fileprivate func addNewAnimationForContext(_ animationContext: AnimationContext) { + guard let animationlayer = animationLayer, let animation = animation else { + return + } + + self.animationContext = animationContext + + guard self.window != nil else { waitingToPlayAnimation = true; return } + + animationID = animationID + 1 + activeAnimationName = AnimationView.animationName + String(animationID) + + /// At this point there is no animation on animationLayer and its state is set. + + let framerate = animation.framerate + + let playFrom = animationContext.playFrom.clamp(animation.startFrame, animation.endFrame) + let playTo = animationContext.playTo.clamp(animation.startFrame, animation.endFrame) + + let duration = ((max(playFrom, playTo) - min(playFrom, playTo)) / CGFloat(framerate)) + + let playingForward: Bool = + ((animationSpeed > 0 && playFrom < playTo) || + (animationSpeed < 0 && playTo < playFrom)) + + var startFrame = currentFrame.clamp(min(playFrom, playTo), max(playFrom, playTo)) + if startFrame == playTo { + startFrame = playFrom + } + + let timeOffset: TimeInterval = playingForward ? + Double(startFrame - min(playFrom, playTo)) / framerate : + Double(max(playFrom, playTo) - startFrame) / framerate + + let layerAnimation = CABasicAnimation(keyPath: "currentFrame") + layerAnimation.fromValue = playFrom + layerAnimation.toValue = playTo + layerAnimation.speed = Float(animationSpeed) + layerAnimation.duration = TimeInterval(duration) + layerAnimation.fillMode = CAMediaTimingFillMode.both + + switch loopMode { + case .playOnce: + layerAnimation.repeatCount = 1 + case .loop: + layerAnimation.repeatCount = HUGE + case .autoReverse: + layerAnimation.repeatCount = HUGE + layerAnimation.autoreverses = true + case let .repeat(amount): + layerAnimation.repeatCount = amount + case let .repeatBackwards(amount): + layerAnimation.repeatCount = amount + layerAnimation.autoreverses = true + } + + layerAnimation.isRemovedOnCompletion = false + if timeOffset != 0 { + let currentLayerTime = viewLayer?.convertTime(CACurrentMediaTime(), from: nil) ?? 0 + layerAnimation.beginTime = currentLayerTime - (timeOffset * 1 / Double(abs(animationSpeed))) + } + layerAnimation.delegate = animationContext.closure + animationContext.closure.animationLayer = animationlayer + animationContext.closure.animationKey = activeAnimationName + + animationlayer.add(layerAnimation, forKey: activeAnimationName) + updateRasterizationState() + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationViewInitializers.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationViewInitializers.swift new file mode 100644 index 0000000..5277f3f --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Animation/AnimationViewInitializers.swift @@ -0,0 +1,83 @@ +// +// AnimationViewInitializers.swift +// lottie-swift-iOS +// +// Created by Brandon Withrow on 2/6/19. +// + +import Foundation + +public extension AnimationView { + + /** + Loads a Lottie animation from a JSON file in the supplied bundle. + + - Parameter name: The string name of the lottie animation with no file + extension provided. + - Parameter bundle: The bundle in which the animation is located. + Defaults to the Main bundle. + - Parameter imageProvider: An image provider for the animation's image data. + If none is supplied Lottie will search in the supplied bundle for images. + */ + convenience init(name: String, + bundle: Bundle = Bundle.main, + imageProvider: AnimationImageProvider? = nil, + animationCache: AnimationCacheProvider? = LRUAnimationCache.sharedCache) { + let animation = Animation.named(name, bundle: bundle, subdirectory: nil, animationCache: animationCache) + let provider = imageProvider ?? BundleImageProvider(bundle: bundle, searchPath: nil) + self.init(animation: animation, imageProvider: provider) + } + + /** + Loads a Lottie animation from a JSON file in a specific path on disk. + + - Parameter name: The absolute path of the Lottie Animation. + - Parameter imageProvider: An image provider for the animation's image data. + If none is supplied Lottie will search in the supplied filepath for images. + */ + convenience init(filePath: String, + imageProvider: AnimationImageProvider? = nil, + animationCache: AnimationCacheProvider? = LRUAnimationCache.sharedCache) { + let animation = Animation.filepath(filePath, animationCache: animationCache) + let provider = imageProvider ?? FilepathImageProvider(filepath: URL(fileURLWithPath: filePath).deletingLastPathComponent().path) + self.init(animation: animation, imageProvider: provider) + } + + /** + Loads a Lottie animation asynchronously from the URL + + - Parameter url: The url to load the animation from. + - Parameter imageProvider: An image provider for the animation's image data. + If none is supplied Lottie will search in the main bundle for images. + - Parameter closure: A closure to be called when the animation has loaded. + */ + convenience init(url: URL, + imageProvider: AnimationImageProvider? = nil, + closure: @escaping AnimationView.DownloadClosure, + animationCache: AnimationCacheProvider? = LRUAnimationCache.sharedCache) { + + if let animationCache = animationCache, let animation = animationCache.animation(forKey: url.absoluteString) { + self.init(animation: animation, imageProvider: imageProvider) + closure(nil) + } else { + + self.init(animation: nil, imageProvider: imageProvider) + + Animation.loadedFrom(url: url, closure: { (animation) in + if let animation = animation { + self.animation = animation + closure(nil) + } else { + closure(LottieDownloadError.downloadFailed) + } + }, animationCache: animationCache) + } + } + + typealias DownloadClosure = (Error?) -> Void + +} + +enum LottieDownloadError: Error { + case downloadFailed +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/AnimationCacheProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/AnimationCacheProvider.swift new file mode 100644 index 0000000..23c4119 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/AnimationCacheProvider.swift @@ -0,0 +1,24 @@ +// +// AnimationCacheProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/5/19. +// + +import Foundation +/** + `AnimationCacheProvider` is a protocol that describes an Animation Cache. + Animation Cache is used when loading `Animation` models. Using an Animation Cache + can increase performance when loading an animation multiple times. + + Lottie comes with a prebuilt LRU Animation Cache. + */ +public protocol AnimationCacheProvider { + + func animation(forKey: String) -> Animation? + + func setAnimation(_ animation: Animation, forKey: String) + + func clearCache() + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/LRUAnimationCache.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/LRUAnimationCache.swift new file mode 100644 index 0000000..11f729f --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/LRUAnimationCache.swift @@ -0,0 +1,57 @@ +// +// LRUAnimationCache.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/5/19. +// + +import Foundation + +/** + An Animation Cache that will store animations up to `cacheSize`. + + Once `cacheSize` is reached, the least recently used animation will be ejected. + The default size of the cache is 100. + */ +public class LRUAnimationCache: AnimationCacheProvider { + + public init() { } + + /// Clears the Cache. + public func clearCache() { + cacheMap.removeAll() + lruList.removeAll() + } + + /// The global shared Cache. + public static let sharedCache = LRUAnimationCache() + + /// The size of the cache. + public var cacheSize: Int = 100 + + public func animation(forKey: String) -> Animation? { + guard let animation = cacheMap[forKey] else { + return nil + } + if let index = lruList.firstIndex(of: forKey) { + lruList.remove(at: index) + lruList.append(forKey) + } + return animation + } + + public func setAnimation(_ animation: Animation, forKey: String) { + cacheMap[forKey] = animation + lruList.append(forKey) + if lruList.count > cacheSize { + let removed = lruList.remove(at: 0) + if removed != forKey { + cacheMap[removed] = nil + } + } + } + + fileprivate var cacheMap: [String : Animation] = [:] + fileprivate var lruList: [String] = [] + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/AnimationKeypath.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/AnimationKeypath.swift new file mode 100644 index 0000000..e9ece1b --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/AnimationKeypath.swift @@ -0,0 +1,46 @@ +// +// AnimationKeypath.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation + +/** + `AnimationKeypath` is an object that describes a keypath search for nodes in the + animation JSON. `AnimationKeypath` matches views and properties inside of `AnimationView` + to their backing `Animation` model by name. + + A keypath can be used to set properties on an existing animation, or can be validated + with an existing `Animation`. + + `AnimationKeypath` can describe a specific object, or can use wildcards for fuzzy matching + of objects. Acceptable wildcards are either "*" (star) or "**" (double star). + Single star will search a single depth for the next object. + Double star will search any depth. + + Read More at https://airbnb.io/lottie/#/ios?id=dynamic-animation-properties + + EG: + @"Layer.Shape Group.Stroke 1.Color" + Represents a specific color node on a specific stroke. + + @"**.Stroke 1.Color" + Represents the color node for every Stroke named "Stroke 1" in the animation. + */ +public struct AnimationKeypath { + + /// Creates a keypath from a dot separated string. The string is separated by "." + public init(keypath: String) { + self.keys = keypath.components(separatedBy: ".") + } + + /// Creates a keypath from a list of strings. + public init(keys: [String]) { + self.keys = keys + } + + let keys: [String] + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/AnyValueProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/AnyValueProvider.swift new file mode 100644 index 0000000..1684cd9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/AnyValueProvider.swift @@ -0,0 +1,29 @@ +// +// AnyValueProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/30/19. +// + +import Foundation +import CoreGraphics + +/** + `AnyValueProvider` is a protocol that return animation data for a property at a + given time. Every fame an `AnimationView` queries all of its properties and asks + if their ValueProvider has an update. If it does the AnimationView will read the + property and update that portion of the animation. + + Value Providers can be used to dynamically set animation properties at run time. + */ +public protocol AnyValueProvider { + + /// The Type of the value provider + var valueType: Any.Type { get } + + /// Asks the provider if it has an update for the given frame. + func hasUpdate(frame: AnimationFrameTime) -> Bool + + /// Asks the provider to update the container with its value for the frame. + func value(frame: AnimationFrameTime) -> Any +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/ColorValueProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/ColorValueProvider.swift new file mode 100644 index 0000000..4d594d2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/ColorValueProvider.swift @@ -0,0 +1,66 @@ +// +// ColorValueProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +import CoreGraphics + +/// A `ValueProvider` that returns a CGColor Value +public final class ColorValueProvider: AnyValueProvider { + + /// Returns a Color for a CGColor(Frame Time) + public typealias ColorValueBlock = (CGFloat) -> Color + + /// The color value of the provider. + public var color: Color { + didSet { + hasUpdate = true + } + } + + /// Initializes with a block provider + public init(block: @escaping ColorValueBlock) { + self.block = block + self.color = Color(r: 0, g: 0, b: 0, a: 1) + } + + /// Initializes with a single color. + public init(_ color: Color) { + self.color = color + self.block = nil + hasUpdate = true + } + + // MARK: ValueProvider Protocol + + public var valueType: Any.Type { + return Color.self + } + + public func hasUpdate(frame: CGFloat) -> Bool { + if block != nil { + return true + } + return hasUpdate + } + + public func value(frame: CGFloat) -> Any { + hasUpdate = false + let newColor: Color + if let block = block { + newColor = block(frame) + } else { + newColor = color + } + return newColor + } + + // MARK: Private + + private var hasUpdate: Bool = true + + private var block: ColorValueBlock? +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/FloatValueProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/FloatValueProvider.swift new file mode 100644 index 0000000..ecd43e1 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/FloatValueProvider.swift @@ -0,0 +1,66 @@ +// +// DoubleValueProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +import CoreGraphics + +/// A `ValueProvider` that returns a CGFloat Value +public final class FloatValueProvider: AnyValueProvider { + + /// Returns a CGFloat for a CGFloat(Frame Time) + public typealias CGFloatValueBlock = (CGFloat) -> CGFloat + + public var float: CGFloat { + didSet { + hasUpdate = true + } + } + + /// Initializes with a block provider + public init(block: @escaping CGFloatValueBlock) { + self.block = block + self.float = 0 + } + + /// Initializes with a single float. + public init(_ float: CGFloat) { + self.float = float + self.block = nil + hasUpdate = true + } + + // MARK: ValueProvider Protocol + + public var valueType: Any.Type { + return Vector1D.self + } + + public func hasUpdate(frame: CGFloat) -> Bool { + if block != nil { + return true + } + return hasUpdate + } + + public func value(frame: CGFloat) -> Any { + hasUpdate = false + let newCGFloat: CGFloat + if let block = block { + newCGFloat = block(frame) + } else { + newCGFloat = float + } + return Vector1D(Double(newCGFloat)) + } + + // MARK: Private + + private var hasUpdate: Bool = true + + private var block: CGFloatValueBlock? +} + diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/GradientValueProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/GradientValueProvider.swift new file mode 100644 index 0000000..d19bfc4 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/GradientValueProvider.swift @@ -0,0 +1,114 @@ +// +// GradientValueProvider.swift +// lottie-swift +// +// Created by Enrique Bermúdez on 10/27/19. +// + +import Foundation +import CoreGraphics + +/// A `ValueProvider` that returns a Gradient Color Value. +public final class GradientValueProvider: AnyValueProvider { + + /// Returns a [Color] for a CGFloat(Frame Time). + public typealias ColorsValueBlock = (CGFloat) -> [Color] + /// Returns a [Double](Color locations) for a CGFloat(Frame Time). + public typealias ColorLocationsBlock = (CGFloat) -> [Double] + + /// The colors values of the provider. + public var colors: [Color] { + didSet { + updateValueArray() + hasUpdate = true + } + } + + /// The color location values of the provider. + public var locations: [Double] { + didSet { + updateValueArray() + hasUpdate = true + } + } + + /// Initializes with a block provider. + public init(block: @escaping ColorsValueBlock, + locations: ColorLocationsBlock? = nil) { + self.block = block + self.locationsBlock = locations + self.colors = [] + self.locations = [] + } + + /// Initializes with an array of colors. + public init(_ colors: [Color], + locations: [Double] = []) { + self.colors = colors + self.locations = locations + updateValueArray() + hasUpdate = true + } + + // MARK: ValueProvider Protocol + + public var valueType: Any.Type { + return [Double].self + } + + public func hasUpdate(frame: CGFloat) -> Bool { + if block != nil || locationsBlock != nil { + return true + } + return hasUpdate + } + + public func value(frame: CGFloat) -> Any { + hasUpdate = false + + if let block = block { + let newColors = block(frame) + let newLocations = locationsBlock?(frame) ?? [] + value = value(from: newColors, locations: newLocations) + } + + return value + } + + // MARK: Private + + private func value(from colors: [Color], locations: [Double]) -> [Double] { + + var colorValues = [Double]() + var alphaValues = [Double]() + var shouldAddAlphaValues = false + + for i in 0.. i ? locations[i] : + (Double(i) / Double(colors.count - 1)) + + colorValues.append(location) + colorValues.append(colors[i].r) + colorValues.append(colors[i].g) + colorValues.append(colors[i].b) + + alphaValues.append(location) + alphaValues.append(colors[i].a) + } + + return colorValues + (shouldAddAlphaValues ? alphaValues : []) + } + + private func updateValueArray() { + value = value(from: colors, locations: locations) + } + + private var hasUpdate: Bool = true + + private var block: ColorsValueBlock? + private var locationsBlock: ColorLocationsBlock? + private var value: [Double] = [] +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/PointValueProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/PointValueProvider.swift new file mode 100644 index 0000000..83579fb --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/PointValueProvider.swift @@ -0,0 +1,64 @@ +// +// PointValueProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +import CoreGraphics +/// A `ValueProvider` that returns a CGPoint Value +public final class PointValueProvider: AnyValueProvider { + + /// Returns a CGPoint for a CGFloat(Frame Time) + public typealias PointValueBlock = (CGFloat) -> CGPoint + + public var point: CGPoint { + didSet { + hasUpdate = true + } + } + + /// Initializes with a block provider + public init(block: @escaping PointValueBlock) { + self.block = block + self.point = .zero + } + + /// Initializes with a single point. + public init(_ point: CGPoint) { + self.point = point + self.block = nil + hasUpdate = true + } + + // MARK: ValueProvider Protocol + + public var valueType: Any.Type { + return Vector3D.self + } + + public func hasUpdate(frame: CGFloat) -> Bool { + if block != nil { + return true + } + return hasUpdate + } + + public func value(frame: CGFloat) -> Any { + hasUpdate = false + let newPoint: CGPoint + if let block = block { + newPoint = block(frame) + } else { + newPoint = point + } + return newPoint.vector3dValue + } + + // MARK: Private + + private var hasUpdate: Bool = true + + private var block: PointValueBlock? +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/SizeValueProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/SizeValueProvider.swift new file mode 100644 index 0000000..4e89320 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/DynamicProperties/ValueProviders/SizeValueProvider.swift @@ -0,0 +1,65 @@ +// +// SizeValueProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +import CoreGraphics + +/// A `ValueProvider` that returns a CGSize Value +public final class SizeValueProvider: AnyValueProvider { + + /// Returns a CGSize for a CGFloat(Frame Time) + public typealias SizeValueBlock = (CGFloat) -> CGSize + + public var size: CGSize { + didSet { + hasUpdate = true + } + } + + /// Initializes with a block provider + public init(block: @escaping SizeValueBlock) { + self.block = block + self.size = .zero + } + + /// Initializes with a single size. + public init(_ size: CGSize) { + self.size = size + self.block = nil + hasUpdate = true + } + + // MARK: ValueProvider Protocol + + public var valueType: Any.Type { + return Vector3D.self + } + + public func hasUpdate(frame: CGFloat) -> Bool { + if block != nil { + return true + } + return hasUpdate + } + + public func value(frame: CGFloat) -> Any { + hasUpdate = false + let newSize: CGSize + if let block = block { + newSize = block(frame) + } else { + newSize = size + } + return newSize.vector3dValue + } + + // MARK: Private + + private var hasUpdate: Bool = true + + private var block: SizeValueBlock? +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/FontProvider/AnimationFontProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/FontProvider/AnimationFontProvider.swift new file mode 100644 index 0000000..9533ac2 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/FontProvider/AnimationFontProvider.swift @@ -0,0 +1,28 @@ +// +// AnimationFontProvider.swift +// Lottie +// +// Created by Brandon Withrow on 8/5/20. +// Copyright © 2020 YurtvilleProds. All rights reserved. +// + +import Foundation +import CoreGraphics +import CoreText + +/** + Font provider is a protocol that is used to supply fonts to `AnimationView`. + + */ +public protocol AnimationFontProvider { + func fontFor(family: String, size: CGFloat) -> CTFont? +} + +/// Default Font provider. +public final class DefaultFontProvider: AnimationFontProvider { + public func fontFor(family: String, size: CGFloat) -> CTFont? { + return CTFontCreateWithName(family as CFString, size, nil) + } + + public init() {} +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/ImageProvider/AnimationImageProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/ImageProvider/AnimationImageProvider.swift new file mode 100644 index 0000000..78cf5f3 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/ImageProvider/AnimationImageProvider.swift @@ -0,0 +1,23 @@ +// +// LottieImageProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import CoreGraphics + +/** + Image provider is a protocol that is used to supply images to `AnimationView`. + + Some animations require a reference to an image. The image provider loads and + provides those images to the `AnimationView`. Lottie includes a couple of + prebuilt Image Providers that supply images from a Bundle, or from a FilePath. + + Additionally custom Image Providers can be made to load images from a URL, + or to Cache images. + */ +public protocol AnimationImageProvider { + func imageForAsset(asset: ImageAsset) -> CGImage? +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/AnimationTime.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/AnimationTime.swift new file mode 100644 index 0000000..b765c50 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/AnimationTime.swift @@ -0,0 +1,15 @@ +// +// AnimationTime.swift +// lottie-swift-iOS +// +// Created by Brandon Withrow on 2/6/19. +// + +import Foundation +import CoreGraphics + +/// Defines animation time in Frames (Seconds * Framerate). +public typealias AnimationFrameTime = CGFloat + +/// Defines animation time by a progress from 0 (beginning of the animation) to 1 (end of the animation) +public typealias AnimationProgressTime = CGFloat diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/Color.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/Color.swift new file mode 100644 index 0000000..4550f4c --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/Color.swift @@ -0,0 +1,41 @@ +// +// Color.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation + +public enum ColorFormatDenominator { + case One + case OneHundred + case TwoFiftyFive + + var value: Double { + switch self { + case .One: + return 1.0 + case .OneHundred: + return 100.0 + case .TwoFiftyFive: + return 255.0 + } + } +} + +public struct Color { + + public var r: Double + public var g: Double + public var b: Double + public var a: Double + + public init(r: Double, g: Double, b: Double, a: Double, denominator: ColorFormatDenominator = .One) { + self.r = r / denominator.value + self.g = g / denominator.value + self.b = b / denominator.value + self.a = a / denominator.value + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/Vectors.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/Vectors.swift new file mode 100644 index 0000000..bdf9381 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/Primitives/Vectors.swift @@ -0,0 +1,37 @@ +// +// Vectors.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation + +public struct Vector1D { + + public init(_ value: Double) { + self.value = value + } + + public let value: Double + +} + + +/** + A three dimensional vector. + These vectors are encoded and decoded from [Double] + */ +public struct Vector3D { + + public let x: Double + public let y: Double + public let z: Double + + public init(x: Double, y: Double, z: Double) { + self.x = x + self.y = y + self.z = z + } + +} diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/TextProvider/AnimationTextProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/TextProvider/AnimationTextProvider.swift new file mode 100644 index 0000000..3e4e8d9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/TextProvider/AnimationTextProvider.swift @@ -0,0 +1,39 @@ +// +// AnimationImageProvider.swift +// Lottie_iOS +// +// Created by Alexandr Goncharov on 07/06/2019. +// + +import Foundation + +/** + Text provider is a protocol that is used to supply text to `AnimationView`. + */ +public protocol AnimationTextProvider: AnyObject { + func textFor(keypathName: String, sourceText: String) -> String +} + +/// Text provider that simply map values from dictionary +public final class DictionaryTextProvider: AnimationTextProvider { + + public init(_ values: [String: String]) { + self.values = values + } + + let values: [String: String] + + public func textFor(keypathName: String, sourceText: String) -> String { + return values[keypathName] ?? sourceText + } +} + +/// Default text provider. Uses text in the animation file +public final class DefaultTextProvider: AnimationTextProvider { + public func textFor(keypathName: String, sourceText: String) -> String { + return sourceText + } + + public init() {} +} + diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedButton.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedButton.swift new file mode 100644 index 0000000..8faa811 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedButton.swift @@ -0,0 +1,68 @@ +// +// AnimatedButton.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit +/** + An interactive button that plays an animation when pressed. + */ +final public class AnimatedButton: AnimatedControl { + + /// Sets the play range for the given UIControlEvent. + public func setPlayRange(fromProgress: AnimationProgressTime, toProgress: AnimationProgressTime, event: UIControl.Event) { + rangesForEvents[event.rawValue] = (from: fromProgress, to: toProgress) + } + + /// Sets the play range for the given UIControlEvent. + public func setPlayRange(fromMarker fromName: String, toMarker toName: String, event: UIControl.Event) { + if let start = animationView.progressTime(forMarker: fromName), + let end = animationView.progressTime(forMarker: toName) { + rangesForEvents[event.rawValue] = (from: start, to: end) + } + } + + public override init(animation: Animation) { + super.init(animation: animation) + self.accessibilityTraits = UIAccessibilityTraits.button + } + + public override init() { + super.init() + self.accessibilityTraits = UIAccessibilityTraits.button + } + + fileprivate var rangesForEvents: [UInt : (from: CGFloat, to: CGFloat)] = [UIControl.Event.touchUpInside.rawValue : (from: 0, to: 1)] + + required public init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + } + + public override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { + let _ = super.beginTracking(touch, with: event) + let touchEvent = UIControl.Event.touchDown + if let playrange = rangesForEvents[touchEvent.rawValue] { + animationView.play(fromProgress: playrange.from, toProgress: playrange.to, loopMode: LottieLoopMode.playOnce) + } + return true + } + + public override func endTracking(_ touch: UITouch?, with event: UIEvent?) { + super.endTracking(touch, with: event) + let touchEvent: UIControl.Event + if let touch = touch, bounds.contains(touch.location(in: self)) { + touchEvent = UIControl.Event.touchUpInside + } else { + touchEvent = UIControl.Event.touchUpOutside + } + + if let playrange = rangesForEvents[touchEvent.rawValue] { + animationView.play(fromProgress: playrange.from, toProgress: playrange.to, loopMode: LottieLoopMode.playOnce) + } + } +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedControl.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedControl.swift new file mode 100644 index 0000000..ab43c26 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedControl.swift @@ -0,0 +1,166 @@ +// +// AnimatedControl.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +/** + Lottie comes prepacked with a two Animated Controls, `AnimatedSwitch` and + `AnimatedButton`. Both of these controls are built on top of `AnimatedControl` + + `AnimatedControl` is a subclass of `UIControl` that provides an interactive + mechanism for controlling the visual state of an animation in response to + user actions. + + The `AnimatedControl` will show and hide layers depending on the current + `UIControl.State` of the control. + + Users of `AnimationControl` can set a Layer Name for each `UIControl.State`. + When the state is change the `AnimationControl` will change the visibility + of its layers. + + NOTE: Do not initialize directly. This is intended to be subclassed. + */ +open class AnimatedControl: UIControl { + + // MARK: Public + + /// The animation view in which the animation is rendered. + public let animationView: AnimationView + + /// The animation backing the animated control. + public var animation: Animation? { + didSet { + animationView.animation = animation + animationView.bounds = animation?.bounds ?? .zero + setNeedsLayout() + updateForState() + animationDidSet() + } + } + + /// The speed of the animation playback. Defaults to 1 + public var animationSpeed: CGFloat { + set { animationView.animationSpeed = newValue } + get { return animationView.animationSpeed } + } + + /// Sets which Animation Layer should be visible for the given state. + public func setLayer(named: String, forState: UIControl.State) { + stateMap[forState.rawValue] = named + updateForState() + } + + /// Sets a ValueProvider for the specified keypath + public func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) { + animationView.setValueProvider(valueProvider, keypath: keypath) + } + + // MARK: Initializers + + public init(animation: Animation) { + self.animationView = AnimationView(animation: animation) + super.init(frame: animation.bounds) + commonInit() + } + + public init() { + self.animationView = AnimationView() + super.init(frame: .zero) + commonInit() + } + + required public init?(coder aDecoder: NSCoder) { + self.animationView = AnimationView() + super.init(coder: aDecoder) + commonInit() + } + + // MARK: UIControl Overrides + + open override var isEnabled: Bool { + didSet { + updateForState() + } + } + + open override var isSelected: Bool { + didSet { + updateForState() + } + } + + open override var isHighlighted: Bool { + didSet { + updateForState() + } + } + + open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { + updateForState() + return super.beginTracking(touch, with: event) + } + + open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { + updateForState() + return super.continueTracking(touch, with: event) + } + + open override func endTracking(_ touch: UITouch?, with event: UIEvent?) { + updateForState() + return super.endTracking(touch, with: event) + } + + open override func cancelTracking(with event: UIEvent?) { + updateForState() + super.cancelTracking(with: event) + } + + open override var intrinsicContentSize: CGSize { + return animationView.intrinsicContentSize + } + + open func animationDidSet() { + + } + + // MARK: Private + + var stateMap: [UInt : String] = [:] + + fileprivate func commonInit() { + animationView.clipsToBounds = false + clipsToBounds = true + animationView.translatesAutoresizingMaskIntoConstraints = false + animationView.backgroundBehavior = .forceFinish + addSubview(animationView) + animationView.contentMode = .scaleAspectFit + animationView.isUserInteractionEnabled = false + animationView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true + animationView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true + animationView.topAnchor.constraint(equalTo: topAnchor).isActive = true + animationView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true + } + + func updateForState() { + guard let animationLayer = animationView.animationLayer else { return } + if let layerName = stateMap[state.rawValue], + let stateLayer = animationLayer.layer(for: AnimationKeypath(keypath: layerName)) { + for layer in animationLayer.animationLayers { + layer.isHidden = true + } + stateLayer.isHidden = false + } else { + for layer in animationLayer.animationLayers { + layer.isHidden = false + } + } + } + +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedSwitch.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedSwitch.swift new file mode 100644 index 0000000..5cfc957 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimatedSwitch.swift @@ -0,0 +1,194 @@ +// +// AnimatedSwitch.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +/** + An interactive switch with an 'On' and 'Off' state. When the user taps on the + switch the state is toggled and the appropriate animation is played. + + Both the 'On' and 'Off' have an animation play range associated with their state. + */ +final public class AnimatedSwitch: AnimatedControl { + + /// Defines what happens when the user taps the switch while an + /// animation is still in flight + public enum CancelBehavior { + case reverse // default - plays the current animation in reverse + case none // does not update the animation when canceled + } + + /// The current state of the switch. + public var isOn: Bool { + set { + /// This is forwarded to a private variable because the animation needs to be updated without animation when set externally and with animation when set internally. + guard _isOn != newValue else { return } + updateOnState(isOn: newValue, animated: false, shouldFireHaptics: false) + } + get { + return _isOn + } + } + + /// The cancel behavior for the switch. See CancelBehavior for options + public var cancelBehavior: CancelBehavior = .reverse + + /// Set the state of the switch and specify animation and haptics + public func setIsOn(_ isOn: Bool, animated: Bool, shouldFireHaptics: Bool = true) { + guard isOn != _isOn else { return } + updateOnState(isOn: isOn, animated: animated, shouldFireHaptics: shouldFireHaptics) + } + + /// Sets the play range for the given state. When the switch is toggled, the animation range is played. + public func setProgressForState(fromProgress: AnimationProgressTime, + toProgress: AnimationProgressTime, + forOnState: Bool) { + if forOnState { + onStartProgress = fromProgress + onEndProgress = toProgress + } else { + offStartProgress = fromProgress + offEndProgress = toProgress + } + + updateOnState(isOn: _isOn, animated: false, shouldFireHaptics: false) + } + + public override init(animation: Animation) { + /// Generate a haptic generator if available. + #if os(iOS) + if #available(iOS 10.0, *) { + self.hapticGenerator = HapticGenerator() + } else { + self.hapticGenerator = NullHapticGenerator() + } + #else + self.hapticGenerator = NullHapticGenerator() + #endif + super.init(animation: animation) + updateOnState(isOn: _isOn, animated: false, shouldFireHaptics: false) + self.accessibilityTraits = UIAccessibilityTraits.button + } + + public override init() { + /// Generate a haptic generator if available. + #if os(iOS) + if #available(iOS 10.0, *) { + self.hapticGenerator = HapticGenerator() + } else { + self.hapticGenerator = NullHapticGenerator() + } + #else + self.hapticGenerator = NullHapticGenerator() + #endif + super.init() + updateOnState(isOn: _isOn, animated: false, shouldFireHaptics: false) + self.accessibilityTraits = UIAccessibilityTraits.button + } + + required public init?(coder aDecoder: NSCoder) { + /// Generate a haptic generator if available. + #if os(iOS) + if #available(iOS 10.0, *) { + self.hapticGenerator = HapticGenerator() + } else { + self.hapticGenerator = NullHapticGenerator() + } + #else + self.hapticGenerator = NullHapticGenerator() + #endif + super.init(coder: aDecoder) + self.accessibilityTraits = UIAccessibilityTraits.button + } + + fileprivate var onStartProgress: CGFloat = 0 + fileprivate var onEndProgress: CGFloat = 1 + fileprivate var offStartProgress: CGFloat = 1 + fileprivate var offEndProgress: CGFloat = 0 + fileprivate var _isOn: Bool = false + fileprivate var hapticGenerator: ImpactGenerator + + // MARK: Animation State + + func updateOnState(isOn: Bool, animated: Bool, shouldFireHaptics: Bool) { + _isOn = isOn + var startProgress = isOn ? onStartProgress : offStartProgress + var endProgress = isOn ? onEndProgress : offEndProgress + let finalProgress = endProgress + + if cancelBehavior == .reverse { + let realtimeProgress = animationView.realtimeAnimationProgress + + let previousStateStart = isOn ? offStartProgress : onStartProgress + let previousStateEnd = isOn ? offEndProgress : onEndProgress + if realtimeProgress.isInRange(min(previousStateStart, previousStateEnd), + max(previousStateStart, previousStateEnd)) { + /// Animation is currently in the previous time range. Reverse the previous play. + startProgress = previousStateEnd + endProgress = previousStateStart + } + } + + updateAccessibilityLabel() + + guard animated == true else { + animationView.currentProgress = finalProgress + return + } + + if shouldFireHaptics { + self.hapticGenerator.generateImpact() + } + + animationView.play(fromProgress: startProgress, toProgress: endProgress, loopMode: LottieLoopMode.playOnce) { (finished) in + if finished == true { + self.animationView.currentProgress = finalProgress + } + } + } + + public override func endTracking(_ touch: UITouch?, with event: UIEvent?) { + super.endTracking(touch, with: event) + updateOnState(isOn: !_isOn, animated: true, shouldFireHaptics: true) + sendActions(for: .valueChanged) + } + + public override func animationDidSet() { + updateOnState(isOn: _isOn, animated: true, shouldFireHaptics: false) + } + + // MARK: Private + + private func updateAccessibilityLabel() { + accessibilityValue = _isOn ? NSLocalizedString("On", comment: "On") : NSLocalizedString("Off", comment: "Off") + } + +} +#endif + +protocol ImpactGenerator { + func generateImpact() +} + +class NullHapticGenerator: ImpactGenerator { + func generateImpact() { + + } +} + +#if os(iOS) +@available(iOS 10.0, *) +class HapticGenerator: ImpactGenerator { + func generateImpact() { + impact.impactOccurred() + } + + fileprivate let impact = UIImpactFeedbackGenerator(style: .light) +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimationSubview.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimationSubview.swift new file mode 100644 index 0000000..d8bc7a9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/AnimationSubview.swift @@ -0,0 +1,20 @@ +// +// AnimationSubview.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +/// A view that can be added to a keypath of an AnimationView +public final class AnimationSubview: UIView { + + var viewLayer: CALayer? { + return layer + } + +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/BundleImageProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/BundleImageProvider.swift new file mode 100644 index 0000000..135cfd9 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/BundleImageProvider.swift @@ -0,0 +1,87 @@ +// +// LottieBundleImageProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 1/25/19. +// + +import Foundation +import CoreGraphics +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +/** + An `AnimationImageProvider` that provides images by name from a specific bundle. + The BundleImageProvider is initialized with a bundle and an optional searchPath. + */ +public class BundleImageProvider: AnimationImageProvider { + + let bundle: Bundle + let searchPath: String? + + /** + Initializes an image provider with a bundle and an optional subpath. + + Provides images for an animation from a bundle. Additionally the provider can + search a specific subpath for the images. + + - Parameter bundle: The bundle containing images for the provider. + - Parameter searchPath: The subpath is a path within the bundle to search for image assets. + + */ + public init(bundle: Bundle, searchPath: String?) { + self.bundle = bundle + self.searchPath = searchPath + } + + public func imageForAsset(asset: ImageAsset) -> CGImage? { + + if asset.name.hasPrefix("data:"), + let url = URL(string: asset.name), + let data = try? Data(contentsOf: url), + let image = UIImage(data: data) { + return image.cgImage + } + + let imagePath: String? + /// Try to find the image in the bundle. + if let searchPath = searchPath { + /// Search in the provided search path for the image + var directoryPath = URL(fileURLWithPath: searchPath) + directoryPath.appendPathComponent(asset.directory) + + if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: directoryPath.path) { + /// First search for the image in the asset provided sub directory. + imagePath = path + } else if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: searchPath) { + /// Try finding the image in the search path. + imagePath = path + } else { + imagePath = bundle.path(forResource: asset.name, ofType: nil) + } + } else { + if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: asset.directory) { + /// First search for the image in the asset provided sub directory. + imagePath = path + } else { + /// First search for the image in bundle. + imagePath = bundle.path(forResource: asset.name, ofType: nil) + } + } + + if imagePath == nil { + guard let image = UIImage(named: asset.name, in: bundle, compatibleWith: nil) else { + return nil + } + return image.cgImage + } + + guard let foundPath = imagePath, let image = UIImage(contentsOfFile: foundPath) else { + /// No image found. + return nil + } + return image.cgImage + } + +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationKeypath.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationKeypath.swift new file mode 100644 index 0000000..d6683af --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationKeypath.swift @@ -0,0 +1,29 @@ +// +// CompatibleAnimationKeypath.swift +// Lottie_iOS +// +// Created by Tyler Hedrick on 3/6/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) + +/// An Objective-C compatible wrapper around Lottie's AnimationKeypath +@objc +public final class CompatibleAnimationKeypath: NSObject { + + /// Creates a keypath from a dot separated string. The string is separated by "." + @objc + public init(keypath: String) { + animationKeypath = AnimationKeypath(keypath: keypath) + } + + /// Creates a keypath from a list of strings. + @objc + public init(keys: [String]) { + animationKeypath = AnimationKeypath(keys: keys) + } + + public let animationKeypath: AnimationKeypath +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationView.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationView.swift new file mode 100644 index 0000000..a248b6a --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/Compatibility/CompatibleAnimationView.swift @@ -0,0 +1,314 @@ +// +// CompatibleAnimationView.swift +// Lottie_iOS +// +// Created by Tyler Hedrick on 3/6/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +/// An Objective-C compatible wrapper around Lottie's Animation class. +/// Use in tandem with CompatibleAnimationView when using Lottie in Objective-C +@objc +public final class CompatibleAnimation: NSObject { + + @objc + static func named(_ name: String) -> CompatibleAnimation { + return CompatibleAnimation(name: name) + } + + @objc + public init(name: String, bundle: Bundle = Bundle.main) { + self.name = name + self.bundle = bundle + super.init() + } + + internal var animation: Animation? { + return Animation.named(name, bundle: bundle) + } + + // MARK: Private + + private let name: String + private let bundle: Bundle +} + +/// An Objective-C compatible wrapper around Lottie's AnimationView. +@objc +public final class CompatibleAnimationView: UIView { + + @objc + init(compatibleAnimation: CompatibleAnimation) { + animationView = AnimationView(animation: compatibleAnimation.animation) + self.compatibleAnimation = compatibleAnimation + super.init(frame: .zero) + commonInit() + } + + @objc + public override init(frame: CGRect) { + animationView = AnimationView() + super.init(frame: frame) + commonInit() + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: Public + + @objc + public var compatibleAnimation: CompatibleAnimation? { + didSet { + animationView.animation = compatibleAnimation?.animation + } + } + + @objc + public var loopAnimationCount: CGFloat = 0 { + didSet { + animationView.loopMode = loopAnimationCount == -1 ? .loop : .repeat(Float(loopAnimationCount)) + } + } + + @objc + public override var contentMode: UIView.ContentMode { + set { animationView.contentMode = newValue } + get { return animationView.contentMode } + } + + @objc + public var shouldRasterizeWhenIdle: Bool { + set { animationView.shouldRasterizeWhenIdle = newValue } + get { return animationView.shouldRasterizeWhenIdle } + } + + @objc + public var currentProgress: CGFloat { + set { animationView.currentProgress = newValue } + get { return animationView.currentProgress } + } + + @objc + public var currentTime: TimeInterval { + set { animationView.currentTime = newValue } + get { return animationView.currentTime } + } + + @objc + public var currentFrame: CGFloat { + set { animationView.currentFrame = newValue } + get { return animationView.currentFrame } + } + + @objc + public var realtimeAnimationFrame: CGFloat { + return animationView.realtimeAnimationFrame + } + + @objc + public var realtimeAnimationProgress: CGFloat { + return animationView.realtimeAnimationProgress + } + + @objc + public var animationSpeed: CGFloat { + set { animationView.animationSpeed = newValue } + get { return animationView.animationSpeed } + } + + @objc + public var respectAnimationFrameRate: Bool { + set { animationView.respectAnimationFrameRate = newValue } + get { return animationView.respectAnimationFrameRate } + } + + @objc + public var isAnimationPlaying: Bool { + return animationView.isAnimationPlaying + } + + @objc + public func play() { + play(completion: nil) + } + + @objc + public func play(completion: ((Bool) -> Void)?) { + animationView.play(completion: completion) + } + + @objc + public func play( + fromProgress: CGFloat, + toProgress: CGFloat, + completion: ((Bool) -> Void)? = nil) + { + animationView.play( + fromProgress: fromProgress, + toProgress: toProgress, + loopMode: nil, + completion: completion) + } + + @objc + public func play( + fromFrame: CGFloat, + toFrame: CGFloat, + completion: ((Bool) -> Void)? = nil) + { + animationView.play( + fromFrame: fromFrame, + toFrame: toFrame, + loopMode: nil, + completion: completion) + } + + @objc + public func play( + fromMarker: String, + toMarker: String, + completion: ((Bool) -> Void)? = nil) + { + animationView.play( + fromMarker: fromMarker, + toMarker: toMarker, + completion: completion) + } + + @objc + public func stop() { + animationView.stop() + } + + @objc + public func pause() { + animationView.pause() + } + + @objc + public func reloadImages() { + animationView.reloadImages() + } + + @objc + public func forceDisplayUpdate() { + animationView.forceDisplayUpdate() + } + + @objc + public func getValue( + for keypath: CompatibleAnimationKeypath, + atFrame: CGFloat) -> Any? + { + return animationView.getValue( + for: keypath.animationKeypath, + atFrame: atFrame) + } + + @objc + public func logHierarchyKeypaths() { + animationView.logHierarchyKeypaths() + } + + @objc + public func setColorValue(_ color: UIColor, forKeypath keypath: CompatibleAnimationKeypath) + { + var red: CGFloat = 0 + var green: CGFloat = 0 + var blue: CGFloat = 0 + var alpha: CGFloat = 0 + // TODO: Fix color spaces + let colorspace = CGColorSpaceCreateDeviceRGB() + + let convertedColor = color.cgColor.converted(to: colorspace, intent: .defaultIntent, options: nil) + + if let components = convertedColor?.components, components.count == 4 { + red = components[0] + green = components[1] + blue = components[2] + alpha = components[3] + } else { + color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) + } + + let valueProvider = ColorValueProvider(Color(r: Double(red), g: Double(green), b: Double(blue), a: Double(alpha))) + animationView.setValueProvider(valueProvider, keypath: keypath.animationKeypath) + } + + @objc + public func getColorValue(for keypath: CompatibleAnimationKeypath, atFrame: CGFloat) -> UIColor? + { + let value = animationView.getValue(for: keypath.animationKeypath, atFrame: atFrame) + guard let colorValue = value as? Color else { + return nil; + } + + return UIColor(red: CGFloat(colorValue.r), green: CGFloat(colorValue.g), blue: CGFloat(colorValue.b), alpha: CGFloat(colorValue.a)) + } + + @objc + public func addSubview( + _ subview: AnimationSubview, + forLayerAt keypath: CompatibleAnimationKeypath) + { + animationView.addSubview( + subview, + forLayerAt: keypath.animationKeypath) + } + + @objc + public func convert( + rect: CGRect, + toLayerAt keypath: CompatibleAnimationKeypath?) + -> CGRect + { + return animationView.convert( + rect, + toLayerAt: keypath?.animationKeypath) ?? .zero + } + + @objc + public func convert( + point: CGPoint, + toLayerAt keypath: CompatibleAnimationKeypath?) + -> CGPoint + { + return animationView.convert( + point, + toLayerAt: keypath?.animationKeypath) ?? .zero + } + + @objc + public func progressTime(forMarker named: String) -> CGFloat { + return animationView.progressTime(forMarker: named) ?? 0 + } + + @objc + public func frameTime(forMarker named: String) -> CGFloat { + return animationView.frameTime(forMarker: named) ?? 0 + } + + // MARK: Private + + private let animationView: AnimationView + + private func commonInit() { + translatesAutoresizingMaskIntoConstraints = false + setUpViews() + } + + private func setUpViews() { + animationView.translatesAutoresizingMaskIntoConstraints = false + addSubview(animationView) + animationView.topAnchor.constraint(equalTo: topAnchor).isActive = true + animationView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true + animationView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true + animationView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true + } +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/FilepathImageProvider.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/FilepathImageProvider.swift new file mode 100644 index 0000000..1de6e28 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/FilepathImageProvider.swift @@ -0,0 +1,56 @@ +// +// FilepathImageProvider.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/1/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +/** + Provides an image for a lottie animation from a provided Bundle. + */ +public class FilepathImageProvider: AnimationImageProvider { + + let filepath: URL + + /** + Initializes an image provider with a specific filepath. + + - Parameter filepath: The absolute filepath containing the images. + + */ + public init(filepath: String) { + self.filepath = URL(fileURLWithPath: filepath) + } + + public init(filepath: URL) { + self.filepath = filepath + } + + public func imageForAsset(asset: ImageAsset) -> CGImage? { + + if asset.name.hasPrefix("data:"), + let url = URL(string: asset.name), + let data = try? Data(contentsOf: url), + let image = UIImage(data: data) { + return image.cgImage + } + + let directPath = filepath.appendingPathComponent(asset.name).path + if FileManager.default.fileExists(atPath: directPath) { + return UIImage(contentsOfFile: directPath)?.cgImage + } + + let pathWithDirectory = filepath.appendingPathComponent(asset.directory).appendingPathComponent(asset.name).path + if FileManager.default.fileExists(atPath: pathWithDirectory) { + return UIImage(contentsOfFile: pathWithDirectory)?.cgImage + } + + return nil + } + +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/LottieView.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/LottieView.swift new file mode 100644 index 0000000..9030268 --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/LottieView.swift @@ -0,0 +1,62 @@ +// +// LottieView.swift +// lottie-swift-iOS +// +// Created by Brandon Withrow on 2/6/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +//public typealias LottieView = UIView + +open class LottieView: UIView { + + var viewLayer: CALayer? { + return layer + } + + func layoutAnimation() { + + } + + func animationMovedToWindow() { + + } + + open override func didMoveToWindow() { + super.didMoveToWindow() + animationMovedToWindow() + } + + var screenScale: CGFloat { + return UIScreen.main.scale + } + + func commonInit() { + contentMode = .scaleAspectFit + clipsToBounds = true + NotificationCenter.default.addObserver(self, selector: #selector(animationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(animationWillMoveToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) + } + + open override var contentMode: UIView.ContentMode { + didSet { + setNeedsLayout() + } + } + + open override func layoutSubviews() { + super.layoutSubviews() + self.layoutAnimation() + } + + @objc func animationWillMoveToBackground() { + } + + @objc func animationWillEnterForeground() { + } + +} +#endif diff --git a/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/UIColorExtension.swift b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/UIColorExtension.swift new file mode 100644 index 0000000..9319f1e --- /dev/null +++ b/sopt_29th_Assignment/Pods/lottie-ios/lottie-swift/src/Public/iOS/UIColorExtension.swift @@ -0,0 +1,21 @@ +// +// UIColorExtension.swift +// lottie-swift +// +// Created by Brandon Withrow on 2/4/19. +// + +import Foundation +#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) +import UIKit + +public extension UIColor { + + var lottieColorValue: Color { + var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 + getRed(&r, green: &g, blue: &b, alpha: &a) + return Color(r: Double(r), g: Double(g), b: Double(b), a: Double(a)) + } + +} +#endif diff --git a/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.pbxproj b/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.pbxproj index c589fbb..d7d8df0 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.pbxproj +++ b/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + D745BC8FFD0438C4A6EABAC4 /* Pods_sopt_29th_Assignment.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FDE0ADBE3C1804B8E78D70D9 /* Pods_sopt_29th_Assignment.framework */; }; FD5B934E27104DC700BE2364 /* makeVibrate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5B934D27104DC700BE2364 /* makeVibrate.swift */; }; FD5B935027104EFD00BE2364 /* applyShadow.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5B934F27104EFD00BE2364 /* applyShadow.swift */; }; FD5B935227104F4900BE2364 /* calculateTopInset.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5B935127104F4900BE2364 /* calculateTopInset.swift */; }; @@ -29,6 +30,30 @@ FD5B93822710741B00BE2364 /* StringLiterals.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5B93812710741B00BE2364 /* StringLiterals.swift */; }; FD5B938527107DD000BE2364 /* ImageLiterals.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5B938427107DD000BE2364 /* ImageLiterals.swift */; }; FD5B93872710841B00BE2364 /* addToolbar.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5B93862710841B00BE2364 /* addToolbar.swift */; }; + FD9D4587272A5F69006C108F /* SubscribeDataModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D4586272A5F69006C108F /* SubscribeDataModel.swift */; }; + FD9D4589272A5F78006C108F /* YoutuberDataModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D4588272A5F78006C108F /* YoutuberDataModel.swift */; }; + FD9D458B272A5FC8006C108F /* SubscribeFilterList + Load.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D458A272A5FC8006C108F /* SubscribeFilterList + Load.swift */; }; + FD9D458D272A6455006C108F /* VideoDataModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D458C272A6455006C108F /* VideoDataModel.swift */; }; + FD9D4590272A6F91006C108F /* CustomTableViewDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D458F272A6F91006C108F /* CustomTableViewDataSource.swift */; }; + FD9D4593272A74AF006C108F /* CustomCollectionViewDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D4592272A74AF006C108F /* CustomCollectionViewDataSource.swift */; }; + FD9D4595272A820F006C108F /* CustomTableViewSectionDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D4594272A820F006C108F /* CustomTableViewSectionDataSource.swift */; }; + FD9D459B272A8DF9006C108F /* SubscribeVideoTVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D4599272A8DF9006C108F /* SubscribeVideoTVC.swift */; }; + FD9D459C272A8DF9006C108F /* SubscribeVideoTVC.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD9D459A272A8DF9006C108F /* SubscribeVideoTVC.xib */; }; + FD9D45A0272A97C0006C108F /* calculateDate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D459F272A97C0006C108F /* calculateDate.swift */; }; + FD9D45A3272AA508006C108F /* UITableViewRegisterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45A2272AA508006C108F /* UITableViewRegisterable.swift */; }; + FD9D45A8272AAC24006C108F /* MainHeaderView.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD9D45A7272AAC24006C108F /* MainHeaderView.xib */; }; + FD9D45AA272AAC2D006C108F /* MainHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45A9272AAC2D006C108F /* MainHeaderView.swift */; }; + FD9D45AC272AAE8B006C108F /* SubscribeYoutuberContainerView.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD9D45AB272AAE8B006C108F /* SubscribeYoutuberContainerView.xib */; }; + FD9D45AE272AAEB6006C108F /* SubscribeYoutuberContainerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45AD272AAEB6006C108F /* SubscribeYoutuberContainerView.swift */; }; + FD9D45B5272AAFA1006C108F /* SubscribeYoutuberCVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45B3272AAFA1006C108F /* SubscribeYoutuberCVC.swift */; }; + FD9D45B6272AAFA1006C108F /* SubscribeYoutuberCVC.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD9D45B4272AAFA1006C108F /* SubscribeYoutuberCVC.xib */; }; + FD9D45B8272AB73F006C108F /* addSubViewFromNib.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45B7272AB73F006C108F /* addSubViewFromNib.swift */; }; + FD9D45BA272AB925006C108F /* UICollectionViewRegisterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45B9272AB925006C108F /* UICollectionViewRegisterable.swift */; }; + FD9D45BC272ABDD5006C108F /* SubscribeFilterContainerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45BB272ABDD5006C108F /* SubscribeFilterContainerView.swift */; }; + FD9D45BE272ABDE5006C108F /* SubscribeFilterContainerView.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD9D45BD272ABDE5006C108F /* SubscribeFilterContainerView.xib */; }; + FD9D45C1272ABE51006C108F /* SubscribeFilterCVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45BF272ABE51006C108F /* SubscribeFilterCVC.swift */; }; + FD9D45C2272ABE51006C108F /* SubscribeFilterCVC.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD9D45C0272ABE51006C108F /* SubscribeFilterCVC.xib */; }; + FD9D45C4272AC726006C108F /* SubscribeVC + UIScrollViewDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9D45C3272AC726006C108F /* SubscribeVC + UIScrollViewDelegate.swift */; }; FDCD39E0271C50490072AB10 /* Presentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDCD39DF271C50490072AB10 /* Presentable.swift */; }; FDCD39E2271C50650072AB10 /* CoordinatorFinishOutput.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDCD39E1271C50650072AB10 /* CoordinatorFinishOutput.swift */; }; FDCD39E4271C507A0072AB10 /* BaseControllable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDCD39E3271C507A0072AB10 /* BaseControllable.swift */; }; @@ -68,6 +93,8 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 42692C6758410515ECBFA1B7 /* Pods-sopt_29th_Assignment.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-sopt_29th_Assignment.release.xcconfig"; path = "Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.release.xcconfig"; sourceTree = ""; }; + 7BA0EBF00B8797B38A1E8890 /* Pods-sopt_29th_Assignment.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-sopt_29th_Assignment.debug.xcconfig"; path = "Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment.debug.xcconfig"; sourceTree = ""; }; FD5B934D27104DC700BE2364 /* makeVibrate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = makeVibrate.swift; sourceTree = ""; }; FD5B934F27104EFD00BE2364 /* applyShadow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = applyShadow.swift; sourceTree = ""; }; FD5B935127104F4900BE2364 /* calculateTopInset.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = calculateTopInset.swift; sourceTree = ""; }; @@ -88,6 +115,30 @@ FD5B93812710741B00BE2364 /* StringLiterals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringLiterals.swift; sourceTree = ""; }; FD5B938427107DD000BE2364 /* ImageLiterals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageLiterals.swift; sourceTree = ""; }; FD5B93862710841B00BE2364 /* addToolbar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = addToolbar.swift; sourceTree = ""; }; + FD9D4586272A5F69006C108F /* SubscribeDataModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscribeDataModel.swift; sourceTree = ""; }; + FD9D4588272A5F78006C108F /* YoutuberDataModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YoutuberDataModel.swift; sourceTree = ""; }; + FD9D458A272A5FC8006C108F /* SubscribeFilterList + Load.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SubscribeFilterList + Load.swift"; sourceTree = ""; }; + FD9D458C272A6455006C108F /* VideoDataModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoDataModel.swift; sourceTree = ""; }; + FD9D458F272A6F91006C108F /* CustomTableViewDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomTableViewDataSource.swift; sourceTree = ""; }; + FD9D4592272A74AF006C108F /* CustomCollectionViewDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomCollectionViewDataSource.swift; sourceTree = ""; }; + FD9D4594272A820F006C108F /* CustomTableViewSectionDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomTableViewSectionDataSource.swift; sourceTree = ""; }; + FD9D4599272A8DF9006C108F /* SubscribeVideoTVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscribeVideoTVC.swift; sourceTree = ""; }; + FD9D459A272A8DF9006C108F /* SubscribeVideoTVC.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = SubscribeVideoTVC.xib; sourceTree = ""; }; + FD9D459F272A97C0006C108F /* calculateDate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = calculateDate.swift; sourceTree = ""; }; + FD9D45A2272AA508006C108F /* UITableViewRegisterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UITableViewRegisterable.swift; sourceTree = ""; }; + FD9D45A7272AAC24006C108F /* MainHeaderView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = MainHeaderView.xib; sourceTree = ""; }; + FD9D45A9272AAC2D006C108F /* MainHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainHeaderView.swift; sourceTree = ""; }; + FD9D45AB272AAE8B006C108F /* SubscribeYoutuberContainerView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = SubscribeYoutuberContainerView.xib; sourceTree = ""; }; + FD9D45AD272AAEB6006C108F /* SubscribeYoutuberContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscribeYoutuberContainerView.swift; sourceTree = ""; }; + FD9D45B3272AAFA1006C108F /* SubscribeYoutuberCVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscribeYoutuberCVC.swift; sourceTree = ""; }; + FD9D45B4272AAFA1006C108F /* SubscribeYoutuberCVC.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = SubscribeYoutuberCVC.xib; sourceTree = ""; }; + FD9D45B7272AB73F006C108F /* addSubViewFromNib.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = addSubViewFromNib.swift; sourceTree = ""; }; + FD9D45B9272AB925006C108F /* UICollectionViewRegisterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UICollectionViewRegisterable.swift; sourceTree = ""; }; + FD9D45BB272ABDD5006C108F /* SubscribeFilterContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscribeFilterContainerView.swift; sourceTree = ""; }; + FD9D45BD272ABDE5006C108F /* SubscribeFilterContainerView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = SubscribeFilterContainerView.xib; sourceTree = ""; }; + FD9D45BF272ABE51006C108F /* SubscribeFilterCVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscribeFilterCVC.swift; sourceTree = ""; }; + FD9D45C0272ABE51006C108F /* SubscribeFilterCVC.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = SubscribeFilterCVC.xib; sourceTree = ""; }; + FD9D45C3272AC726006C108F /* SubscribeVC + UIScrollViewDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SubscribeVC + UIScrollViewDelegate.swift"; sourceTree = ""; }; FDCD39DF271C50490072AB10 /* Presentable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Presentable.swift; sourceTree = ""; }; FDCD39E1271C50650072AB10 /* CoordinatorFinishOutput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoordinatorFinishOutput.swift; sourceTree = ""; }; FDCD39E3271C507A0072AB10 /* BaseControllable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseControllable.swift; sourceTree = ""; }; @@ -129,6 +180,7 @@ FDD7A6C1270AB1BE0099F245 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; FDD7A6C4270AB1BE0099F245 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; FDD7A6C6270AB1BE0099F245 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = "sopt_29th_Assignment/Global/Supporting FIles/Info.plist"; sourceTree = SOURCE_ROOT; }; + FDE0ADBE3C1804B8E78D70D9 /* Pods_sopt_29th_Assignment.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_sopt_29th_Assignment.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -136,15 +188,34 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + D745BC8FFD0438C4A6EABAC4 /* Pods_sopt_29th_Assignment.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 10061CBCE8FC6BF76EFCFD76 /* Pods */ = { + isa = PBXGroup; + children = ( + 7BA0EBF00B8797B38A1E8890 /* Pods-sopt_29th_Assignment.debug.xcconfig */, + 42692C6758410515ECBFA1B7 /* Pods-sopt_29th_Assignment.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 34B50A1F613194144E39964D /* Frameworks */ = { + isa = PBXGroup; + children = ( + FDE0ADBE3C1804B8E78D70D9 /* Pods_sopt_29th_Assignment.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; FD5B934827104B3700BE2364 /* Screens */ = { isa = PBXGroup; children = ( + FD9D45A5272AABF0006C108F /* CommonViews */, FDCD3A06271C7C130072AB10 /* Library */, FDCD3A05271C7C0C0072AB10 /* Subscribe */, FDCD3A04271C7BFE0072AB10 /* Writing */, @@ -160,6 +231,8 @@ FD5B934927104B5E00BE2364 /* Global */ = { isa = PBXGroup; children = ( + FD9D45A1272AA4F1006C108F /* Protocols */, + FD9D4581272A5E60006C108F /* Models */, FD5B93752710637E00BE2364 /* UIComponents */, FD5B93602710559800BE2364 /* Storyboards */, FD5B93562710501000BE2364 /* Extension */, @@ -187,6 +260,7 @@ FD5B935127104F4900BE2364 /* calculateTopInset.swift */, FD5B93862710841B00BE2364 /* addToolbar.swift */, FDCD39FB271C6B260072AB10 /* Logged + UserDefaults.swift */, + FD9D459F272A97C0006C108F /* calculateDate.swift */, ); path = Utils; sourceTree = ""; @@ -220,6 +294,7 @@ FDCD3A11271C83DD0072AB10 /* UIImage + Extension.swift */, FDCD3A13271C84B70072AB10 /* NotificationName+Extension.swift */, FDCD3A31271CB03E0072AB10 /* UIColor + Extension.swift */, + FD9D45B7272AB73F006C108F /* addSubViewFromNib.swift */, ); path = Extension; sourceTree = ""; @@ -266,12 +341,107 @@ FD5B93752710637E00BE2364 /* UIComponents */ = { isa = PBXGroup; children = ( + FD9D4591272A74A0006C108F /* CollectionView */, + FD9D458E272A6F35006C108F /* TableView */, FD5B9376271063A500BE2364 /* CustomInputTextField.swift */, FD5B937D27106CB500BE2364 /* CustomBlueButton.swift */, ); path = UIComponents; sourceTree = ""; }; + FD9D4581272A5E60006C108F /* Models */ = { + isa = PBXGroup; + children = ( + FD9D4585272A5F5D006C108F /* Subscribe */, + ); + path = Models; + sourceTree = ""; + }; + FD9D4585272A5F5D006C108F /* Subscribe */ = { + isa = PBXGroup; + children = ( + FD9D4586272A5F69006C108F /* SubscribeDataModel.swift */, + FD9D4588272A5F78006C108F /* YoutuberDataModel.swift */, + FD9D458C272A6455006C108F /* VideoDataModel.swift */, + FD9D458A272A5FC8006C108F /* SubscribeFilterList + Load.swift */, + ); + path = Subscribe; + sourceTree = ""; + }; + FD9D458E272A6F35006C108F /* TableView */ = { + isa = PBXGroup; + children = ( + FD9D458F272A6F91006C108F /* CustomTableViewDataSource.swift */, + FD9D4594272A820F006C108F /* CustomTableViewSectionDataSource.swift */, + ); + path = TableView; + sourceTree = ""; + }; + FD9D4591272A74A0006C108F /* CollectionView */ = { + isa = PBXGroup; + children = ( + FD9D4592272A74AF006C108F /* CustomCollectionViewDataSource.swift */, + ); + path = CollectionView; + sourceTree = ""; + }; + FD9D4598272A8DD5006C108F /* Video */ = { + isa = PBXGroup; + children = ( + FD9D4599272A8DF9006C108F /* SubscribeVideoTVC.swift */, + FD9D459A272A8DF9006C108F /* SubscribeVideoTVC.xib */, + ); + path = Video; + sourceTree = ""; + }; + FD9D459D272A9202006C108F /* Filter */ = { + isa = PBXGroup; + children = ( + FD9D45BB272ABDD5006C108F /* SubscribeFilterContainerView.swift */, + FD9D45BD272ABDE5006C108F /* SubscribeFilterContainerView.xib */, + FD9D45BF272ABE51006C108F /* SubscribeFilterCVC.swift */, + FD9D45C0272ABE51006C108F /* SubscribeFilterCVC.xib */, + ); + path = Filter; + sourceTree = ""; + }; + FD9D459E272A9206006C108F /* Youtuber */ = { + isa = PBXGroup; + children = ( + FD9D45AB272AAE8B006C108F /* SubscribeYoutuberContainerView.xib */, + FD9D45AD272AAEB6006C108F /* SubscribeYoutuberContainerView.swift */, + FD9D45B3272AAFA1006C108F /* SubscribeYoutuberCVC.swift */, + FD9D45B4272AAFA1006C108F /* SubscribeYoutuberCVC.xib */, + ); + path = Youtuber; + sourceTree = ""; + }; + FD9D45A1272AA4F1006C108F /* Protocols */ = { + isa = PBXGroup; + children = ( + FD9D45A2272AA508006C108F /* UITableViewRegisterable.swift */, + FD9D45B9272AB925006C108F /* UICollectionViewRegisterable.swift */, + ); + path = Protocols; + sourceTree = ""; + }; + FD9D45A5272AABF0006C108F /* CommonViews */ = { + isa = PBXGroup; + children = ( + FD9D45A6272AABFE006C108F /* Header */, + ); + path = CommonViews; + sourceTree = ""; + }; + FD9D45A6272AABFE006C108F /* Header */ = { + isa = PBXGroup; + children = ( + FD9D45A7272AAC24006C108F /* MainHeaderView.xib */, + FD9D45A9272AAC2D006C108F /* MainHeaderView.swift */, + ); + path = Header; + sourceTree = ""; + }; FDCD39DD271C4E7B0072AB10 /* Coordinator */ = { isa = PBXGroup; children = ( @@ -376,7 +546,11 @@ FDCD3A05271C7C0C0072AB10 /* Subscribe */ = { isa = PBXGroup; children = ( + FD9D459E272A9206006C108F /* Youtuber */, + FD9D459D272A9202006C108F /* Filter */, + FD9D4598272A8DD5006C108F /* Video */, FDCD3A0D271C7C430072AB10 /* SubscribeVC.swift */, + FD9D45C3272AC726006C108F /* SubscribeVC + UIScrollViewDelegate.swift */, FDCD3A1B271C85370072AB10 /* Subscribe.storyboard */, ); path = Subscribe; @@ -396,6 +570,8 @@ children = ( FDD7A6B7270AB1BC0099F245 /* sopt_29th_Assignment */, FDD7A6B6270AB1BC0099F245 /* Products */, + 10061CBCE8FC6BF76EFCFD76 /* Pods */, + 34B50A1F613194144E39964D /* Frameworks */, ); sourceTree = ""; }; @@ -424,9 +600,11 @@ isa = PBXNativeTarget; buildConfigurationList = FDD7A6C9270AB1BE0099F245 /* Build configuration list for PBXNativeTarget "sopt_29th_Assignment" */; buildPhases = ( + 574CB164059E57F1DD0A28DA /* [CP] Check Pods Manifest.lock */, FDD7A6B1270AB1BC0099F245 /* Sources */, FDD7A6B2270AB1BC0099F245 /* Frameworks */, FDD7A6B3270AB1BC0099F245 /* Resources */, + B1A0938C110466ED4676759F /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -477,19 +655,67 @@ buildActionMask = 2147483647; files = ( FD5B936F2710609E00BE2364 /* Account.storyboard in Resources */, + FD9D45C2272ABE51006C108F /* SubscribeFilterCVC.xib in Resources */, FDCD3A18271C851A0072AB10 /* Writing.storyboard in Resources */, + FD9D45BE272ABDE5006C108F /* SubscribeFilterContainerView.xib in Resources */, + FD9D459C272A8DF9006C108F /* SubscribeVideoTVC.xib in Resources */, FD5B93792710674800BE2364 /* Assets.xcassets in Resources */, FDCD3A1A271C852B0072AB10 /* Shorts.storyboard in Resources */, FD5B93782710670500BE2364 /* Main.storyboard in Resources */, + FD9D45A8272AAC24006C108F /* MainHeaderView.xib in Resources */, FDCD3A1C271C85370072AB10 /* Subscribe.storyboard in Resources */, FDCD3A1E271C85450072AB10 /* Library.storyboard in Resources */, FDCD3A22271C85750072AB10 /* MainTab.storyboard in Resources */, + FD9D45AC272AAE8B006C108F /* SubscribeYoutuberContainerView.xib in Resources */, FDCD3A16271C850B0072AB10 /* Home.storyboard in Resources */, + FD9D45B6272AAFA1006C108F /* SubscribeYoutuberCVC.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 574CB164059E57F1DD0A28DA /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-sopt_29th_Assignment-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + B1A0938C110466ED4676759F /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-sopt_29th_Assignment/Pods-sopt_29th_Assignment-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ FDD7A6B1270AB1BC0099F245 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -500,35 +726,47 @@ FDCD3A2C271C87580072AB10 /* LibraryCoordinator.swift in Sources */, FDCD39E6271C50870072AB10 /* Coordinator.swift in Sources */, FD5B93582710501F00BE2364 /* getClassName + UIViewController.swift in Sources */, + FD9D45C1272ABE51006C108F /* SubscribeFilterCVC.swift in Sources */, FDCD39F4271C5DF60072AB10 /* LaunchInstructor.swift in Sources */, FDCD39E9271C50C30072AB10 /* Router.swift in Sources */, + FD9D45BA272AB925006C108F /* UICollectionViewRegisterable.swift in Sources */, FDCD39F1271C5D980072AB10 /* ApplicationCoordinator.swift in Sources */, FD5B935027104EFD00BE2364 /* applyShadow.swift in Sources */, FDCD3A14271C84B70072AB10 /* NotificationName+Extension.swift in Sources */, FDCD3A26271C87340072AB10 /* ShortsCoordinator.swift in Sources */, FDCD3A24271C87270072AB10 /* HomeCoordinator.swift in Sources */, FDCD3A0A271C7C2D0072AB10 /* ShortsVC.swift in Sources */, + FD9D4593272A74AF006C108F /* CustomCollectionViewDataSource.swift in Sources */, FD5B937E27106CB500BE2364 /* CustomBlueButton.swift in Sources */, FD5B938027106DBD00BE2364 /* ColorLiterals.swift in Sources */, FDCD39E2271C50650072AB10 /* CoordinatorFinishOutput.swift in Sources */, FDCD39FE271C773B0072AB10 /* MainTabCoordinator.swift in Sources */, + FD9D459B272A8DF9006C108F /* SubscribeVideoTVC.swift in Sources */, FD5B93822710741B00BE2364 /* StringLiterals.swift in Sources */, FDCD3A30271CAFD60072AB10 /* MainNavigationController.swift in Sources */, FDCD3A2A271C874F0072AB10 /* SubscribeCoordinator.swift in Sources */, FDCD39E0271C50490072AB10 /* Presentable.swift in Sources */, FDCD39EE271C58CD0072AB10 /* BaseCoordinator.swift in Sources */, + FD9D4595272A820F006C108F /* CustomTableViewSectionDataSource.swift in Sources */, FD5B9377271063A500BE2364 /* CustomInputTextField.swift in Sources */, + FD9D45B5272AAFA1006C108F /* SubscribeYoutuberCVC.swift in Sources */, FDD7A6BD270AB1BC0099F245 /* ViewController.swift in Sources */, FDCD3A01271C78EB0072AB10 /* MainTabBarController.swift in Sources */, + FD9D45B8272AB73F006C108F /* addSubViewFromNib.swift in Sources */, FDCD3A0C271C7C390072AB10 /* WritingVC.swift in Sources */, + FD9D45C4272AC726006C108F /* SubscribeVC + UIScrollViewDelegate.swift in Sources */, FDCD3A0E271C7C430072AB10 /* SubscribeVC.swift in Sources */, FD5B935227104F4900BE2364 /* calculateTopInset.swift in Sources */, FD5B9365271056BE00BE2364 /* ModuleFactory.swift in Sources */, FD5B936927105F7A00BE2364 /* SignInVC.swift in Sources */, + FD9D458B272A5FC8006C108F /* SubscribeFilterList + Load.swift in Sources */, + FD9D4590272A6F91006C108F /* CustomTableViewDataSource.swift in Sources */, FDCD3A10271C7CB10072AB10 /* LibraryVC.swift in Sources */, FDCD3A08271C7C250072AB10 /* HomeVC.swift in Sources */, FD5B9362271055A100BE2364 /* Storyboards.swift in Sources */, FDD7A6B9270AB1BC0099F245 /* AppDelegate.swift in Sources */, + FD9D4589272A5F78006C108F /* YoutuberDataModel.swift in Sources */, + FD9D45AA272AAC2D006C108F /* MainHeaderView.swift in Sources */, FD5B937C271067E300BE2364 /* addPadding + UITextField.swift in Sources */, FDCD3A32271CB03E0072AB10 /* UIColor + Extension.swift in Sources */, FD5B935F2710557200BE2364 /* controllerFromStoryboard + UIViewController.swift in Sources */, @@ -537,8 +775,14 @@ FDCD39FA271C63A30072AB10 /* SigningCoordinator.swift in Sources */, FD5B934E27104DC700BE2364 /* makeVibrate.swift in Sources */, FDCD3A2E271C8DD20072AB10 /* SceneDelegate.swift in Sources */, + FD9D458D272A6455006C108F /* VideoDataModel.swift in Sources */, + FD9D45BC272ABDD5006C108F /* SubscribeFilterContainerView.swift in Sources */, + FD9D45A3272AA508006C108F /* UITableViewRegisterable.swift in Sources */, + FD9D45AE272AAEB6006C108F /* SubscribeYoutuberContainerView.swift in Sources */, FDCD39EB271C543D0072AB10 /* CoordinatorFactory.swift in Sources */, + FD9D4587272A5F69006C108F /* SubscribeDataModel.swift in Sources */, FD5B93872710841B00BE2364 /* addToolbar.swift in Sources */, + FD9D45A0272A97C0006C108F /* calculateDate.swift in Sources */, FDCD39E4271C507A0072AB10 /* BaseControllable.swift in Sources */, FDCD3A28271C873C0072AB10 /* WritingCoordinator.swift in Sources */, FD5B938527107DD000BE2364 /* ImageLiterals.swift in Sources */, @@ -689,6 +933,7 @@ }; FDD7A6CA270AB1BE0099F245 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 7BA0EBF00B8797B38A1E8890 /* Pods-sopt_29th_Assignment.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -717,6 +962,7 @@ }; FDD7A6CB270AB1BE0099F245 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 42692C6758410515ECBFA1B7 /* Pods-sopt_29th_Assignment.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; diff --git a/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.xcworkspace/xcuserdata/kone.xcuserdatad/UserInterfaceState.xcuserstate b/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.xcworkspace/xcuserdata/kone.xcuserdatad/UserInterfaceState.xcuserstate index edd9718..3b921aa 100644 Binary files a/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.xcworkspace/xcuserdata/kone.xcuserdatad/UserInterfaceState.xcuserstate and b/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/project.xcworkspace/xcuserdata/kone.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/xcschememanagement.plist b/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/xcschememanagement.plist index 4118fe4..9e1943b 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/sopt_29th_Assignment/sopt_29th_Assignment.xcodeproj/xcuserdata/kone.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ sopt_29th_Assignment.xcscheme_^#shared#^_ orderHint - 0 + 13 diff --git a/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/contents.xcworkspacedata b/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..9303c44 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/xcuserdata/kone.xcuserdatad/UserInterfaceState.xcuserstate b/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/xcuserdata/kone.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..942207e Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment.xcworkspace/xcuserdata/kone.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Extension/addSubViewFromNib.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Extension/addSubViewFromNib.swift new file mode 100644 index 0000000..4c1949d --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Extension/addSubViewFromNib.swift @@ -0,0 +1,17 @@ +// +// addSubViewFromNib.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + + +extension UIView{ + public func addSubviewFromNib(view : UIView){ + let view = Bundle.main.loadNibNamed(view.className, owner: self, options: nil)?.first as! UIView + view.frame = bounds + addSubview(view) + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Extension/getClassName + UIViewController.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Extension/getClassName + UIViewController.swift index 2b6d35e..83176f4 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Extension/getClassName + UIViewController.swift +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Extension/getClassName + UIViewController.swift @@ -31,20 +31,7 @@ extension UIViewController { } -extension UICollectionViewCell { - - static var className: String { - NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last! - } - - var className: String { - NSStringFromClass(self.classForCoder).components(separatedBy: ".").last! - } -} - - - -extension UITableViewCell { +extension UIView { static var className: String { NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last! diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ColorLiterals.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ColorLiterals.swift index 7e7df81..983fcde 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ColorLiterals.swift +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ColorLiterals.swift @@ -18,4 +18,13 @@ extension UIColor { @nonobjc class var gray: UIColor{ return UIColor(red: 138/255, green: 138/255, blue: 138/255, alpha: 1) } + @nonobjc class var darkGray: UIColor{ + return UIColor(red: 98/255, green: 98/255, blue: 98/255, alpha: 1) + } + @nonobjc class var palerGray: UIColor{ + return UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1) + } + @nonobjc class var borderColor: UIColor{ + return UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1) + } } diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ImageLiterals.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ImageLiterals.swift index 149aba9..3aad039 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ImageLiterals.swift +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/ImageLiterals.swift @@ -27,5 +27,33 @@ struct ImageLiterals{ static let library_activated = UIImage(named :"LibraryIconFill")! static let library_unactivated = UIImage(named :"LibraryIcon")! } + + struct Header{ + static let main_logo = UIImage(named: "ic_main_logo")! + static let air_play = UIImage(named: "ic_airplay")! + static let alarm = UIImage(named: "ic_alarm")! + static let search = UIImage(named: "ic_search")! + static let userIcon = UIImage(named: "ic_sopt")! + } + + struct Subscribe{ + + struct Youtuber{ + static let ggamju1 = UIImage(named: "ggamju1")! + static let ggamju2 = UIImage(named: "ggamju2")! + static let ggamju3 = UIImage(named: "ggamju3")! + static let ggamju4 = UIImage(named: "ggamju4")! + static let ggamju5 = UIImage(named: "ggamju5")! + static let ggamju6 = UIImage(named: "ggamju6")! + } + + struct Video{ + static let thumbnail = UIImage(named: "wesoptiOSPart")! + static let userIcon = UIImage(named: "ic_sopt")! + } + + } + + } diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/StringLiterals.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/StringLiterals.swift index 2b45d4c..39eae81 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/StringLiterals.swift +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Literals/StringLiterals.swift @@ -13,6 +13,7 @@ struct I18N{ struct Components{ static let next = "다음" static let ok = "확인" + static let total = "전체" } @@ -29,4 +30,15 @@ struct I18N{ static let subscribe = "구독" static let library = "보관함" } + + struct Subscribe{ + struct Filter{ + static let total = "전체" + static let today = "오늘" + static let continueToWatch = "이어서 시청하기" + static let noWatch = "시청하지 않음" + static let live = "실시간" + static let article = "게시물" + } + } } diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/SubscribeDataModel.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/SubscribeDataModel.swift new file mode 100644 index 0000000..977fb09 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/SubscribeDataModel.swift @@ -0,0 +1,12 @@ +// +// SubscribeDataModel.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import Foundation + +// 추후 하위 항목에서 Extension으로 확장해 사용. +struct SubscribeDataModel{ +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/SubscribeFilterList + Load.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/SubscribeFilterList + Load.swift new file mode 100644 index 0000000..8d3c5fe --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/SubscribeFilterList + Load.swift @@ -0,0 +1,33 @@ +// +// SubscribeFilterList + Load.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import Foundation + +extension SubscribeDataModel{ + + struct Filter{ + var sortCase : String + var idx : Int + } + + static func loadFilterList() -> [SubscribeDataModel.Filter]{ + return [ + SubscribeDataModel.Filter(sortCase: I18N.Subscribe.Filter.total, + idx: 0), + SubscribeDataModel.Filter(sortCase: I18N.Subscribe.Filter.today, + idx: 1), + SubscribeDataModel.Filter(sortCase: I18N.Subscribe.Filter.continueToWatch, + idx: 2), + SubscribeDataModel.Filter(sortCase: I18N.Subscribe.Filter.noWatch, + idx: 3), + SubscribeDataModel.Filter(sortCase: I18N.Subscribe.Filter.live, + idx: 4), + SubscribeDataModel.Filter(sortCase: I18N.Subscribe.Filter.article, + idx: 5) + ].sorted(by: {$0.idx < $1.idx}) + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/VideoDataModel.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/VideoDataModel.swift new file mode 100644 index 0000000..25f57de --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/VideoDataModel.swift @@ -0,0 +1,82 @@ +// +// VideoDataModel.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +extension SubscribeDataModel{ + struct Video{ + var thumbnailImage : UIImage + var idx : Int + var title : String + var url : String + var viewCount : Int + var time : String + var youtuber : SubscribeDataModel.Youtuber + + // 임시용으로 Dummy 데이터 로드함수 제작, 추후에는 네트워크에서 불러와서 처리 + static func loadDummyList() -> [SubscribeDataModel.Video]{ + let SOPT = Youtuber(thumbnailImage: ImageLiterals.Subscribe.Video.userIcon, name: "WE SOPT", idx: 0) + return [ + Video(thumbnailImage: ImageLiterals.Subscribe.Video.thumbnail, + idx: 100, + title: "1차 iOS 세미나 : iOS 컴포넌트 이해, Xcode 기본 사용법, View 화면전환", + url: "https://www.youtube.com/", + viewCount: 423, + time: "2021-09-02 12:00:13", + youtuber: SOPT), + + Video(thumbnailImage: ImageLiterals.Subscribe.Video.thumbnail, + idx: 101, + title: "2차 iOS 세미나 : AutoLayout, StackView, TabBarController", + url: "https://www.youtube.com/", + viewCount: 5123, + time: "2021-09-09 12:00:13", + youtuber: SOPT), + + Video(thumbnailImage: ImageLiterals.Subscribe.Video.thumbnail, + idx: 102, + title: "3차 iOS 세미나 : ScrollView, Delegate Pattern, TableView, CollectionView", + url: "https://www.youtube.com/", + viewCount: 423, + time: "2021-09-16 12:00:13", + youtuber: SOPT), + + Video(thumbnailImage: ImageLiterals.Subscribe.Video.thumbnail, + idx: 103, + title: "4차 iOS 세미나 : Cocoapods & Networking, REST API", + url: "https://www.youtube.com/", + viewCount: 423, + time: "2021-09-23 12:00:13", + youtuber: SOPT), + + Video(thumbnailImage: ImageLiterals.Subscribe.Video.thumbnail, + idx: 104, + title: "7차 iOS 세미나 : Animation과 제스쳐, 데이터 전달 심화 ", + url: "https://www.youtube.com/", + viewCount: 423, + time: "2021-09-30 12:00:13", + youtuber: SOPT), + + Video(thumbnailImage: ImageLiterals.Subscribe.Video.thumbnail, + idx: 105, + title: "8차 iOS 세미나 : 8차 세미나 자제휴강하시죠! 엠티가자!", + url: "https://www.youtube.com/", + viewCount: 423, + time: "2021-10-05 12:00:13", + youtuber: SOPT), + ].sorted(by: { $0.idx < $1.idx }) + } + } + + + +} +extension SubscribeDataModel.Video: CustomStringConvertible { + public var description: String { + return "\(youtuber.name) ・ 조회수 \(viewCount)회 ・ \(calculatePastTime(date: time))" + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/YoutuberDataModel.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/YoutuberDataModel.swift new file mode 100644 index 0000000..f210add --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Models/Subscribe/YoutuberDataModel.swift @@ -0,0 +1,29 @@ +// +// YoutuberDataModel.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + + +extension SubscribeDataModel{ + struct Youtuber{ + var thumbnailImage : UIImage + var name : String + var idx : Int + + // 임시용으로 Dummy 데이터 로드함수 제작, 추후에는 네트워크에서 불러와서 처리 + static func loadDummyList() -> [SubscribeDataModel.Youtuber]{ + return [ + Youtuber(thumbnailImage: ImageLiterals.Subscribe.Youtuber.ggamju1, name: "iOSPart", idx: 0), + Youtuber(thumbnailImage: ImageLiterals.Subscribe.Youtuber.ggamju2, name: "AndroidPart", idx: 1), + Youtuber(thumbnailImage: ImageLiterals.Subscribe.Youtuber.ggamju3, name: "ServerPart", idx: 2), + Youtuber(thumbnailImage: ImageLiterals.Subscribe.Youtuber.ggamju4, name: "WebPart", idx: 3), + Youtuber(thumbnailImage: ImageLiterals.Subscribe.Youtuber.ggamju5, name: "DesignPart", idx: 4), + Youtuber(thumbnailImage: ImageLiterals.Subscribe.Youtuber.ggamju6, name: "PlanPart", idx: 5) + ].sorted(by: { $0.idx < $1.idx }) + } + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Protocols/UICollectionViewRegisterable.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Protocols/UICollectionViewRegisterable.swift new file mode 100644 index 0000000..6b082a4 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Protocols/UICollectionViewRegisterable.swift @@ -0,0 +1,27 @@ +// +// UICollectionViewRegisterable.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + + + + +protocol UICollectionViewRegisterable { + static var isFromNib: Bool { get } + static func register(target: UICollectionView) +} + +extension UICollectionViewRegisterable where Self: UICollectionViewCell { + static func register(target: UICollectionView) { + if self.isFromNib { + target.register(UINib(nibName: Self.className, bundle: nil), forCellWithReuseIdentifier: Self.className) + } else { + target.register(Self.self, forCellWithReuseIdentifier: Self.className) + } + } +} + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Protocols/UITableViewRegisterable.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Protocols/UITableViewRegisterable.swift new file mode 100644 index 0000000..f65797f --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Protocols/UITableViewRegisterable.swift @@ -0,0 +1,25 @@ +// +// UITableViewRegistable.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +protocol UITableViewRegisterable { + + static var isFromNib: Bool { get } + static func register(target: UITableView) +} + +extension UITableViewRegisterable where Self: UITableViewCell { + static func register(target: UITableView) { + if self.isFromNib { + target.register(UINib(nibName: Self.className, bundle: nil), forCellReuseIdentifier: Self.className) + } else { + target.register(Self.self, forCellReuseIdentifier: Self.className) + } + } +} + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/Contents.json new file mode 100644 index 0000000..00243bb --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "btn_detail.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "btn_detail@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "btn_detail@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail.png new file mode 100644 index 0000000..ce51690 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail@2x.png new file mode 100644 index 0000000..bd9c953 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail@3x.png new file mode 100644 index 0000000..633709c Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/btn_detail.imageset/btn_detail@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/Contents.json new file mode 100644 index 0000000..5ef9752 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ggamju1.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ggamju1@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ggamju1@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1.png new file mode 100644 index 0000000..5204dfe Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1@2x.png new file mode 100644 index 0000000..f1838ca Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1@3x.png new file mode 100644 index 0000000..3dd18f7 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju1.imageset/ggamju1@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/Contents.json new file mode 100644 index 0000000..7ecc720 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ggamju2.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ggamju2@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ggamju2@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2.png new file mode 100644 index 0000000..e6733b7 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2@2x.png new file mode 100644 index 0000000..9d0301e Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2@3x.png new file mode 100644 index 0000000..4b0b98f Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju2.imageset/ggamju2@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/Contents.json new file mode 100644 index 0000000..68ea549 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ggamju3.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ggamju3@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ggamju3@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3.png new file mode 100644 index 0000000..4603ded Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3@2x.png new file mode 100644 index 0000000..4a7cbb9 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3@3x.png new file mode 100644 index 0000000..88d6268 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju3.imageset/ggamju3@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/Contents.json new file mode 100644 index 0000000..97564f5 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ggamju4.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ggamju4@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ggamju4@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4.png new file mode 100644 index 0000000..b59e8dd Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4@2x.png new file mode 100644 index 0000000..aa68abd Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4@3x.png new file mode 100644 index 0000000..1ce14d0 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju4.imageset/ggamju4@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/Contents.json new file mode 100644 index 0000000..bd6fd4a --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ggamju5.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ggamju5@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ggamju5@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5.png new file mode 100644 index 0000000..b799902 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5@2x.png new file mode 100644 index 0000000..2d5d5e2 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5@3x.png new file mode 100644 index 0000000..06f63c9 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju5.imageset/ggamju5@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/Contents.json new file mode 100644 index 0000000..d2e772b --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ggamju6.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ggamju6@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ggamju6@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6.png new file mode 100644 index 0000000..b86c8f9 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6@2x.png new file mode 100644 index 0000000..2928b57 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6@3x.png new file mode 100644 index 0000000..4934332 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ggamju6.imageset/ggamju6@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/Contents.json new file mode 100644 index 0000000..099863d --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ic_airplay.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ic_airplay@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ic_airplay@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay.png new file mode 100644 index 0000000..1881755 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay@2x.png new file mode 100644 index 0000000..afe0356 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay@3x.png new file mode 100644 index 0000000..79151ea Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_airplay.imageset/ic_airplay@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/Contents.json new file mode 100644 index 0000000..d125d69 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ic_alarm.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ic_alarm@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ic_alarm@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm.png new file mode 100644 index 0000000..712a7b5 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm@2x.png new file mode 100644 index 0000000..bd02607 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm@3x.png new file mode 100644 index 0000000..9ede9f7 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_alarm.imageset/ic_alarm@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/Contents.json new file mode 100644 index 0000000..cb2ee6f --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ic_main_logo.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ic_main_logo@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ic_main_logo@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo.png new file mode 100644 index 0000000..b1d16f2 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo@2x.png new file mode 100644 index 0000000..18f362c Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo@3x.png new file mode 100644 index 0000000..4761c0c Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_main_logo.imageset/ic_main_logo@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/Contents.json new file mode 100644 index 0000000..268eae7 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ic_search.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ic_search@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ic_search@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search.png new file mode 100644 index 0000000..0722e0c Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search@2x.png new file mode 100644 index 0000000..c2fde8e Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search@3x.png new file mode 100644 index 0000000..ccb02c7 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_search.imageset/ic_search@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/Contents.json new file mode 100644 index 0000000..bab8e5f --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "ic_sopt.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "ic_sopt@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "ic_sopt@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt.png new file mode 100644 index 0000000..5417d1f Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt@2x.png new file mode 100644 index 0000000..87a30c7 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt@3x.png new file mode 100644 index 0000000..43edd9f Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/ic_sopt.imageset/ic_sopt@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/Contents.json b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/Contents.json new file mode 100644 index 0000000..098d8d8 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "wesoptiOSPart.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "wesoptiOSPart@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "wesoptiOSPart@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart.png new file mode 100644 index 0000000..d37af8f Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart@2x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart@2x.png new file mode 100644 index 0000000..1867d4b Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart@2x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart@3x.png b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart@3x.png new file mode 100644 index 0000000..537f6d3 Binary files /dev/null and b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Resource/Assets.xcassets/wesoptiOSPart.imageset/wesoptiOSPart@3x.png differ diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/CollectionView/CustomCollectionViewDataSource.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/CollectionView/CustomCollectionViewDataSource.swift new file mode 100644 index 0000000..dae2f30 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/CollectionView/CustomCollectionViewDataSource.swift @@ -0,0 +1,75 @@ +// +// CustomCollectionViewDataSource.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +public struct CollectionViewLayout{ + var itemSize : CGSize + var interItemSpacing : CGFloat + var lineSpacing : CGFloat + var cellInset : UIEdgeInsets +} + +public class CustomCollectionViewListDataSource: NSObject, UICollectionViewDataSource, + UICollectionViewDelegate, + UICollectionViewDelegateFlowLayout{ + let items: [T] + let cellFactory: (T) -> UICollectionViewCell + let sizeFactory: (T) -> CollectionViewLayout + public var onItemSelected: (T,IndexPath) -> Void = { (_,index) in } + + public init(items: [T], + cellSizeFactory : @escaping (T) -> CollectionViewLayout, + cellFactory: @escaping (T) -> UICollectionViewCell) { + self.items = items + self.sizeFactory = cellSizeFactory + self.cellFactory = cellFactory + } + + func item(at indexPath: IndexPath) -> T { + return self.items[indexPath.row] + } + + // MARK: UICollectionViewViewDataSource + + public func numberOfSections(in collectionView: UICollectionView) -> Int { + return 1 + } + + public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return self.items.count + } + + public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + return cellFactory(item(at: indexPath)) + } + + // MARK: UICollectionViewDelegate + + public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + self.onItemSelected(item(at: indexPath), indexPath) + } + + + // MARK: UICollectionViewDelegateFlowLayout + public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + return sizeFactory(item(at: indexPath)).itemSize + } + + public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { + return sizeFactory(item(at: IndexPath(row: 0, section: section))).cellInset + } + + public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { + return sizeFactory(item(at: IndexPath(row: 0, section: section))).interItemSpacing + } + + public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { + return sizeFactory(item(at: IndexPath(row: 0, section: section))).lineSpacing + } +} + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/TableView/CustomTableViewDataSource.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/TableView/CustomTableViewDataSource.swift new file mode 100644 index 0000000..9073a89 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/TableView/CustomTableViewDataSource.swift @@ -0,0 +1,56 @@ +// +// CustomTableViewDelegate.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +public class CustomTableViewListDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { + let items: [T] + let cellFactory: (T) -> UITableViewCell + public var onItemSelected: (T,IndexPath) -> Void = { _,index in } + public var scrollViewDidScroll: (CGPoint) -> Void = { cor in } + public var scrollViewWillBeginScroll: (CGPoint) -> Void = { cor in } + + public init(items: [T], cellFactory: @escaping (T) -> UITableViewCell) { + self.items = items + self.cellFactory = cellFactory + } + + func item(at indexPath: IndexPath) -> T { + return self.items[indexPath.row] + } + + // MARK: UITableViewDataSource + + public func numberOfSections(in tableView: UITableView) -> Int { + return 1 + } + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return self.items.count + } + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + return cellFactory(item(at: indexPath)) + } + + // MARK: UITableViewDelegate + + public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + self.onItemSelected(item(at: indexPath), indexPath) + } + + // MARK: UITableViewDelegate + + + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + self.scrollViewDidScroll(scrollView.contentOffset) + } + + public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + self.scrollViewWillBeginScroll(scrollView.contentOffset) + } + + +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/TableView/CustomTableViewSectionDataSource.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/TableView/CustomTableViewSectionDataSource.swift new file mode 100644 index 0000000..0a4f497 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/UIComponents/TableView/CustomTableViewSectionDataSource.swift @@ -0,0 +1,52 @@ +// +// CustomTableViewSectionDataSource.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +public class CustomTableViewSectionDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { + struct Section { + let title: String + let items: [T] + } + let sections: [Section] + let cellFactory: (T) -> UITableViewCell + public var onItemSelected: (T) -> Void = { _ in } + + public init(items: [T], + categorizer: (T) -> String, + cellFactory: @escaping (T) -> UITableViewCell) { + let groups = Dictionary(grouping: items, by: categorizer) + self.sections = groups.map(Section.init).sorted(by: { $0.title < $1.title }) + self.cellFactory = cellFactory + } + + func item(at indexPath: IndexPath) -> T { + return self.sections[indexPath.section].items[indexPath.row] + } + + // MARK: UITableViewDataSource + + public func numberOfSections(in tableView: UITableView) -> Int { + return self.sections.count + } + public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + return self.sections[section].title + } + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return self.sections[section].items.count + } + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + return cellFactory(item(at: indexPath)) + } + + // MARK: UITableViewDelegate + + public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + self.onItemSelected(item(at: indexPath)) + } +} + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Global/Utils/calculateDate.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Utils/calculateDate.swift new file mode 100644 index 0000000..6eabbec --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Global/Utils/calculateDate.swift @@ -0,0 +1,54 @@ +// +// calculateDate.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import Foundation +public func calculatePastTime(date : String) -> String +{ + + let minute = 60 + let hour = minute * 60 + let day = hour * 60 + let week = day * 7 + + var message : String = "" + + let UTCDate = Date() + let formatter = DateFormatter() + formatter.timeZone = TimeZone(secondsFromGMT: 32400) + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + let defaultTimeZoneStr = formatter.string(from: UTCDate) + + let format = DateFormatter() + format.dateFormat = "yyyy-MM-dd HH:mm:ss" + format.locale = Locale(identifier: "ko_KR") + + guard let tempDate = format.date(from: date) else {return ""} + let krTime = format.date(from: defaultTimeZoneStr) + + let articleDate = format.string(from: tempDate) + var useTime = Int(krTime!.timeIntervalSince(tempDate)) + useTime = useTime - 32400 + + if useTime < minute{ + message = "방금 전" + }else if useTime < hour{ + message = String(useTime/minute) + "분 전" + }else if useTime < day{ + message = String(useTime/hour) + "시간 전" + }else if useTime < week{ + message = String(useTime/day) + "일 전" + }else if useTime < week * 4{ + message = String(useTime/week) + "주 전" + }else{ + let timeArray = articleDate.components(separatedBy: " ") + let dateArray = timeArray[0].components(separatedBy: "-") + message = dateArray[1] + "월 " + dateArray[2] + "일" + } + + + return message +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/CommonViews/Header/MainHeaderView.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/CommonViews/Header/MainHeaderView.swift new file mode 100644 index 0000000..4f434e6 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/CommonViews/Header/MainHeaderView.swift @@ -0,0 +1,34 @@ +// +// MainHeaderView.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +class MainHeaderView : UIView{ + + var delegate : MainHeaderDelegate? + + @IBOutlet var mainIconList: [UIView]! + override init(frame: CGRect) { + super.init(frame: frame) + addSubviewFromNib(view: self) + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + addSubviewFromNib(view: self) + } + + @IBAction func profileButtonClicked(_ sender: Any) { + delegate?.profileButtonClicked() + } +} + + + +protocol MainHeaderDelegate{ + func profileButtonClicked() +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/CommonViews/Header/MainHeaderView.xib b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/CommonViews/Header/MainHeaderView.xib new file mode 100644 index 0000000..d601cdd --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/CommonViews/Header/MainHeaderView.xib @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterCVC.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterCVC.swift new file mode 100644 index 0000000..cbe8f3e --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterCVC.swift @@ -0,0 +1,38 @@ +// +// SubscrbieFilterCVC.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +class SubscribeFilterCVC: UICollectionViewCell,UICollectionViewRegisterable { + static var isFromNib: Bool{ + get{ + return true + } + } + + @IBOutlet weak var filterNameLabel: UILabel! + + override func awakeFromNib() { + super.awakeFromNib() + setLayer() + // Initialization code + } + + private func setLayer(){ + layer.cornerRadius = 16 + } + + func setFilterCell(isClicked : Bool, name : String){ + layer.borderWidth = 1 + filterNameLabel.text = name + backgroundColor = isClicked ? .darkGray : .palerGray + filterNameLabel.textColor = isClicked ? .white : .black + layer.borderColor = isClicked ? UIColor.darkGray.cgColor : UIColor.borderColor.cgColor + } + + +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterCVC.xib b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterCVC.xib new file mode 100644 index 0000000..a15b388 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterCVC.xib @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterContainerView.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterContainerView.swift new file mode 100644 index 0000000..78017e1 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterContainerView.swift @@ -0,0 +1,103 @@ +// +// SubscribeFilterContainerView.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +class SubscribeFilterContainerView: UIView { + + // MARK: - Vars & Lets Part + + var delegate : SubscribeFilterDelegate? + private let filterList = SubscribeDataModel.loadFilterList() + private var currentDataSource: (UICollectionViewDataSource & + UICollectionViewDelegate & + UICollectionViewDelegateFlowLayout)? { + didSet { + self.filterCV.dataSource = currentDataSource + self.filterCV.delegate = currentDataSource + self.filterCV.reloadData() + } + } + private var clickedIdx = 0{ + didSet{ + delegate?.filterChanged(clickedIdx: clickedIdx) + setDataSource() + } + } + + // MARK: - UI Components + + @IBOutlet weak var filterCV: UICollectionView! + + // MARK: - Life Cycle + + override init(frame: CGRect) { + super.init(frame: frame) + addSubviewFromNib(view: self) + setCollectionView() + setDataSource() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + addSubviewFromNib(view: self) + setCollectionView() + setDataSource() + } + + // MARK: - User Function Partsl + + private func setCollectionView(){ + SubscribeFilterCVC.register(target: self.filterCV) + } + + private func setDataSource(){ + let dataSource = CustomCollectionViewListDataSource( + items: filterList, + cellSizeFactory: {[unowned self] in self.makeCellSize(for: $0)}, + cellFactory: {[unowned self] in self.makeCell(for: $0)}) + dataSource.onItemSelected = { (_,indexPath) in + print("Filter Cell Clicked!!",indexPath.row) + self.clickedIdx = indexPath.row + } + self.currentDataSource = dataSource + } + + private func makeCell(for cell : SubscribeDataModel.Filter) -> UICollectionViewCell{ + let filterCell = self.filterCV.dequeueReusableCell(withReuseIdentifier: SubscribeFilterCVC.className, + for: IndexPath(row: 0, section: 0)) as! SubscribeFilterCVC + filterCell.setFilterCell(isClicked: clickedIdx == getFilterIndex(cell.sortCase), + name: cell.sortCase) + return filterCell + } + + private func makeCellSize(for cell : SubscribeDataModel.Filter) -> CollectionViewLayout{ + return CollectionViewLayout(itemSize: CGSize(width: calculateCellWidth(cell.sortCase), height: 32), + interItemSpacing: 9, + lineSpacing: 0, + cellInset: UIEdgeInsets(top: 8, left: 13, bottom: 8, right: 13)) + + } + + private func calculateCellWidth(_ labelName : String) -> CGFloat{ + let label = UILabel() + label.font = .systemFont(ofSize: 14) + label.text = labelName + label.sizeToFit() + return label.frame.size.width + 20 + } + + private func getFilterIndex(_ filterName : String) -> Int{ + guard let idx = filterList.firstIndex(where: { data in data.sortCase == filterName }) else{ return -1 } + return idx + } +} + + +protocol SubscribeFilterDelegate{ + func filterChanged(clickedIdx :Int) +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterContainerView.xib b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterContainerView.xib new file mode 100644 index 0000000..5392196 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Filter/SubscribeFilterContainerView.xib @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Subscribe.storyboard b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Subscribe.storyboard index 2a05d7c..3efb915 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Subscribe.storyboard +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Subscribe.storyboard @@ -5,6 +5,7 @@ + @@ -16,24 +17,80 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/SubscribeVC + UIScrollViewDelegate.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/SubscribeVC + UIScrollViewDelegate.swift new file mode 100644 index 0000000..96e6fd8 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/SubscribeVC + UIScrollViewDelegate.swift @@ -0,0 +1,15 @@ +// +// SubscribeVC + UIScrollViewDelegate.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import Foundation +import UIKit + +extension SubscribeVC : UIScrollViewDelegate{ + func scrollViewDidScroll(_ scrollView: UIScrollView) { + print(scrollView.contentOffset.x) + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/SubscribeVC.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/SubscribeVC.swift index e644ee4..025f43f 100644 --- a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/SubscribeVC.swift +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/SubscribeVC.swift @@ -6,6 +6,8 @@ // import UIKit +import ListPlaceholder +import SkeletonView protocol SubscribeViewControllable : BaseControllable{ @@ -13,12 +15,129 @@ protocol SubscribeViewControllable : BaseControllable{ class SubscribeVC: UIViewController,SubscribeViewControllable { + + // MARK: - Vars & Lets Part + + private var lastPosY :CGFloat = 0 + private let dummyVideoData = SubscribeDataModel.Video.loadDummyList() + private var currentDataSource: (UITableViewDataSource & UITableViewDelegate)? { + didSet { + self.videoTV.dataSource = currentDataSource + self.videoTV.delegate = currentDataSource + self.videoTV.reloadData() + } + } + + + // MARK: - UI Components + @IBOutlet weak var videoTV: UITableView! + @IBOutlet weak var mainNavigationBar: MainHeaderView!{ + didSet{ + mainNavigationBar.delegate = self + } + } + @IBOutlet weak var filterContainerView: SubscribeFilterContainerView!{ + didSet{ + filterContainerView.delegate = self + } + } + + + @IBOutlet weak var navigationBarTopConstraint: NSLayoutConstraint! + @IBOutlet weak var headerCellTopConstraint: NSLayoutConstraint! + // MARK: - Life Cycles + + override func viewDidLoad() { + super.viewDidLoad() + setTableView() + setDataSource() + showLoader() + } - override func viewDidLoad() { - super.viewDidLoad() + + // MARK: - User Functions Part + + //샘플로만 Place Holder 만들어서 넣기 , 실제 통신때 확장하기! + private func showLoader(){ + videoTV.showLoader() + DispatchQueue.main.asyncAfter(deadline: .now() + 2.3) { [weak self] in + self?.videoTV.hideLoader() + } + } + + private func setTableView(){ + videoTV.separatorStyle = .none + videoTV.contentInset = UIEdgeInsets(top: 196, left: 0, bottom: 0, right: 0) + videoTV.refreshControl = UIRefreshControl() + SubscribeVideoTVC.register(target: self.videoTV) + } + + private func setDataSource(){ + let dataSource = CustomTableViewListDataSource( + items: dummyVideoData, + cellFactory: {[unowned self] in self.makeCell(for: $0)}) + dataSource.onItemSelected = { (_,indexPath) in + print("Video Cell Clicked!!",indexPath.row) + } + dataSource.scrollViewDidScroll = { (contentoffSet) in + self.scrollViewDidScroll(posY: contentoffSet.y) + } + dataSource.scrollViewWillBeginScroll = { (contentoffSet) in + self.lastPosY = contentoffSet.y + } + self.currentDataSource = dataSource + } + + private func makeCell(for cell : SubscribeDataModel.Video) -> UITableViewCell{ + guard let videoCell = self.videoTV.dequeueReusableCell(withIdentifier: SubscribeVideoTVC.className) as? SubscribeVideoTVC else {return UITableViewCell()} + videoCell.selectionStyle = .none + videoCell.setData(thumbnail: cell.thumbnailImage, + userIcon: cell.youtuber.thumbnailImage, + title: cell.title, + subtitle: cell.description) + return videoCell + } +} +// MARK: - Extension + +extension SubscribeVC{ + func scrollViewDidScroll(posY : CGFloat){ + print("posY",posY) + self.headerCellTopConstraint.constant = posY >= -196 ? + (posY) * (-1) - 152 : 44 + switch(posY){ + case -500 ... -44: + self.navigationBarTopConstraint.constant = 0 + self.setNavibarItemAlpha(alpha: 1) + case -44 ... 0: + self.navigationBarTopConstraint.constant = (posY) * (-1) - 44 + self.setNavibarItemAlpha(alpha: 1 - (posY + 44) / 44) + default : + self.setNavibarItemAlpha(alpha: 0) + self.navigationBarTopConstraint.constant = -44 } - + } + + func setNavibarItemAlpha(alpha: CGFloat){ + self.mainNavigationBar.mainIconList.forEach { + $0.alpha = alpha + } + } + +} +extension SubscribeVC : SubscribeFilterDelegate{ + func filterChanged(clickedIdx: Int) { + showLoader() + } +} + + +extension SubscribeVC : MainHeaderDelegate{ + func profileButtonClicked() { + + } + } diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Video/SubscribeVideoTVC.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Video/SubscribeVideoTVC.swift new file mode 100644 index 0000000..3ed42df --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Video/SubscribeVideoTVC.swift @@ -0,0 +1,47 @@ +// +// SubscribeVideoTVC.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +class SubscribeVideoTVC: UITableViewCell,UITableViewRegisterable { + static var isFromNib: Bool{ + get { + return true + } + } + + @IBOutlet weak var thumbnailImageView: UIImageView! + @IBOutlet weak var userIconImageView: UIImageView! + @IBOutlet weak var titleLabel: UILabel! + @IBOutlet weak var subtitleLabel: UILabel! + + override func awakeFromNib() { + super.awakeFromNib() + } + + override func prepareForReuse() { + thumbnailImageView.image = UIImage() + userIconImageView.image = UIImage() + titleLabel.text?.removeAll() + subtitleLabel.text?.removeAll() + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + } + + func setData(thumbnail: UIImage, + userIcon : UIImage, + title : String, + subtitle : String){ + thumbnailImageView.image = thumbnail + userIconImageView.image = userIcon + titleLabel.text = title + subtitleLabel.text = subtitle + } + +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Video/SubscribeVideoTVC.xib b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Video/SubscribeVideoTVC.xib new file mode 100644 index 0000000..9fb8f17 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Video/SubscribeVideoTVC.xib @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberCVC.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberCVC.swift new file mode 100644 index 0000000..58348d7 --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberCVC.swift @@ -0,0 +1,34 @@ +// +// SubscribeYoutuberCVC.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +class SubscribeYoutuberCVC: UICollectionViewCell,UICollectionViewRegisterable { + + static var isFromNib : Bool{ + get{ + return true + } + } + + + + + @IBOutlet weak var profileImageView: UIImageView! + @IBOutlet weak var nameLabel: UILabel! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + func setCellData(profileImage : UIImage, name : String){ + profileImageView.image = profileImage + nameLabel.text = name + } + +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberCVC.xib b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberCVC.xib new file mode 100644 index 0000000..bccdcde --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberCVC.xib @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberContainerView.swift b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberContainerView.swift new file mode 100644 index 0000000..822bfdb --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberContainerView.swift @@ -0,0 +1,76 @@ +// +// SubscribeYoutuberContainerView.swift +// sopt_29th_Assignment +// +// Created by 송지훈 on 2021/10/28. +// + +import UIKit + +class SubscribeYoutuberContainerView : UIView{ + + // MARK: - Vars & Lets Part + + private let dummyYoutuberList = SubscribeDataModel.Youtuber.loadDummyList() + private var currentDataSource: (UICollectionViewDataSource & + UICollectionViewDelegate & + UICollectionViewDelegateFlowLayout)? { + didSet { + self.YoutuberCV.dataSource = currentDataSource + self.YoutuberCV.delegate = currentDataSource + self.YoutuberCV.reloadData() + } + } + + // MARK: - UI Components + + @IBOutlet weak var YoutuberCV: UICollectionView! + + // MARK: - Life Cycle + + override init(frame: CGRect) { + super.init(frame: frame) + addSubviewFromNib(view: self) + setCollectionView() + setDataSource() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + addSubviewFromNib(view: self) + setCollectionView() + setDataSource() + } + + // MARK: - User Function Partsl + + private func setCollectionView(){ + SubscribeYoutuberCVC.register(target: self.YoutuberCV) + } + + private func setDataSource(){ + let dataSource = CustomCollectionViewListDataSource( + items: dummyYoutuberList, + cellSizeFactory: {[unowned self] in self.makeCellSize(for: $0)}, + cellFactory: {[unowned self] in self.makeCell(for: $0)}) + dataSource.onItemSelected = { (_,indexPath) in + print("Youtuber Cell Clicked!!",indexPath.row) + } + self.currentDataSource = dataSource + } + + private func makeCell(for cell : SubscribeDataModel.Youtuber) -> UICollectionViewCell{ + let youtuberCell = self.YoutuberCV.dequeueReusableCell(withReuseIdentifier: SubscribeYoutuberCVC.className, + for: IndexPath(row: 0, section: 0)) as! SubscribeYoutuberCVC + youtuberCell.setCellData(profileImage: cell.thumbnailImage, + name: cell.name) + return youtuberCell + } + + private func makeCellSize(for cell : SubscribeDataModel.Youtuber) -> CollectionViewLayout{ + return CollectionViewLayout(itemSize: CGSize(width: 72, height: 104), + interItemSpacing: .zero, + lineSpacing: .zero, + cellInset: .zero) + } +} diff --git a/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberContainerView.xib b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberContainerView.xib new file mode 100644 index 0000000..d50f1ea --- /dev/null +++ b/sopt_29th_Assignment/sopt_29th_Assignment/Screens/Subscribe/Youtuber/SubscribeYoutuberContainerView.xib @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +