diff --git a/Statistics/Podfile b/Statistics/Podfile new file mode 100644 index 0000000..1c6ca3c --- /dev/null +++ b/Statistics/Podfile @@ -0,0 +1,13 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'Statistics' do + # Comment the next line if you're not using Swift and don't want to use dynamic frameworks + use_frameworks! + + # Pods for Statistics + + pod 'Alamofire', '~> 4.5' + pod 'PNChart' + +end diff --git a/Statistics/Podfile.lock b/Statistics/Podfile.lock new file mode 100644 index 0000000..3280ff7 --- /dev/null +++ b/Statistics/Podfile.lock @@ -0,0 +1,18 @@ +PODS: + - Alamofire (4.6.0) + - PNChart (0.8.9): + - UICountingLabel (~> 1.2.0) + - UICountingLabel (1.2.0) + +DEPENDENCIES: + - Alamofire (~> 4.5) + - PNChart + +SPEC CHECKSUMS: + Alamofire: f41a599bd63041760b26d393ec1069d9d7b917f4 + PNChart: 84774d225c2126ded6c93d4dbe6ae98c3a73c2d2 + UICountingLabel: 1db4e7d023e1762171eb226d6dff47a7a84f27aa + +PODFILE CHECKSUM: 208f4b353aba8b81671f1a706d4bade9ed36416b + +COCOAPODS: 1.2.1 diff --git a/Statistics/Pods/Alamofire/LICENSE b/Statistics/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..1654602 --- /dev/null +++ b/Statistics/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2017 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/Statistics/Pods/Alamofire/README.md b/Statistics/Pods/Alamofire/README.md new file mode 100644 index 0000000..eb5a522 --- /dev/null +++ b/Statistics/Pods/Alamofire/README.md @@ -0,0 +1,236 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](https://alamofire.github.io/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +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](Documentation/Usage.md) + - **Intro -** [Making a Request](Documentation/Usage.md#making-a-request), [Response Handling](Documentation/Usage.md#response-handling), [Response Validation](Documentation/Usage.md#response-validation), [Response Caching](Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](Documentation/Usage.md#http-methods), [Parameter Encoding](Documentation/Usage.md#parameter-encoding), [HTTP Headers](Documentation/Usage.md#http-headers), [Authentication](Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](Documentation/Usage.md#statistical-metrics), [cURL Command Output](Documentation/Usage.md#curl-command-output) +- [Advanced Usage](Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](Documentation/AdvancedUsage.md#session-manager), [Session Delegate](Documentation/AdvancedUsage.md#session-delegate), [Request](Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](Documentation/AdvancedUsage.md#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](Documentation/AdvancedUsage.md#custom-response-serialization) + - **Connection -** [Security](Documentation/AdvancedUsage.md#security), [Network Reachability](Documentation/AdvancedUsage.md#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.3+ +- Swift 3.1+ + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1+ is required to build Alamofire 4.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.5' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 4.5 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +#### Swift 3 + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +#### Swift 4 + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0") +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage (Resolved on 9/1/17 in Xcode 9 beta 6). + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +- Pay our legal fees to register as a federal non-profit organization +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Statistics/Pods/Alamofire/Source/AFError.swift b/Statistics/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..585ae14 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/Statistics/Pods/Alamofire/Source/Alamofire.swift b/Statistics/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..e971613 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherwise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/Statistics/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Statistics/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..9031395 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/Statistics/Pods/Alamofire/Source/MultipartFormData.swift b/Statistics/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..ba02d24 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,580 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(macOS) +import CoreServices +#endif + +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let crlf = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + let boundaryText: String + + switch boundaryType { + case .initial: + boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" + } + + return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates a multipart form data object. + /// + /// - returns: The multipart form data object. + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /// + /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + /// information, please refer to the following article: + /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + /// + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + public func append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter headers: The HTTP headers for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// It is important to note that this method will load all the appended body parts into memory all at the same + /// time. This method should only be used when the encoded data will have a small memory footprint. For large data + /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + /// + /// - throws: An `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes the appended body parts into the given file URL. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - parameter fileURL: The file URL to write the multipart form data into. + /// + /// - throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/Statistics/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Statistics/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..cdb5a02 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,233 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +public class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + public enum NetworkReachabilityStatus { + case unknown + case notReachable + case reachable(ConnectionType) + } + + /// Defines the various connection types detected by reachability flags. + /// + /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. + /// - wwan: The connection type is a WWAN connection. + public enum ConnectionType { + case ethernetOrWiFi + case wwan + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard isNetworkReachable(with: flags) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } + + func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { + let isReachable = flags.contains(.reachable) + let needsConnection = flags.contains(.connectionRequired) + let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) + let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + + return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/Statistics/Pods/Alamofire/Source/Notifications.swift b/Statistics/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..df41505 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,52 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + } +} diff --git a/Statistics/Pods/Alamofire/Source/ParameterEncoding.swift b/Statistics/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..dabb562 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,432 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// HTTP method definitions. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode +/// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending +/// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent) { + self.destination = destination + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + /// + /// - parameter key: The key of the query component. + /// - parameter value: The value of the query component. + /// + /// - returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: "\(key)[]", value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape((value.boolValue ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape((bool ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /// Returns a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + /// + /// - parameter string: The string to be percent-escaped. + /// + /// - returns: The percent-escaped string. + public func escape(_ string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the +/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header +/// field of an encoded request is set to `application/x-plist`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/Statistics/Pods/Alamofire/Source/Request.swift b/Statistics/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..d93c52d --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,653 @@ +// +// Request.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + open let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as + /// well as the response status code if a response has been received. + open var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.httpMethod { + components.append(HTTPMethod) + } + + if let urlString = request?.url?.absoluteString { + components.append(urlString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -v"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential = delegate.credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if session.configuration.httpShouldSetCookies { + if + let cookieStorage = session.configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + + #if swift(>=3.2) + components.append("-b \"\(string[.. URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + /// + /// This closure returns the bytes most recently received from the server, not including data from previous calls. + /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + /// also important to note that the server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download request has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - parameter directory: The search path directory. `.DocumentDirectory` by default. + /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. + /// + /// - returns: A download file destination closure. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/Statistics/Pods/Alamofire/Source/Response.swift b/Statistics/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..814662c --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,567 @@ +// +// Response.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to store all data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter data: The data returned by the server. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/Statistics/Pods/Alamofire/Source/ResponseSerialization.swift b/Statistics/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..1f29ed8 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,715 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: requestStartTime, + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type initialized from the response data with the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/Statistics/Pods/Alamofire/Source/Result.swift b/Statistics/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000..bbd3c61 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,300 @@ +// +// Result.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to represent whether a request was successful or encountered an error. +/// +/// - success: The request and all post processing operations were successful resulting in the serialization of the +/// provided associated value. +/// +/// - failure: The request encountered an error resulting in a failure. The associated values are the original data +/// provided by the server as well as the error that caused the failure. +public enum Result { + case success(Value) + case failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .success: + return true + case .failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .success(let value): + return value + case .failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .success: + return nil + case .failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .success: + return "SUCCESS" + case .failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .success(let value): + return "SUCCESS: \(value)" + case .failure(let error): + return "FAILURE: \(error)" + } + } +} + +// MARK: - Functional APIs + +extension Result { + /// Creates a `Result` instance from the result of a closure. + /// + /// A failure result is created when the closure throws, and a success result is created when the closure + /// succeeds without throwing an error. + /// + /// func someString() throws -> String { ... } + /// + /// let result = Result(value: { + /// return try someString() + /// }) + /// + /// // The type of result is Result + /// + /// The trailing closure syntax is also supported: + /// + /// let result = Result { try someString() } + /// + /// - parameter value: The closure to execute and create the result for. + public init(value: () throws -> Value) { + do { + self = try .success(value()) + } catch { + self = .failure(error) + } + } + + /// Returns the success value, or throws the failure error. + /// + /// let possibleString: Result = .success("success") + /// try print(possibleString.unwrap()) + /// // Prints "success" + /// + /// let noString: Result = .failure(error) + /// try print(noString.unwrap()) + /// // Throws error + public func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: Result = .success(Data()) + /// let possibleInt = possibleData.map { $0.count } + /// try print(possibleInt.unwrap()) + /// // Prints "0" + /// + /// let noData: Result = .failure(error) + /// let noInt = noData.map { $0.count } + /// try print(noInt.unwrap()) + /// // Throws error + /// + /// - parameter transform: A closure that takes the success value of the `Result` instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func map(_ transform: (Value) -> T) -> Result { + switch self { + case .success(let value): + return .success(transform(value)) + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func flatMap(_ transform: (Value) throws -> T) -> Result { + switch self { + case .success(let value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: Result = .failure(someError) + /// let withMyError: Result = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func mapError(_ transform: (Error) -> T) -> Result { + switch self { + case .failure(let error): + return .failure(transform(error)) + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func flatMapError(_ transform: (Error) throws -> T) -> Result { + switch self { + case .failure(let error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withValue(_ closure: (Value) -> Void) -> Result { + if case let .success(value) = self { closure(value) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withError(_ closure: (Error) -> Void) -> Result { + if case let .failure(error) = self { closure(error) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a success. + /// + /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifSuccess(_ closure: () -> Void) -> Result { + if isSuccess { closure() } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure. + /// + /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifFailure(_ closure: () -> Void) -> Result { + if isFailure { closure() } + + return self + } +} diff --git a/Statistics/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Statistics/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000..1ad3530 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +open class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + open let policies: [String: ServerTrustPolicy] + + /// Initializes the `ServerTrustPolicyManager` instance with the given policies. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - parameter policies: A dictionary of all policies mapped to a particular host. + /// + /// - returns: The new `ServerTrustPolicyManager` instance. + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /// Returns the `ServerTrustPolicy` for the given host if applicable. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - parameter host: The host to use when searching for a matching policy. + /// + /// - returns: The server trust policy for the given host if found. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when +/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust +/// with a given set of criteria to determine whether the server trust is valid and the connection should be made. +/// +/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other +/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged +/// to route all communication over an HTTPS connection with pinning enabled. +/// +/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to +/// validate the host provided by the challenge. Applications are encouraged to always +/// validate the host in production environments to guarantee the validity of the server's +/// certificate chain. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. Applications are encouraged to always validate the host +/// in production environments to guarantee the validity of the server's certificate chain. +/// +/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is +/// considered valid if one of the pinned certificates match one of the server certificates. +/// By validating both the certificate chain and host, certificate pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered +/// valid if one of the pinned public keys match one of the server certificate public keys. +/// By validating both the certificate chain and host, public key pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. +public enum ServerTrustPolicy { + case performDefaultEvaluation(validateHost: Bool) + case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case disableEvaluation + case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) + + // MARK: - Bundle Location + + /// Returns all certificates within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `.cer` files. + /// + /// - returns: All certificates within the given bundle. + public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /// Returns all public keys within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `*.cer` files. + /// + /// - returns: All public keys within the given bundle. + public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /// Evaluates whether the server trust is valid for the given host. + /// + /// - parameter serverTrust: The server trust to evaluate. + /// - parameter host: The host of the challenge protection space. + /// + /// - returns: Whether the server trust is valid. + public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .performDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == pinnedCertificateData { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .disableEvaluation: + serverTrustIsValid = true + case let .customEvaluation(closure): + serverTrustIsValid = closure(serverTrust, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/Statistics/Pods/Alamofire/Source/SessionDelegate.swift b/Statistics/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..d38c253 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,719 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + private var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// Tells the delegate that the session has been invalidated. + /// + /// - parameter session: The session object that was invalidated. + /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /// Requests credentials from the delegate in response to a session-level authentication request from the + /// remote server. + /// + /// - parameter session: The session containing the task that requested authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Tells the delegate that the remote server requested an HTTP redirect. + /// + /// - parameter session: The session containing the task whose request resulted in a redirect. + /// - parameter task: The task whose request resulted in a redirect. + /// - parameter response: An object containing the server’s response to the original request. + /// - parameter request: A URL request object filled out with the new location. + /// - parameter completionHandler: A closure that your handler should call with either the value of the request + /// parameter, a modified URL request object, or NULL to refuse the redirect and + /// return the body of the redirect response. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /// Requests credentials from the delegate in response to an authentication request from the remote server. + /// + /// - parameter session: The session containing the task whose request requires authentication. + /// - parameter task: The task whose request requires authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task]?.delegate { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: challenge, completionHandler: completionHandler) + } + } + + /// Tells the delegate when a task requires a new request body stream to send to the remote server. + /// + /// - parameter session: The session containing the task that needs a new body stream. + /// - parameter task: The task that needs a new body stream. + /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task]?.delegate { + delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /// Periodically informs the delegate of the progress of sending body content to the server. + /// + /// - parameter session: The session containing the data task. + /// - parameter task: The data task. + /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + /// - parameter totalBytesSent: The total number of bytes sent so far. + /// - parameter totalBytesExpectedToSend: The expected length of the body data. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// Tells the delegate that the task finished transferring data. + /// + /// - parameter session: The session containing the task whose request finished transferring data. + /// - parameter task: The task whose request finished transferring data. + /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + strongSelf.taskDidComplete?(session, task, error) + + strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: [Notification.Key.Task: task] + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if request.delegate.error != nil { + error = request.delegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// Tells the delegate that the data task received the initial reply (headers) from the server. + /// + /// - parameter session: The session containing the data task that received an initial reply. + /// - parameter dataTask: The data task that received an initial reply. + /// - parameter response: A URL response object populated with headers. + /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + /// constant to indicate whether the transfer should continue as a data task or + /// should become a download task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /// Tells the delegate that the data task was changed to a download task. + /// + /// - parameter session: The session containing the task that was replaced by a download task. + /// - parameter dataTask: The data task that was replaced by a download task. + /// - parameter downloadTask: The new download task that replaced the data task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// Tells the delegate that the data task has received some of the expected data. + /// + /// - parameter session: The session containing the data task that provided data. + /// - parameter dataTask: The data task that provided data. + /// - parameter data: A data object containing the transferred data. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: data) + } + } + + /// Asks the delegate whether the data (or upload) task should store the response in the cache. + /// + /// - parameter session: The session containing the data (or upload) task. + /// - parameter dataTask: The data (or upload) task. + /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + /// caching policy and the values of certain received headers, such as the Pragma + /// and Cache-Control headers. + /// - parameter completionHandler: A block that your handler must call, providing either the original proposed + /// response, a modified version of that response, or NULL to prevent caching the + /// response. If your delegate implements this method, it must call this completion + /// handler; otherwise, your app leaks memory. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// Tells the delegate that a download task has finished downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that finished. + /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + /// open the file for reading or move it to a permanent location in your app’s sandbox + /// container directory before returning from this delegate method. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + } + } + + /// Periodically informs the delegate about the download’s progress. + /// + /// - parameter session: The session containing the download task. + /// - parameter downloadTask: The download task. + /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate + /// method was called. + /// - parameter totalBytesWritten: The total number of bytes transferred so far. + /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + /// header. If this header was not provided, the value is + /// `NSURLSessionTransferSizeUnknown`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /// Tells the delegate that the download task has resumed downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. + /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + /// existing content, then this value is zero. Otherwise, this value is an + /// integer representing the number of bytes on disk that do not need to be + /// retrieved again. + /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /// Tells the delegate that the write side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /// Tells the delegate that the system has determined that a better route to the host is available. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + /// - parameter inputStream: The new input stream. + /// - parameter outputStream: The new output stream. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/Statistics/Pods/Alamofire/Source/SessionManager.swift b/Statistics/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000..0ff677b --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,892 @@ +// +// SessionManager.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +open class SessionManager { + + // MARK: - Helper Types + + /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + /// associated values. + /// + /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with + /// streaming information. + /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + /// error. + public enum MultipartFormDataEncodingResult { + case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + open static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + open static let defaultHTTPHeaders: HTTPHeaders = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + open let session: URLSession + + /// The session delegate handling all the task and session delegate callbacks. + open let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// The background completion handler closure provided by the UIApplicationDelegate + /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + /// will automatically call the handler. + /// + /// If you need to handle your own events before the handler is called, then you need to override the + /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + /// + /// `nil` by default. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` by default. + /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + /// default. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter session: The URL session. + /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) + } catch { + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + DispatchQueue.main.async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/Statistics/Pods/Alamofire/Source/TaskDelegate.swift b/Statistics/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000..0607758 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,466 @@ +// +// TaskDelegate.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as +/// executing all operations attached to the serial operation queue upon task completion. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + open let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + set { + taskLock.lock(); defer { taskLock.unlock() } + _task = newValue + } + get { + taskLock.lock(); defer { taskLock.unlock() } + return _task + } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + private var _task: URLSessionTask? { + didSet { reset() } + } + + private let taskLock = NSLock() + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + _task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/Statistics/Pods/Alamofire/Source/Timeline.swift b/Statistics/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000..c5dabd1 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/Statistics/Pods/Alamofire/Source/Validation.swift b/Statistics/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..989ac20 --- /dev/null +++ b/Statistics/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,315 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether validation was successful or encountered an error resulting in a failure. + /// + /// - success: The validation was successful. + /// - failure: The validation failed encountering the provided error. + public enum ValidationResult { + case success + case failure(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + + #if swift(>=3.2) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + #else + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + #endif + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/Statistics/Pods/Manifest.lock b/Statistics/Pods/Manifest.lock new file mode 100644 index 0000000..3280ff7 --- /dev/null +++ b/Statistics/Pods/Manifest.lock @@ -0,0 +1,18 @@ +PODS: + - Alamofire (4.6.0) + - PNChart (0.8.9): + - UICountingLabel (~> 1.2.0) + - UICountingLabel (1.2.0) + +DEPENDENCIES: + - Alamofire (~> 4.5) + - PNChart + +SPEC CHECKSUMS: + Alamofire: f41a599bd63041760b26d393ec1069d9d7b917f4 + PNChart: 84774d225c2126ded6c93d4dbe6ae98c3a73c2d2 + UICountingLabel: 1db4e7d023e1762171eb226d6dff47a7a84f27aa + +PODFILE CHECKSUM: 208f4b353aba8b81671f1a706d4bade9ed36416b + +COCOAPODS: 1.2.1 diff --git a/Statistics/Pods/PNChart/LICENSE b/Statistics/Pods/PNChart/LICENSE new file mode 100644 index 0000000..4d5f9c6 --- /dev/null +++ b/Statistics/Pods/PNChart/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Kevin + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION 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/Statistics/Pods/PNChart/PNChart/PNBar.h b/Statistics/Pods/PNChart/PNChart/PNBar.h new file mode 100755 index 0000000..68e6b0b --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNBar.h @@ -0,0 +1,37 @@ +// +// PNBar.h +// PNChartDemo +// +// Created by kevin on 11/7/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import +#import + +@interface PNBar : UIView + + +- (void)rollBack; + +@property (nonatomic) float grade; +@property (nonatomic) float maxDivisor; + +@property (nonatomic) CAShapeLayer *chartLine; +@property (nonatomic) UIColor *barColor; +@property (nonatomic) UIColor *barColorGradientStart; +@property (nonatomic) CGFloat barRadius; +@property (nonatomic) CAShapeLayer *gradientMask; + +@property (nonatomic) CAShapeLayer *gradeLayer; +@property (nonatomic) CATextLayer* textLayer; + +/** Text color for all bars in the chart. */ +@property (nonatomic) UIColor * labelTextColor; + +@property (nonatomic, assign) BOOL isNegative; //!< 是否是负数 +@property (nonatomic, assign) BOOL isShowNumber; //!< 是否显示numbers + +/** Display the bar with or without animation. Default is YES. **/ +@property (nonatomic) BOOL displayAnimated; +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNBar.m b/Statistics/Pods/PNChart/PNChart/PNBar.m new file mode 100755 index 0000000..8ea5fc9 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNBar.m @@ -0,0 +1,288 @@ +// +// PNBar.m +// PNChartDemo +// +// Created by kevin on 11/7/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import "PNBar.h" +#import "PNColor.h" +#import + +@interface PNBar () + +@property (nonatomic) float copyGrade; + +@end + +@implementation PNBar + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + + if (self) { + _chartLine = [CAShapeLayer layer]; + _chartLine.lineCap = kCALineCapButt; + _chartLine.fillColor = [[UIColor whiteColor] CGColor]; + _chartLine.lineWidth = self.frame.size.width; + _chartLine.strokeEnd = 0.0; + self.clipsToBounds = YES; + [self.layer addSublayer:_chartLine]; + self.barRadius = 2.0; + } + + return self; +} + +-(void)setBarRadius:(CGFloat)barRadius +{ + _barRadius = barRadius; + self.layer.cornerRadius = _barRadius; +} + + +- (void)setGrade:(float)grade +{ + _copyGrade = grade; + CGFloat startPosY = (1 - grade) * self.frame.size.height; + + UIBezierPath *progressline = [UIBezierPath bezierPath]; + + [progressline moveToPoint:CGPointMake(self.frame.size.width / 2.0, self.frame.size.height)]; + [progressline addLineToPoint:CGPointMake(self.frame.size.width / 2.0, startPosY)]; + + [progressline setLineWidth:1.0]; + [progressline setLineCapStyle:kCGLineCapSquare]; + [self addAnimationIfNeededWithProgressLine:progressline]; + + + if (_barColor) { + _chartLine.strokeColor = [_barColor CGColor]; + } + else { + _chartLine.strokeColor = [PNGreen CGColor]; + } + + if (_grade) { + + _chartLine.path = progressline.CGPath; + + if (_barColorGradientStart) { + + // Add gradient + self.gradientMask.path = progressline.CGPath; + + CABasicAnimation* opacityAnimation = [self fadeAnimation]; + [self.textLayer addAnimation:opacityAnimation forKey:nil]; + + } + + }else{ + _chartLine.strokeEnd = 1.0; + + _chartLine.path = progressline.CGPath; + // Check if user wants to add a gradient from the start color to the bar color + if (_barColorGradientStart) { + + // Add gradient + self.gradientMask = [CAShapeLayer layer]; + self.gradientMask.fillColor = [[UIColor clearColor] CGColor]; + self.gradientMask.strokeColor = [[UIColor blackColor] CGColor]; + self.gradientMask.lineWidth = self.frame.size.width; + self.gradientMask.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height); + self.gradientMask.path = progressline.CGPath; + + CAGradientLayer *gradientLayer = [CAGradientLayer layer]; + gradientLayer.startPoint = CGPointMake(0.0,0.0); + gradientLayer.endPoint = CGPointMake(1.0 ,0.0); + gradientLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height); + UIColor *middleColor = [UIColor colorWithWhite:255/255 alpha:0.8]; + NSArray *colors = @[ + (__bridge id)self.barColor.CGColor, + (__bridge id)middleColor.CGColor, + (__bridge id)self.barColor.CGColor + ]; + gradientLayer.colors = colors; + + [gradientLayer setMask:self.gradientMask]; + + [_chartLine addSublayer:gradientLayer]; + + self.gradientMask.strokeEnd = 1.0; + + CABasicAnimation* opacityAnimation = [self fadeAnimation]; + [self.textLayer addAnimation:opacityAnimation forKey:nil]; + } + } + + _grade = grade; + +} + + +- (void)rollBack +{ + [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations: ^{ + _chartLine.strokeColor = [UIColor clearColor].CGColor; + } completion:nil]; +} + +- (void)setBarColorGradientStart:(UIColor *)barColorGradientStart +{ + // Set gradient color, remove any existing sublayer first + for (CALayer *sublayer in [_chartLine sublayers]) { + [sublayer removeFromSuperlayer]; + } + _barColorGradientStart = barColorGradientStart; + + [self setGrade:_grade]; + +} + +// Only override drawRect: if you perform custom drawing. +// An empty implementation adversely affects performance during animation. +- (void)drawRect:(CGRect)rect +{ + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor); + CGContextFillRect(context, rect); +} + + +// add number display on the top of bar +-(CGPathRef)gradePath:(CGRect)rect +{ + return nil; +} + +-(CATextLayer*)textLayer +{ + if (!_textLayer) { + _textLayer = [[CATextLayer alloc]init]; + [_textLayer setString:@"0"]; + [_textLayer setAlignmentMode:kCAAlignmentCenter]; + [_textLayer setForegroundColor:[_labelTextColor CGColor]]; + _textLayer.hidden = YES; + + } + + return _textLayer; +} + +- (void) setLabelTextColor:(UIColor *)labelTextColor { + _labelTextColor = labelTextColor; + [_textLayer setForegroundColor:[_labelTextColor CGColor]]; +} + +-(void)setGradeFrame:(CGFloat)grade startPosY:(CGFloat)startPosY +{ + CGFloat textheigt = self.bounds.size.height*self.grade; + + CGFloat topSpace = self.bounds.size.height * (1-self.grade); + CGFloat textWidth = self.bounds.size.width; + + [_chartLine addSublayer:self.textLayer]; + [self.textLayer setFontSize:18.0]; + + [self.textLayer setString:[[NSString alloc]initWithFormat:@"%0.f",grade*self.maxDivisor]]; + + CGSize size = CGSizeMake(320,2000); //设置一个行高上限 + NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:18.0]}; + size = [self.textLayer.string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size; + float verticalY ; + + if (size.height>=textheigt) { + + verticalY = topSpace - size.height; + } else { + verticalY = topSpace + (textheigt-size.height)/2.0; + } + + [self.textLayer setFrame:CGRectMake((textWidth-size.width)/2.0,verticalY, size.width,size.height)]; + self.textLayer.contentsScale = [UIScreen mainScreen].scale; + +} + +- (void)setIsShowNumber:(BOOL)isShowNumber{ + if (isShowNumber) { + self.textLayer.hidden = NO; + [self setGradeFrame:_copyGrade startPosY:0]; + }else{ + self.textLayer.hidden = YES; + } +} +- (void)setIsNegative:(BOOL)isNegative{ + if (isNegative) { + [self.textLayer setString:[[NSString alloc]initWithFormat:@"- %1.f",_grade*self.maxDivisor]]; + + CGSize size = CGSizeMake(320,2000); //设置一个行高上限 + NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:18.0]}; + size = [self.textLayer.string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size; + CGRect frame = self.textLayer.frame; + frame.origin.x = (self.bounds.size.width - size.width)/2.0; + frame.size = size; + self.textLayer.frame = frame; + + [self addRotationAnimationIfNeeded]; + } +} + +-(CABasicAnimation*)fadeAnimation +{ + CABasicAnimation* fadeAnimation = nil; + if (self.displayAnimated) { + fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; + fadeAnimation.fromValue = [NSNumber numberWithFloat:0.0]; + fadeAnimation.toValue = [NSNumber numberWithFloat:1.0]; + fadeAnimation.duration = 2.0; + } + return fadeAnimation; +} + +-(void)addAnimationIfNeededWithProgressLine:(UIBezierPath *)progressline +{ + if (self.displayAnimated) { + CABasicAnimation *pathAnimation = nil; + + if (_grade) { + pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"]; + pathAnimation.fromValue = (id)_chartLine.path; + pathAnimation.toValue = (id)[progressline CGPath]; + pathAnimation.duration = 0.5f; + pathAnimation.autoreverses = NO; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + [_chartLine addAnimation:pathAnimation forKey:@"animationKey"]; + } + else { + pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + pathAnimation.duration = 1.0; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + pathAnimation.fromValue = @0.0f; + pathAnimation.toValue = @1.0f; + [_chartLine addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; + } + + [self.gradientMask addAnimation:pathAnimation forKey:@"animationKey"]; + } +} + +- (void)addRotationAnimationIfNeeded +{ + if (self.displayAnimated) { + CABasicAnimation* rotationAnimation; + rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; + rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI]; + [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + rotationAnimation.duration = 0.1; + rotationAnimation.repeatCount = 0;//你可以设置到最大的整数值 + rotationAnimation.cumulative = NO; + rotationAnimation.removedOnCompletion = NO; + rotationAnimation.fillMode = kCAFillModeForwards; + [self.textLayer addAnimation:rotationAnimation forKey:@"Rotation"]; + } +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNBarChart.h b/Statistics/Pods/PNChart/PNChart/PNBarChart.h new file mode 100755 index 0000000..e628c08 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNBarChart.h @@ -0,0 +1,123 @@ +// +// PNBarChart.h +// PNChartDemo +// +// Created by kevin on 11/7/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import +#import "PNGenericChart.h" +#import "PNChartDelegate.h" +#import "PNBar.h" + +#define kXLabelMargin 15 +#define kYLabelMargin 15 +#define kYLabelHeight 11 +#define kXLabelHeight 20 + +typedef NSString *(^PNYLabelFormatter)(CGFloat yLabelValue); + +@interface PNBarChart : PNGenericChart + +/** + * Draws the chart in an animated fashion. + */ +- (void)strokeChart; + +@property (nonatomic) NSArray *xLabels; +@property (nonatomic) NSArray *yLabels; +@property (nonatomic) NSArray *yValues; + +@property (nonatomic) NSMutableArray * bars; + +@property (nonatomic) CGFloat xLabelWidth; +@property (nonatomic) float yValueMax; +@property (nonatomic) UIColor *strokeColor; +@property (nonatomic) NSArray *strokeColors; + + +/** Update Values. */ +- (void)updateChartData:(NSArray *)data; + +/** Changes chart margin. */ +@property (nonatomic) CGFloat yChartLabelWidth; + +/** Formats the ylabel text. */ +@property (copy) PNYLabelFormatter yLabelFormatter; + +/** Prefix to y label values, none if unset. */ +@property (nonatomic) NSString *yLabelPrefix; + +/** Suffix to y label values, none if unset. */ +@property (nonatomic) NSString *yLabelSuffix; + +@property (nonatomic) CGFloat chartMarginLeft; +@property (nonatomic) CGFloat chartMarginRight; +@property (nonatomic) CGFloat chartMarginTop; +@property (nonatomic) CGFloat chartMarginBottom; + +/** Controls whether labels should be displayed. */ +@property (nonatomic) BOOL showLabel; + +/** Controls whether the chart border line should be displayed. */ +@property (nonatomic) BOOL showChartBorder; + +@property (nonatomic) UIColor *chartBorderColor; + +/** Controls whether the chart Horizontal separator should be displayed. */ +@property (nonatomic, assign) BOOL showLevelLine; + +/** Chart bottom border, co-linear with the x-axis. */ +@property (nonatomic) CAShapeLayer * chartBottomLine; + +/** Chart bottom border, level separator-linear with the x-axis. */ +@property (nonatomic) CAShapeLayer * chartLevelLine; + +/** Chart left border, co-linear with the y-axis. */ +@property (nonatomic) CAShapeLayer * chartLeftLine; + +/** Corner radius for all bars in the chart. */ +@property (nonatomic) CGFloat barRadius; + +/** Width of all bars in the chart. */ +@property (nonatomic) CGFloat barWidth; + +@property (nonatomic) CGFloat labelMarginTop; + +/** Background color of all bars in the chart. */ +@property (nonatomic) UIColor * barBackgroundColor; + +/** Text color for all bars in the chart. */ +@property (nonatomic) UIColor * labelTextColor; + +/** Font for all bars in the chart. */ +@property (nonatomic) UIFont * labelFont; + +/** How many labels on the x-axis to skip in between displaying labels. */ +@property (nonatomic) NSInteger xLabelSkip; + +/** How many labels on the y-axis to skip in between displaying labels. */ +@property (nonatomic) NSInteger yLabelSum; + +/** The maximum for the range of values to display on the y-axis. */ +@property (nonatomic) CGFloat yMaxValue; + +/** The minimum for the range of values to display on the y-axis. */ +@property (nonatomic) CGFloat yMinValue; + +/** Controls whether each bar should have a gradient fill. */ +@property (nonatomic) UIColor *barColorGradientStart; + +/** Controls whether text for x-axis be straight or rotate 45 degree. */ +@property (nonatomic) BOOL rotateForXAxisText; + +@property (nonatomic, weak) id delegate; + +/**whether show gradient bar*/ +@property (nonatomic, assign) BOOL isGradientShow; + +/** whether show numbers*/ +@property (nonatomic, assign) BOOL isShowNumbers; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNBarChart.m b/Statistics/Pods/PNChart/PNChart/PNBarChart.m new file mode 100755 index 0000000..e2c7c6f --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNBarChart.m @@ -0,0 +1,459 @@ +// +// PNBarChart.m +// PNChartDemo +// +// Created by kevin on 11/7/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import "PNBarChart.h" +#import "PNColor.h" +#import "PNChartLabel.h" + +@interface PNBarChart () { + NSMutableArray *_xChartLabels; + NSMutableArray *_yChartLabels; +} + +- (UIColor *)barColorAtIndex:(NSUInteger)index; + +@end + +@implementation PNBarChart + +- (id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + + if (self) { + [self setupDefaultValues]; + } + return self; +} + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + + if (self) { + [self setupDefaultValues]; + } + + return self; +} + +- (void)setupDefaultValues +{ + [super setupDefaultValues]; + self.backgroundColor = [UIColor whiteColor]; + self.clipsToBounds = YES; + _showLabel = YES; + _barBackgroundColor = PNLightGrey; + _labelTextColor = [UIColor grayColor]; + _labelFont = [UIFont systemFontOfSize:11.0f]; + _xChartLabels = [NSMutableArray array]; + _yChartLabels = [NSMutableArray array]; + _bars = [NSMutableArray array]; + _xLabelSkip = 1; + _yLabelSum = 4; + _labelMarginTop = 0; + _chartMarginLeft = 25.0; + _chartMarginRight = 25.0; + _chartMarginTop = 25.0; + _chartMarginBottom = 25.0; + _barRadius = 2.0; + _showChartBorder = NO; + _chartBorderColor = PNLightGrey; + _showLevelLine = NO; + _yChartLabelWidth = 18; + _rotateForXAxisText = false; + _isGradientShow = YES; + _isShowNumbers = YES; + _yLabelPrefix = @""; + _yLabelSuffix = @""; + _yLabelFormatter = ^(CGFloat yValue){ + return [NSString stringWithFormat:@"%1.f",yValue]; + }; +} + +- (void)setYValues:(NSArray *)yValues +{ + _yValues = yValues; + //make the _yLabelSum value dependant of the distinct values of yValues to avoid duplicates on yAxis + + if (_showLabel) { + [self __addYCoordinateLabelsValues]; + } else { + [self processYMaxValue]; + } +} + +- (void)processYMaxValue { + NSArray *yAxisValues = _yLabels ? _yLabels : _yValues; + _yLabelSum = _yLabels ? _yLabels.count - 1 :_yLabelSum; + if (_yMaxValue) { + _yValueMax = _yMaxValue; + } else { + [self getYValueMax:yAxisValues]; + } + + if (_yLabelSum==4) { + _yLabelSum = yAxisValues.count; + (_yLabelSum % 2 == 0) ? _yLabelSum : _yLabelSum++; + } +} + +#pragma mark - Private Method +#pragma mark - Add Y Label +- (void)__addYCoordinateLabelsValues{ + + [self viewCleanupForCollection:_yChartLabels]; + + [self processYMaxValue]; + + float sectionHeight = (self.frame.size.height - _chartMarginTop - _chartMarginBottom - kXLabelHeight) / _yLabelSum; + + for (int i = 0; i <= _yLabelSum; i++) { + NSString *labelText; + if (_yLabels) { + float yAsixValue = [_yLabels[_yLabels.count - i - 1] floatValue]; + labelText= _yLabelFormatter(yAsixValue); + } else { + labelText = _yLabelFormatter((float)_yValueMax * ( (_yLabelSum - i) / (float)_yLabelSum )); + } + + PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectZero]; + label.font = _labelFont; + label.textColor = _labelTextColor; + [label setTextAlignment:NSTextAlignmentRight]; + label.text = [NSString stringWithFormat:@"%@%@%@", _yLabelPrefix, labelText, _yLabelSuffix]; + + [self addSubview:label]; + + label.frame = (CGRect){0, sectionHeight * i + _chartMarginTop - kYLabelHeight/2.0, _yChartLabelWidth, kYLabelHeight}; + + [_yChartLabels addObject:label]; + } +} + +-(void)updateChartData:(NSArray *)data{ + self.yValues = data; + [self updateBar]; +} + +- (void)getYValueMax:(NSArray *)yLabels +{ + CGFloat max = [[yLabels valueForKeyPath:@"@max.floatValue"] floatValue]; + + //ensure max is even + _yValueMax = max ; + + if (_yValueMax == 0) { + _yValueMax = _yMinValue; + } +} + +- (void)setXLabels:(NSArray *)xLabels +{ + _xLabels = xLabels; + + if (_xChartLabels) { + [self viewCleanupForCollection:_xChartLabels]; + }else{ + _xChartLabels = [NSMutableArray new]; + } + + _xLabelWidth = (self.frame.size.width - _chartMarginLeft - _chartMarginRight) / [xLabels count]; + + if (_showLabel) { + int labelAddCount = 0; + for (int index = 0; index < _xLabels.count; index++) { + labelAddCount += 1; + + if (labelAddCount == _xLabelSkip) { + NSString *labelText = [_xLabels[index] description]; + PNChartLabel * label = [[PNChartLabel alloc] initWithFrame:CGRectMake(0, 0, _xLabelWidth, kXLabelHeight)]; + label.font = _labelFont; + label.textColor = _labelTextColor; + [label setTextAlignment:NSTextAlignmentCenter]; + label.text = labelText; + //[label sizeToFit]; + CGFloat labelXPosition; + if (_rotateForXAxisText){ + label.transform = CGAffineTransformMakeRotation(M_PI / 4); + labelXPosition = (index * _xLabelWidth + _chartMarginLeft + _xLabelWidth /1.5); + } + else{ + labelXPosition = (index * _xLabelWidth + _chartMarginLeft + _xLabelWidth /2.0 ); + } + label.center = CGPointMake(labelXPosition, + self.frame.size.height - kXLabelHeight - _chartMarginTop + label.frame.size.height /2.0 + _labelMarginTop); + labelAddCount = 0; + + [_xChartLabels addObject:label]; + [self addSubview:label]; + } + } + } +} + + +- (void)setStrokeColor:(UIColor *)strokeColor +{ + _strokeColor = strokeColor; +} + +- (void)updateBar +{ + + //Add bars + CGFloat chartCavanHeight = self.frame.size.height - _chartMarginTop - _chartMarginBottom - kXLabelHeight; + NSInteger index = 0; + + for (NSNumber *valueString in _yValues) { + + PNBar *bar; + + if (_bars.count == _yValues.count) { + bar = [_bars objectAtIndex:index]; + }else{ + CGFloat barWidth; + CGFloat barXPosition; + + if (_barWidth) { + barWidth = _barWidth; + barXPosition = index * _xLabelWidth + _chartMarginLeft + _xLabelWidth /2.0 - _barWidth /2.0; + }else{ + barXPosition = index * _xLabelWidth + _chartMarginLeft + _xLabelWidth * 0.25; + if (_showLabel) { + barWidth = _xLabelWidth * 0.5; + + } + else { + barWidth = _xLabelWidth * 0.6; + + } + } + + bar = [[PNBar alloc] initWithFrame:CGRectMake(barXPosition, //Bar X position + self.frame.size.height - chartCavanHeight - kXLabelHeight - _chartMarginBottom + _chartMarginTop , //Bar Y position + barWidth, // Bar witdh + self.showLevelLine ? chartCavanHeight/2.0:chartCavanHeight)]; //Bar height + + //Change Bar Radius + bar.barRadius = _barRadius; + + //Set Bar Animation + bar.displayAnimated = self.displayAnimated; + + //Change Bar Background color + bar.backgroundColor = _barBackgroundColor; + //Bar StrokColor First + if (self.strokeColor) { + bar.barColor = self.strokeColor; + }else{ + bar.barColor = [self barColorAtIndex:index]; + } + + if (self.labelTextColor) { + bar.labelTextColor = self.labelTextColor; + } + + // Add gradient + if (self.isGradientShow) { + bar.barColorGradientStart = bar.barColor; + } + + //For Click Index + bar.tag = index; + + [_bars addObject:bar]; + [self addSubview:bar]; + } + + //Height Of Bar + float value = [valueString floatValue]; + float grade =fabsf((float)value / (float)_yValueMax); + + if (isnan(grade)) { + grade = 0; + } + bar.maxDivisor = (float)_yValueMax; + bar.grade = grade; + bar.isShowNumber = self.isShowNumbers; + CGRect originalFrame = bar.frame; + NSString *currentNumber = [NSString stringWithFormat:@"%f",value]; + + if ([[currentNumber substringToIndex:1] isEqualToString:@"-"] && self.showLevelLine) { + CGAffineTransform transform =CGAffineTransformMakeRotation(M_PI); + [bar setTransform:transform]; + originalFrame.origin.y = bar.frame.origin.y + bar.frame.size.height; + bar.frame = originalFrame; + bar.isNegative = YES; + + } + index += 1; + } +} + +- (void)strokeChart +{ + //Add Labels + + [self viewCleanupForCollection:_bars]; + + + //Update Bar + + [self updateBar]; + + //Add chart border lines + + if (_showChartBorder) { + _chartBottomLine = [CAShapeLayer layer]; + _chartBottomLine.lineCap = kCALineCapButt; + _chartBottomLine.fillColor = [[UIColor whiteColor] CGColor]; + _chartBottomLine.lineWidth = 1.0; + _chartBottomLine.strokeEnd = 0.0; + + UIBezierPath *progressline = [UIBezierPath bezierPath]; + + [progressline moveToPoint:CGPointMake(_chartMarginLeft, self.frame.size.height - kXLabelHeight - _chartMarginBottom + _chartMarginTop)]; + [progressline addLineToPoint:CGPointMake(self.frame.size.width - _chartMarginRight, self.frame.size.height - kXLabelHeight - _chartMarginBottom + _chartMarginTop)]; + + [progressline setLineWidth:1.0]; + [progressline setLineCapStyle:kCGLineCapSquare]; + _chartBottomLine.path = progressline.CGPath; + _chartBottomLine.strokeColor = [_chartBorderColor CGColor];; + _chartBottomLine.strokeEnd = 1.0; + + [self.layer addSublayer:_chartBottomLine]; + + //Add left Chart Line + + _chartLeftLine = [CAShapeLayer layer]; + _chartLeftLine.lineCap = kCALineCapButt; + _chartLeftLine.fillColor = [[UIColor whiteColor] CGColor]; + _chartLeftLine.lineWidth = 1.0; + _chartLeftLine.strokeEnd = 0.0; + + UIBezierPath *progressLeftline = [UIBezierPath bezierPath]; + + [progressLeftline moveToPoint:CGPointMake(_chartMarginLeft, self.frame.size.height - kXLabelHeight - _chartMarginBottom + _chartMarginTop)]; + [progressLeftline addLineToPoint:CGPointMake(_chartMarginLeft, _chartMarginTop)]; + + [progressLeftline setLineWidth:1.0]; + [progressLeftline setLineCapStyle:kCGLineCapSquare]; + _chartLeftLine.path = progressLeftline.CGPath; + _chartLeftLine.strokeColor = [_chartBorderColor CGColor]; + _chartLeftLine.strokeEnd = 1.0; + + [self addBorderAnimationIfNeeded]; + [self.layer addSublayer:_chartLeftLine]; + } + + // Add Level Separator Line + if (_showLevelLine) { + _chartLevelLine = [CAShapeLayer layer]; + _chartLevelLine.lineCap = kCALineCapButt; + _chartLevelLine.fillColor = [[UIColor whiteColor] CGColor]; + _chartLevelLine.lineWidth = 1.0; + _chartLevelLine.strokeEnd = 0.0; + + UIBezierPath *progressline = [UIBezierPath bezierPath]; + + [progressline moveToPoint:CGPointMake(_chartMarginLeft, (self.frame.size.height - kXLabelHeight )/2.0)]; + [progressline addLineToPoint:CGPointMake(self.frame.size.width - _chartMarginLeft - _chartMarginRight, (self.frame.size.height - kXLabelHeight )/2.0)]; + + [progressline setLineWidth:1.0]; + [progressline setLineCapStyle:kCGLineCapSquare]; + _chartLevelLine.path = progressline.CGPath; + + _chartLevelLine.strokeColor = PNLightGrey.CGColor; + + [self addSeparatorAnimationIfNeeded]; + _chartLevelLine.strokeEnd = 1.0; + + [self.layer addSublayer:_chartLevelLine]; + } else { + if (_chartLevelLine) { + [_chartLevelLine removeFromSuperlayer]; + _chartLevelLine = nil; + } + } +} + +- (void)addBorderAnimationIfNeeded +{ + if (self.displayAnimated) { + CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + pathAnimation.duration = 0.5; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + pathAnimation.fromValue = @0.0f; + pathAnimation.toValue = @1.0f; + [_chartBottomLine addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; + + CABasicAnimation *pathLeftAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + pathLeftAnimation.duration = 0.5; + pathLeftAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + pathLeftAnimation.fromValue = @0.0f; + pathLeftAnimation.toValue = @1.0f; + [_chartLeftLine addAnimation:pathLeftAnimation forKey:@"strokeEndAnimation"]; + } +} + +- (void)addSeparatorAnimationIfNeeded +{ + if (self.displayAnimated) { + CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + pathAnimation.duration = 0.5; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + pathAnimation.fromValue = @0.0f; + pathAnimation.toValue = @1.0f; + [_chartLevelLine addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; + } +} + +- (void)viewCleanupForCollection:(NSMutableArray *)array +{ + if (array.count) { + [array makeObjectsPerformSelector:@selector(removeFromSuperview)]; + [array removeAllObjects]; + } +} + + +#pragma mark - Class extension methods + +- (UIColor *)barColorAtIndex:(NSUInteger)index +{ + if ([self.strokeColors count] == [self.yValues count]) { + return self.strokeColors[index]; + } + else { + return self.strokeColor; + } +} + +#pragma mark - Touch detection + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +{ + [self touchPoint:touches withEvent:event]; + [super touchesBegan:touches withEvent:event]; +} + +- (void)touchPoint:(NSSet *)touches withEvent:(UIEvent *)event +{ + //Get the point user touched + UITouch *touch = [touches anyObject]; + CGPoint touchPoint = [touch locationInView:self]; + UIView *subview = [self hitTest:touchPoint withEvent:nil]; + + if ([subview isKindOfClass:[PNBar class]] && [self.delegate respondsToSelector:@selector(userClickedOnBarAtIndex:)]) { + [self.delegate userClickedOnBarAtIndex:subview.tag]; + } +} + + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNChart.h b/Statistics/Pods/PNChart/PNChart/PNChart.h new file mode 100644 index 0000000..0835d39 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNChart.h @@ -0,0 +1,22 @@ +// +// PNChart.h +// Version 0.1 +// PNChart +// +// Created by kevin on 10/3/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import +#import "PNChart.h" +#import "PNColor.h" +#import "PNLineChart.h" +#import "PNLineChartData.h" +#import "PNLineChartDataItem.h" +#import "PNBarChart.h" +#import "PNCircleChart.h" +#import "PNChartDelegate.h" +#import "PNPieChart.h" +#import "PNScatterChart.h" +#import "PNRadarChart.h" +#import "PNRadarChartDataItem.h" diff --git a/Statistics/Pods/PNChart/PNChart/PNChartDelegate.h b/Statistics/Pods/PNChart/PNChart/PNChartDelegate.h new file mode 100644 index 0000000..6d49f7c --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNChartDelegate.h @@ -0,0 +1,33 @@ +// +// PNChartDelegate.h +// PNChartDemo +// +// Created by kevinzhow on 13-12-11. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import + +@protocol PNChartDelegate +@optional +/** + * Callback method that gets invoked when the user taps on the chart line. + */ +- (void)userClickedOnLinePoint:(CGPoint)point lineIndex:(NSInteger)lineIndex; + +/** + * Callback method that gets invoked when the user taps on a chart line key point. + */ +- (void)userClickedOnLineKeyPoint:(CGPoint)point + lineIndex:(NSInteger)lineIndex + pointIndex:(NSInteger)pointIndex; + +/** + * Callback method that gets invoked when the user taps on a chart bar. + */ +- (void)userClickedOnBarAtIndex:(NSInteger)barIndex; + + +- (void)userClickedOnPieIndexItem:(NSInteger)pieIndex; +- (void)didUnselectPieItem; +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNChartLabel.h b/Statistics/Pods/PNChart/PNChart/PNChartLabel.h new file mode 100644 index 0000000..9ba6afa --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNChartLabel.h @@ -0,0 +1,13 @@ +// +// PNChartLabel.h +// PNChart +// +// Created by kevin on 10/3/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import + +@interface PNChartLabel : UILabel + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNChartLabel.m b/Statistics/Pods/PNChart/PNChart/PNChartLabel.m new file mode 100644 index 0000000..b0980d1 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNChartLabel.m @@ -0,0 +1,32 @@ +// +// PNChartLabel.m +// PNChart +// +// Created by kevin on 10/3/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import "PNChartLabel.h" + +@implementation PNChartLabel + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + + if (self) { + self.font = [UIFont boldSystemFontOfSize:11.0f]; + self.backgroundColor = [UIColor clearColor]; + self.textAlignment = NSTextAlignmentCenter; + self.userInteractionEnabled = YES; + self.adjustsFontSizeToFitWidth = YES; + self.numberOfLines = 0; + /* if you want to see ... in large labels un-comment this line + self.minimumScaleFactor = 0.8; + */ + } + + return self; +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNCircleChart.h b/Statistics/Pods/PNChart/PNChart/PNCircleChart.h new file mode 100644 index 0000000..0c57376 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNCircleChart.h @@ -0,0 +1,74 @@ +// +// PNCircleChart.h +// PNChartDemo +// +// Created by kevinzhow on 13-11-30. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import +#import "PNColor.h" +#import + +typedef NS_ENUM (NSUInteger, PNChartFormatType) { + PNChartFormatTypePercent, + PNChartFormatTypeDollar, + PNChartFormatTypeNone, + PNChartFormatTypeDecimal, + PNChartFormatTypeDecimalTwoPlaces, +}; + +#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI) + +@interface PNCircleChart : UIView + +- (void)strokeChart; +- (void)growChartByAmount:(NSNumber *)growAmount; +- (void)updateChartByCurrent:(NSNumber *)current; +- (void)updateChartByCurrent:(NSNumber *)current byTotal:(NSNumber *)total; +- (id)initWithFrame:(CGRect)frame + total:(NSNumber *)total + current:(NSNumber *)current + clockwise:(BOOL)clockwise; + +- (id)initWithFrame:(CGRect)frame + total:(NSNumber *)total + current:(NSNumber *)current + clockwise:(BOOL)clockwise + shadow:(BOOL)hasBackgroundShadow + shadowColor:(UIColor *)backgroundShadowColor; + +- (id)initWithFrame:(CGRect)frame + total:(NSNumber *)total + current:(NSNumber *)current + clockwise:(BOOL)clockwise + shadow:(BOOL)hasBackgroundShadow + shadowColor:(UIColor *)backgroundShadowColor +displayCountingLabel:(BOOL)displayCountingLabel; + +- (id)initWithFrame:(CGRect)frame + total:(NSNumber *)total + current:(NSNumber *)current + clockwise:(BOOL)clockwise + shadow:(BOOL)hasBackgroundShadow + shadowColor:(UIColor *)backgroundShadowColor +displayCountingLabel:(BOOL)displayCountingLabel + overrideLineWidth:(NSNumber *)overrideLineWidth; + +@property (strong, nonatomic) UICountingLabel *countingLabel; +@property (nonatomic) UIColor *strokeColor; +@property (nonatomic) UIColor *strokeColorGradientStart; +@property (nonatomic) NSNumber *total; +@property (nonatomic) NSNumber *current; +@property (nonatomic) NSNumber *lineWidth; +@property (nonatomic) NSTimeInterval duration; +@property (nonatomic) PNChartFormatType chartType; + +@property (nonatomic) CAShapeLayer *circle; +@property (nonatomic) CAShapeLayer *gradientMask; +@property (nonatomic) CAShapeLayer *circleBackground; + +@property (nonatomic) BOOL displayCountingLabel; +@property (nonatomic) BOOL displayAnimated; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNCircleChart.m b/Statistics/Pods/PNChart/PNChart/PNCircleChart.m new file mode 100644 index 0000000..19f70e5 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNCircleChart.m @@ -0,0 +1,267 @@ +// +// PNCircleChart.m +// PNChartDemo +// +// Created by kevinzhow on 13-11-30. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import "PNCircleChart.h" + +@interface PNCircleChart () +@end + +@implementation PNCircleChart + +- (id)initWithFrame:(CGRect)frame total:(NSNumber *)total current:(NSNumber *)current clockwise:(BOOL)clockwise { + + return [self initWithFrame:frame + total:total + current:current + clockwise:clockwise + shadow:NO + shadowColor:[UIColor clearColor] + displayCountingLabel:YES + overrideLineWidth:@8.0f]; + +} + +- (id)initWithFrame:(CGRect)frame total:(NSNumber *)total current:(NSNumber *)current clockwise:(BOOL)clockwise shadow:(BOOL)hasBackgroundShadow shadowColor:(UIColor *)backgroundShadowColor { + + return [self initWithFrame:frame + total:total + current:current + clockwise:clockwise + shadow:shadow + shadowColor:backgroundShadowColor + displayCountingLabel:YES + overrideLineWidth:@8.0f]; + +} + +- (id)initWithFrame:(CGRect)frame total:(NSNumber *)total current:(NSNumber *)current clockwise:(BOOL)clockwise shadow:(BOOL)hasBackgroundShadow shadowColor:(UIColor *)backgroundShadowColor displayCountingLabel:(BOOL)displayCountingLabel { + + return [self initWithFrame:frame + total:total + current:current + clockwise:clockwise + shadow:shadow + shadowColor:backgroundShadowColor + displayCountingLabel:displayCountingLabel + overrideLineWidth:@8.0f]; + +} + +- (id)initWithFrame:(CGRect)frame + total:(NSNumber *)total + current:(NSNumber *)current + clockwise:(BOOL)clockwise + shadow:(BOOL)hasBackgroundShadow + shadowColor:(UIColor *)backgroundShadowColor +displayCountingLabel:(BOOL)displayCountingLabel + overrideLineWidth:(NSNumber *)overrideLineWidth +{ + self = [super initWithFrame:frame]; + + if (self) { + _total = total; + _current = current; + _strokeColor = PNFreshGreen; + _duration = 1.0; + _chartType = PNChartFormatTypePercent; + _displayAnimated = YES; + + _displayCountingLabel = displayCountingLabel; + + CGFloat startAngle = clockwise ? -90.0f : 270.0f; + CGFloat endAngle = clockwise ? -90.01f : 270.01f; + + _lineWidth = overrideLineWidth; + + UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2.0f, self.frame.size.height/2.0f) + radius:(self.frame.size.height * 0.5) - ([_lineWidth floatValue]/2.0f) + startAngle:DEGREES_TO_RADIANS(startAngle) + endAngle:DEGREES_TO_RADIANS(endAngle) + clockwise:clockwise]; + + _circle = [CAShapeLayer layer]; + _circle.path = circlePath.CGPath; + _circle.lineCap = kCALineCapRound; + _circle.fillColor = [UIColor clearColor].CGColor; + _circle.lineWidth = [_lineWidth floatValue]; + _circle.zPosition = 1; + + _circleBackground = [CAShapeLayer layer]; + _circleBackground.path = circlePath.CGPath; + _circleBackground.lineCap = kCALineCapRound; + _circleBackground.fillColor = [UIColor clearColor].CGColor; + _circleBackground.lineWidth = [_lineWidth floatValue]; + _circleBackground.strokeColor = (hasBackgroundShadow ? backgroundShadowColor.CGColor : [UIColor clearColor].CGColor); + _circleBackground.strokeEnd = 1.0; + _circleBackground.zPosition = -1; + + [self.layer addSublayer:_circle]; + [self.layer addSublayer:_circleBackground]; + + _countingLabel = [[UICountingLabel alloc] initWithFrame:CGRectMake(0, 0, 100.0, 50.0)]; + [_countingLabel setTextAlignment:NSTextAlignmentCenter]; + [_countingLabel setFont:[UIFont boldSystemFontOfSize:16.0f]]; + [_countingLabel setTextColor:[UIColor grayColor]]; + [_countingLabel setBackgroundColor:[UIColor clearColor]]; + [_countingLabel setCenter:CGPointMake(self.frame.size.width/2.0f, self.frame.size.height/2.0f)]; + _countingLabel.method = UILabelCountingMethodEaseInOut; + if (_displayCountingLabel) { + [self addSubview:_countingLabel]; + } + } + + return self; +} + + +- (void)strokeChart +{ + // Add counting label + + if (_displayCountingLabel) { + NSString *format; + switch (self.chartType) { + case PNChartFormatTypePercent: + format = @"%d%%"; + break; + case PNChartFormatTypeDollar: + format = @"$%d"; + break; + case PNChartFormatTypeDecimal: + format = @"%.1f"; + break; + case PNChartFormatTypeDecimalTwoPlaces: + format = @"%.2f"; + break; + case PNChartFormatTypeNone: + default: + format = @"%d"; + break; + } + self.countingLabel.format = format; + [self addSubview:self.countingLabel]; + } + + + // Add circle params + + _circle.lineWidth = [_lineWidth floatValue]; + _circleBackground.lineWidth = [_lineWidth floatValue]; + _circleBackground.strokeEnd = 1.0; + _circle.strokeColor = _strokeColor.CGColor; + _circle.strokeEnd = [_current floatValue] / [_total floatValue]; + + // Check if user wants to add a gradient from the start color to the bar color + if (_strokeColorGradientStart) { + + // Add gradient + self.gradientMask = [CAShapeLayer layer]; + self.gradientMask.fillColor = [[UIColor clearColor] CGColor]; + self.gradientMask.strokeColor = [[UIColor blackColor] CGColor]; + self.gradientMask.lineWidth = _circle.lineWidth; + self.gradientMask.lineCap = kCALineCapRound; + CGRect gradientFrame = CGRectMake(0, 0, 2*self.bounds.size.width, 2*self.bounds.size.height); + self.gradientMask.frame = gradientFrame; + self.gradientMask.path = _circle.path; + + CAGradientLayer *gradientLayer = [CAGradientLayer layer]; + gradientLayer.startPoint = CGPointMake(0.5,1.0); + gradientLayer.endPoint = CGPointMake(0.5,0.0); + gradientLayer.frame = gradientFrame; + UIColor *endColor = (_strokeColor ? _strokeColor : [UIColor greenColor]); + NSArray *colors = @[ + (id)endColor.CGColor, + (id)_strokeColorGradientStart.CGColor + ]; + gradientLayer.colors = colors; + + [gradientLayer setMask:self.gradientMask]; + + [_circle addSublayer:gradientLayer]; + + self.gradientMask.strokeEnd = [_current floatValue] / [_total floatValue]; + } + + [self addAnimationIfNeeded]; +} + + + +- (void)growChartByAmount:(NSNumber *)growAmount +{ + NSNumber *updatedValue = [NSNumber numberWithFloat:[_current floatValue] + [growAmount floatValue]]; + + // Add animation + [self updateChartByCurrent:updatedValue]; +} + + +-(void)updateChartByCurrent:(NSNumber *)current{ + + [self updateChartByCurrent:current + byTotal:_total]; + +} + +-(void)updateChartByCurrent:(NSNumber *)current byTotal:(NSNumber *)total { + double totalPercentageValue = [current floatValue]/([total floatValue]/100.0); + + if (_strokeColorGradientStart) { + self.gradientMask.strokeEnd = _circle.strokeEnd; + } + + // Add animation + if (self.displayAnimated) { + CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + pathAnimation.duration = self.duration; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + pathAnimation.fromValue = @([_current floatValue] / [_total floatValue]); + pathAnimation.toValue = @([current floatValue] / [total floatValue]); + + if (_strokeColorGradientStart) { + [self.gradientMask addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; + } + [_circle addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; + + if (_displayCountingLabel) { + [self.countingLabel countFrom:fmin([_current floatValue], [_total floatValue]) to:totalPercentageValue withDuration:self.duration]; + } + + } + else if (_displayCountingLabel) { + [self.countingLabel countFrom:totalPercentageValue to:totalPercentageValue withDuration:self.duration]; + } + + _circle.strokeEnd = [current floatValue] / [total floatValue]; + _current = current; + _total = total; +} + +- (void)addAnimationIfNeeded +{ + double percentageValue = [_current floatValue]/([_total floatValue]/100.0); + + if (self.displayAnimated) { + CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + pathAnimation.duration = self.duration; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + pathAnimation.fromValue = @(0.0f); + pathAnimation.toValue = @([_current floatValue] / [_total floatValue]); + [_circle addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; + [_countingLabel countFrom:0 to:percentageValue withDuration:self.duration]; + + if (self.gradientMask && _strokeColorGradientStart) { + [self.gradientMask addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; + } + } + else { + [_countingLabel countFrom:percentageValue to:percentageValue withDuration:self.duration]; + } +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNColor.h b/Statistics/Pods/PNChart/PNChart/PNColor.h new file mode 100644 index 0000000..cfd3ff8 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNColor.h @@ -0,0 +1,53 @@ +// +// PNColor.h +// PNChart +// +// Created by kevin on 13-6-8. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import +#import + +/* + * System Versioning Preprocessor Macros + */ + +#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width) + +#define PNGrey [UIColor colorWithRed:246.0 / 255.0 green:246.0 / 255.0 blue:246.0 / 255.0 alpha:1.0f] +#define PNLightBlue [UIColor colorWithRed:94.0 / 255.0 green:147.0 / 255.0 blue:196.0 / 255.0 alpha:1.0f] +#define PNGreen [UIColor colorWithRed:77.0 / 255.0 green:186.0 / 255.0 blue:122.0 / 255.0 alpha:1.0f] +#define PNTitleColor [UIColor colorWithRed:0.0 / 255.0 green:189.0 / 255.0 blue:113.0 / 255.0 alpha:1.0f] +#define PNButtonGrey [UIColor colorWithRed:141.0 / 255.0 green:141.0 / 255.0 blue:141.0 / 255.0 alpha:1.0f] +#define PNLightGreen [UIColor colorWithRed:77.0 / 255.0 green:216.0 / 255.0 blue:122.0 / 255.0 alpha:1.0f] +#define PNFreshGreen [UIColor colorWithRed:77.0 / 255.0 green:196.0 / 255.0 blue:122.0 / 255.0 alpha:1.0f] +#define PNDeepGreen [UIColor colorWithRed:77.0 / 255.0 green:176.0 / 255.0 blue:122.0 / 255.0 alpha:1.0f] +#define PNRed [UIColor colorWithRed:245.0 / 255.0 green:94.0 / 255.0 blue:78.0 / 255.0 alpha:1.0f] +#define PNMauve [UIColor colorWithRed:88.0 / 255.0 green:75.0 / 255.0 blue:103.0 / 255.0 alpha:1.0f] +#define PNBrown [UIColor colorWithRed:119.0 / 255.0 green:107.0 / 255.0 blue:95.0 / 255.0 alpha:1.0f] +#define PNBlue [UIColor colorWithRed:82.0 / 255.0 green:116.0 / 255.0 blue:188.0 / 255.0 alpha:1.0f] +#define PNDarkBlue [UIColor colorWithRed:121.0 / 255.0 green:134.0 / 255.0 blue:142.0 / 255.0 alpha:1.0f] +#define PNYellow [UIColor colorWithRed:242.0 / 255.0 green:197.0 / 255.0 blue:117.0 / 255.0 alpha:1.0f] +#define PNWhite [UIColor colorWithRed:255.0 / 255.0 green:255.0 / 255.0 blue:255.0 / 255.0 alpha:1.0f] +#define PNDeepGrey [UIColor colorWithRed:99.0 / 255.0 green:99.0 / 255.0 blue:99.0 / 255.0 alpha:1.0f] +#define PNPinkGrey [UIColor colorWithRed:200.0 / 255.0 green:193.0 / 255.0 blue:193.0 / 255.0 alpha:1.0f] +#define PNHealYellow [UIColor colorWithRed:245.0 / 255.0 green:242.0 / 255.0 blue:238.0 / 255.0 alpha:1.0f] +#define PNLightGrey [UIColor colorWithRed:225.0 / 255.0 green:225.0 / 255.0 blue:225.0 / 255.0 alpha:1.0f] +#define PNCleanGrey [UIColor colorWithRed:251.0 / 255.0 green:251.0 / 255.0 blue:251.0 / 255.0 alpha:1.0f] +#define PNLightYellow [UIColor colorWithRed:241.0 / 255.0 green:240.0 / 255.0 blue:240.0 / 255.0 alpha:1.0f] +#define PNDarkYellow [UIColor colorWithRed:152.0 / 255.0 green:150.0 / 255.0 blue:159.0 / 255.0 alpha:1.0f] +#define PNPinkDark [UIColor colorWithRed:170.0 / 255.0 green:165.0 / 255.0 blue:165.0 / 255.0 alpha:1.0f] +#define PNCloudWhite [UIColor colorWithRed:244.0 / 255.0 green:244.0 / 255.0 blue:244.0 / 255.0 alpha:1.0f] +#define PNBlack [UIColor colorWithRed:45.0 / 255.0 green:45.0 / 255.0 blue:45.0 / 255.0 alpha:1.0f] +#define PNStarYellow [UIColor colorWithRed:252.0 / 255.0 green:223.0 / 255.0 blue:101.0 / 255.0 alpha:1.0f] +#define PNTwitterColor [UIColor colorWithRed:0.0 / 255.0 green:171.0 / 255.0 blue:243.0 / 255.0 alpha:1.0] +#define PNWeiboColor [UIColor colorWithRed:250.0 / 255.0 green:0.0 / 255.0 blue:33.0 / 255.0 alpha:1.0] +#define PNiOSGreenColor [UIColor colorWithRed:98.0 / 255.0 green:247.0 / 255.0 blue:77.0 / 255.0 alpha:1.0] + + +@interface PNColor : NSObject + +- (UIImage *)imageFromColor:(UIColor *)color; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNColor.m b/Statistics/Pods/PNChart/PNChart/PNColor.m new file mode 100644 index 0000000..2ebc8c0 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNColor.m @@ -0,0 +1,29 @@ +// +// PNColor.m +// PNChart +// +// Created by kevin on 13-6-8. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import "PNColor.h" +#import + +@implementation PNColor + +- (UIImage *)imageFromColor:(UIColor *)color +{ + CGRect rect = CGRectMake(0, 0, 1, 1); + + UIGraphicsBeginImageContext(rect.size); + CGContextRef context = UIGraphicsGetCurrentContext(); + CGContextSetFillColorWithColor(context, [color CGColor]); + CGContextFillRect(context, rect); + UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + + return img; +} + + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNGenericChart.h b/Statistics/Pods/PNChart/PNChart/PNGenericChart.h new file mode 100644 index 0000000..829d84a --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNGenericChart.h @@ -0,0 +1,48 @@ +// +// PNGenericChart.h +// PNChartDemo +// +// Created by Andi Palo on 26/02/15. +// Copyright (c) 2015 kevinzhow. All rights reserved. +// + +#import + +typedef NS_ENUM(NSUInteger, PNLegendPosition) { + PNLegendPositionTop = 0, + PNLegendPositionBottom = 1, + PNLegendPositionLeft = 2, + PNLegendPositionRight = 3 +}; + +typedef NS_ENUM(NSUInteger, PNLegendItemStyle) { + PNLegendItemStyleStacked = 0, + PNLegendItemStyleSerial = 1 +}; + +@interface PNGenericChart : UIView + +@property (assign, nonatomic) BOOL hasLegend; +@property (assign, nonatomic) PNLegendPosition legendPosition; +@property (assign, nonatomic) PNLegendItemStyle legendStyle; + +@property (assign, nonatomic) UIFont *legendFont; +@property (assign, nonatomic) UIColor *legendFontColor; +@property (assign, nonatomic) NSUInteger labelRowsInSerialMode; + +/** Display the chart with or without animation. Default is YES. **/ +@property (nonatomic) BOOL displayAnimated; + +/** + * returns the Legend View, or nil if no chart data is present. + * The origin of the legend frame is 0,0 but you can set it with setFrame:(CGRect) + * + * @param mWidth Maximum width of legend. Height will depend on this and font size + * + * @return UIView of Legend + */ +- (UIView*) getLegendWithMaxWidth:(CGFloat)mWidth; + + +- (void) setupDefaultValues; +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNGenericChart.m b/Statistics/Pods/PNChart/PNChart/PNGenericChart.m new file mode 100644 index 0000000..c54ac37 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNGenericChart.m @@ -0,0 +1,54 @@ +// +// PNGenericChart.m +// PNChartDemo +// +// Created by Andi Palo on 26/02/15. +// Copyright (c) 2015 kevinzhow. All rights reserved. +// + +#import "PNGenericChart.h" + +@interface PNGenericChart () + + + +@end + +@implementation PNGenericChart + +/* +// Only override drawRect: if you perform custom drawing. +// An empty implementation adversely affects performance during animation. +- (void)drawRect:(CGRect)rect { + // Drawing code +} +*/ + +- (void) setupDefaultValues{ + self.hasLegend = YES; + self.legendPosition = PNLegendPositionBottom; + self.legendStyle = PNLegendItemStyleStacked; + self.labelRowsInSerialMode = 1; + self.displayAnimated = YES; +} + + + +/** + * to be implemented in subclass + */ +- (UIView*) getLegendWithMaxWidth:(CGFloat)mWidth{ + [self doesNotRecognizeSelector:_cmd]; + return nil; +} + +- (void) setLabelRowsInSerialMode:(NSUInteger)num{ + if (self.legendStyle == PNLegendItemStyleSerial) { + _labelRowsInSerialMode = num; + }else{ + _labelRowsInSerialMode = 1; + } +} + + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNLineChart.h b/Statistics/Pods/PNChart/PNChart/PNLineChart.h new file mode 100755 index 0000000..b30878a --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNLineChart.h @@ -0,0 +1,110 @@ +// +// PNLineChart.h +// PNChartDemo +// +// Created by kevin on 11/7/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import +#import +#import "PNChartDelegate.h" +#import "PNGenericChart.h" + +@interface PNLineChart : PNGenericChart + +/** + * Draws the chart in an animated fashion. + */ +- (void)strokeChart; + +@property (nonatomic, weak) id delegate; + +@property (nonatomic) NSArray *xLabels; +@property (nonatomic) NSArray *yLabels; + +/** + * Array of `LineChartData` objects, one for each line. + */ +@property (nonatomic) NSArray *chartData; + +@property (nonatomic) NSMutableArray *pathPoints; +@property (nonatomic) NSMutableArray *xChartLabels; +@property (nonatomic) NSMutableArray *yChartLabels; + +@property (nonatomic) CGFloat xLabelWidth; +@property (nonatomic) UIFont *xLabelFont; +@property (nonatomic) UIColor *xLabelColor; +@property (nonatomic) CGFloat yValueMax; +@property (nonatomic) CGFloat yFixedValueMax; +@property (nonatomic) CGFloat yFixedValueMin; +@property (nonatomic) CGFloat yValueMin; +@property (nonatomic) NSInteger yLabelNum; +@property (nonatomic) CGFloat yLabelHeight; +@property (nonatomic) UIFont *yLabelFont; +@property (nonatomic) UIColor *yLabelColor; +@property (nonatomic) CGFloat chartCavanHeight; +@property (nonatomic) CGFloat chartCavanWidth; +@property (nonatomic) BOOL showLabel; +@property (nonatomic) BOOL showGenYLabels; +@property (nonatomic) BOOL showYGridLines; +@property (nonatomic) UIColor *yGridLinesColor; +@property (nonatomic) BOOL thousandsSeparator; + +@property (nonatomic) CGFloat chartMarginLeft; +@property (nonatomic) CGFloat chartMarginRight; +@property (nonatomic) CGFloat chartMarginTop; +@property (nonatomic) CGFloat chartMarginBottom; + +/** + * Controls whether to show the coordinate axis. Default is NO. + */ +@property (nonatomic, getter = isShowCoordinateAxis) BOOL showCoordinateAxis; +@property (nonatomic) UIColor *axisColor; +@property (nonatomic) CGFloat axisWidth; + +@property (nonatomic, strong) NSString *xUnit; +@property (nonatomic, strong) NSString *yUnit; + +/** + * String formatter for float values in y-axis labels. If not set, defaults to @"%1.f" + */ +@property (nonatomic, strong) NSString *yLabelFormat; + +/** + * Block formatter for custom string in y-axis labels. If not set, defaults to yLabelFormat + */ +@property (nonatomic, copy) NSString* (^yLabelBlockFormatter)(CGFloat); + + +/** + * Controls whether to curve the line chart or not + */ +@property (nonatomic) BOOL showSmoothLines; + +- (void)setXLabels:(NSArray *)xLabels withWidth:(CGFloat)width; + +/** + * Update Chart Value + */ + +- (void)updateChartData:(NSArray *)data; + + +/** + * returns the Legend View, or nil if no chart data is present. + * The origin of the legend frame is 0,0 but you can set it with setFrame:(CGRect) + * + * @param mWidth Maximum width of legend. Height will depend on this and font size + * + * @return UIView of Legend + */ +- (UIView*) getLegendWithMaxWidth:(CGFloat)mWidth; + + ++ (CGSize)sizeOfString:(NSString *)text withWidth:(float)width font:(UIFont *)font; + ++ (CGPoint)midPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2; ++ (CGPoint)controlPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNLineChart.m b/Statistics/Pods/PNChart/PNChart/PNLineChart.m new file mode 100755 index 0000000..0e4349a --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNLineChart.m @@ -0,0 +1,1084 @@ +// +// PNLineChart.m +// PNChartDemo +// +// Created by kevin on 11/7/13. +// Copyright (c) 2013年 kevinzhow. All rights reserved. +// + +#import "PNLineChart.h" +#import "PNColor.h" +#import "PNChartLabel.h" +#import "PNLineChartData.h" +#import "PNLineChartDataItem.h" +#import + +@interface PNLineChart () + +@property(nonatomic) NSMutableArray *chartLineArray; // Array[CAShapeLayer] +@property(nonatomic) NSMutableArray *chartPointArray; // Array[CAShapeLayer] save the point layer + +@property(nonatomic) NSMutableArray *chartPath; // Array of line path, one for each line. +@property(nonatomic) NSMutableArray *pointPath; // Array of point path, one for each line +@property(nonatomic) NSMutableArray *endPointsOfPath; // Array of start and end points of each line path, one for each line + +@property(nonatomic) CABasicAnimation *pathAnimation; // will be set to nil if _displayAnimation is NO + +// display grade +@property(nonatomic) NSMutableArray *gradeStringPaths; + +@end + +@implementation PNLineChart + +@synthesize pathAnimation = _pathAnimation; + +#pragma mark initialization + +- (id)initWithCoder:(NSCoder *)coder { + self = [super initWithCoder:coder]; + + if (self) { + [self setupDefaultValues]; + } + + return self; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + + if (self) { + [self setupDefaultValues]; + } + + return self; +} + + +#pragma mark instance methods + +- (void)setYLabels { + CGFloat yStep = (_yValueMax - _yValueMin) / _yLabelNum; + CGFloat yStepHeight = _chartCavanHeight / _yLabelNum; + + if (_yChartLabels) { + for (PNChartLabel *label in _yChartLabels) { + [label removeFromSuperview]; + } + } else { + _yChartLabels = [NSMutableArray new]; + } + + if (yStep == 0.0) { + PNChartLabel *minLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger) _chartCavanHeight, (NSInteger) _chartMarginBottom, (NSInteger) _yLabelHeight)]; + minLabel.text = [self formatYLabel:0.0]; + [self setCustomStyleForYLabel:minLabel]; + [self addSubview:minLabel]; + [_yChartLabels addObject:minLabel]; + + PNChartLabel *midLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger) (_chartCavanHeight / 2), (NSInteger) _chartMarginBottom, (NSInteger) _yLabelHeight)]; + midLabel.text = [self formatYLabel:_yValueMax]; + [self setCustomStyleForYLabel:midLabel]; + [self addSubview:midLabel]; + [_yChartLabels addObject:midLabel]; + + PNChartLabel *maxLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, 0.0, (NSInteger) _chartMarginBottom, (NSInteger) _yLabelHeight)]; + maxLabel.text = [self formatYLabel:_yValueMax * 2]; + [self setCustomStyleForYLabel:maxLabel]; + [self addSubview:maxLabel]; + [_yChartLabels addObject:maxLabel]; + + } else { + NSInteger index = 0; + NSInteger num = _yLabelNum + 1; + + while (num > 0) { + PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger) (_chartCavanHeight - index * yStepHeight), (NSInteger) _chartMarginBottom, (NSInteger) _yLabelHeight)]; + [label setTextAlignment:NSTextAlignmentRight]; + label.text = [self formatYLabel:_yValueMin + (yStep * index)]; + [self setCustomStyleForYLabel:label]; + [self addSubview:label]; + [_yChartLabels addObject:label]; + index += 1; + num -= 1; + } + } +} + +- (void)setYLabels:(NSArray *)yLabels { + _showGenYLabels = NO; + _yLabelNum = yLabels.count - 1; + + CGFloat yLabelHeight; + if (_showLabel) { + yLabelHeight = _chartCavanHeight / [yLabels count]; + } else { + yLabelHeight = (self.frame.size.height) / [yLabels count]; + } + + return [self setYLabels:yLabels withHeight:yLabelHeight]; +} + +- (void)setYLabels:(NSArray *)yLabels withHeight:(CGFloat)height { + _yLabels = yLabels; + _yLabelHeight = height; + if (_yChartLabels) { + for (PNChartLabel *label in _yChartLabels) { + [label removeFromSuperview]; + } + } else { + _yChartLabels = [NSMutableArray new]; + } + + NSString *labelText; + + if (_showLabel) { + CGFloat yStepHeight = _chartCavanHeight / _yLabelNum; + + for (int index = 0; index < yLabels.count; index++) { + labelText = yLabels[index]; + + NSInteger y = (NSInteger) (_chartCavanHeight - index * yStepHeight); + + PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, y, (NSInteger) _chartMarginLeft * 0.9, (NSInteger) _yLabelHeight)]; + [label setTextAlignment:NSTextAlignmentRight]; + label.text = labelText; + [self setCustomStyleForYLabel:label]; + [self addSubview:label]; + [_yChartLabels addObject:label]; + } + } +} + +- (CGFloat)computeEqualWidthForXLabels:(NSArray *)xLabels { + CGFloat xLabelWidth; + + if (_showLabel) { + xLabelWidth = _chartCavanWidth / [xLabels count]; + } else { + xLabelWidth = (self.frame.size.width) / [xLabels count]; + } + + return xLabelWidth; +} + + +- (void)setXLabels:(NSArray *)xLabels { + CGFloat xLabelWidth; + + if (_showLabel) { + xLabelWidth = _chartCavanWidth / [xLabels count]; + } else { + xLabelWidth = (self.frame.size.width - _chartMarginLeft - _chartMarginRight) / [xLabels count]; + } + + return [self setXLabels:xLabels withWidth:xLabelWidth]; +} + +- (void)setXLabels:(NSArray *)xLabels withWidth:(CGFloat)width { + _xLabels = xLabels; + _xLabelWidth = width; + if (_xChartLabels) { + for (PNChartLabel *label in _xChartLabels) { + [label removeFromSuperview]; + } + } else { + _xChartLabels = [NSMutableArray new]; + } + + NSString *labelText; + + if (_showLabel) { + for (int index = 0; index < xLabels.count; index++) { + labelText = xLabels[index]; + + NSInteger x = (index * _xLabelWidth + _chartMarginLeft + _xLabelWidth / 2.0); + NSInteger y = _chartMarginBottom + _chartCavanHeight; + + PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectMake(x, y, (NSInteger) _xLabelWidth, (NSInteger) _chartMarginBottom)]; + [label setTextAlignment:NSTextAlignmentCenter]; + label.text = labelText; + [self setCustomStyleForXLabel:label]; + [self addSubview:label]; + [_xChartLabels addObject:label]; + } + } +} + +- (void)setCustomStyleForXLabel:(UILabel *)label { + if (_xLabelFont) { + label.font = _xLabelFont; + } + + if (_xLabelColor) { + label.textColor = _xLabelColor; + } + +} + +- (void)setCustomStyleForYLabel:(UILabel *)label { + if (_yLabelFont) { + label.font = _yLabelFont; + } + + if (_yLabelColor) { + label.textColor = _yLabelColor; + } +} + +#pragma mark - Touch at point + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { + [self touchPoint:touches withEvent:event]; + [self touchKeyPoint:touches withEvent:event]; +} + +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { + [self touchPoint:touches withEvent:event]; + [self touchKeyPoint:touches withEvent:event]; +} + +- (void)touchPoint:(NSSet *)touches withEvent:(UIEvent *)event { + // Get the point user touched + UITouch *touch = [touches anyObject]; + CGPoint touchPoint = [touch locationInView:self]; + + for (NSInteger p = _pathPoints.count - 1; p >= 0; p--) { + NSArray *linePointsArray = _endPointsOfPath[p]; + + for (int i = 0; i < (int) linePointsArray.count - 1; i += 2) { + CGPoint p1 = [linePointsArray[i] CGPointValue]; + CGPoint p2 = [linePointsArray[i + 1] CGPointValue]; + + // Closest distance from point to line + float distance = fabs(((p2.x - p1.x) * (touchPoint.y - p1.y)) - ((p1.x - touchPoint.x) * (p1.y - p2.y))); + distance /= hypot(p2.x - p1.x, p1.y - p2.y); + + if (distance <= 5.0) { + // Conform to delegate parameters, figure out what bezier path this CGPoint belongs to. + for (UIBezierPath *path in _chartPath) { + BOOL pointContainsPath = CGPathContainsPoint(path.CGPath, NULL, p1, NO); + + if (pointContainsPath) { + [_delegate userClickedOnLinePoint:touchPoint lineIndex:[_chartPath indexOfObject:path]]; + + return; + } + } + } + } + } +} + +- (void)touchKeyPoint:(NSSet *)touches withEvent:(UIEvent *)event { + // Get the point user touched + UITouch *touch = [touches anyObject]; + CGPoint touchPoint = [touch locationInView:self]; + + for (NSInteger p = _pathPoints.count - 1; p >= 0; p--) { + NSArray *linePointsArray = _pathPoints[p]; + + for (int i = 0; i < (int) linePointsArray.count - 1; i += 1) { + CGPoint p1 = [linePointsArray[i] CGPointValue]; + CGPoint p2 = [linePointsArray[i + 1] CGPointValue]; + + float distanceToP1 = fabs(hypot(touchPoint.x - p1.x, touchPoint.y - p1.y)); + float distanceToP2 = hypot(touchPoint.x - p2.x, touchPoint.y - p2.y); + + float distance = MIN(distanceToP1, distanceToP2); + + if (distance <= 10.0) { + [_delegate userClickedOnLineKeyPoint:touchPoint + lineIndex:p + pointIndex:(distance == distanceToP2 ? i + 1 : i)]; + + return; + } + } + } +} + +#pragma mark - Draw Chart + +- (void)strokeChart { + _chartPath = [[NSMutableArray alloc] init]; + _pointPath = [[NSMutableArray alloc] init]; + _gradeStringPaths = [NSMutableArray array]; + + [self calculateChartPath:_chartPath andPointsPath:_pointPath andPathKeyPoints:_pathPoints andPathStartEndPoints:_endPointsOfPath]; + // Draw each line + for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) { + PNLineChartData *chartData = self.chartData[lineIndex]; + CAShapeLayer *chartLine = (CAShapeLayer *) self.chartLineArray[lineIndex]; + CAShapeLayer *pointLayer = (CAShapeLayer *) self.chartPointArray[lineIndex]; + UIGraphicsBeginImageContext(self.frame.size); + // setup the color of the chart line + if (chartData.color) { + chartLine.strokeColor = [[chartData.color colorWithAlphaComponent:chartData.alpha] CGColor]; + if (chartData.inflexionPointColor) { + pointLayer.strokeColor = [[chartData.inflexionPointColor + colorWithAlphaComponent:chartData.alpha] CGColor]; + } + } else { + chartLine.strokeColor = [PNGreen CGColor]; + pointLayer.strokeColor = [PNGreen CGColor]; + } + + UIBezierPath *progressline = [_chartPath objectAtIndex:lineIndex]; + UIBezierPath *pointPath = [_pointPath objectAtIndex:lineIndex]; + + chartLine.path = progressline.CGPath; + pointLayer.path = pointPath.CGPath; + + [CATransaction begin]; + + [chartLine addAnimation:self.pathAnimation forKey:@"strokeEndAnimation"]; + chartLine.strokeEnd = 1.0; + + // if you want cancel the point animation, conment this code, the point will show immediately + if (chartData.inflexionPointStyle != PNLineChartPointStyleNone) { + [pointLayer addAnimation:self.pathAnimation forKey:@"strokeEndAnimation"]; + } + + [CATransaction commit]; + + NSMutableArray *textLayerArray = [self.gradeStringPaths objectAtIndex:lineIndex]; + for (CATextLayer *textLayer in textLayerArray) { + CABasicAnimation *fadeAnimation = [self fadeAnimation]; + [textLayer addAnimation:fadeAnimation forKey:nil]; + } + + UIGraphicsEndImageContext(); + } +} + + +- (void)calculateChartPath:(NSMutableArray *)chartPath andPointsPath:(NSMutableArray *)pointsPath andPathKeyPoints:(NSMutableArray *)pathPoints andPathStartEndPoints:(NSMutableArray *)pointsOfPath { + + // Draw each line + for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) { + PNLineChartData *chartData = self.chartData[lineIndex]; + + CGFloat yValue; + CGFloat innerGrade; + + UIBezierPath *progressline = [UIBezierPath bezierPath]; + + UIBezierPath *pointPath = [UIBezierPath bezierPath]; + + + [chartPath insertObject:progressline atIndex:lineIndex]; + [pointsPath insertObject:pointPath atIndex:lineIndex]; + + + NSMutableArray *gradePathArray = [NSMutableArray array]; + [self.gradeStringPaths addObject:gradePathArray]; + + NSMutableArray *linePointsArray = [[NSMutableArray alloc] init]; + NSMutableArray *lineStartEndPointsArray = [[NSMutableArray alloc] init]; + int last_x = 0; + int last_y = 0; + NSMutableArray *> *progrssLinePaths = [NSMutableArray new]; + CGFloat inflexionWidth = chartData.inflexionPointWidth; + + for (NSUInteger i = 0; i < chartData.itemCount; i++) { + + yValue = chartData.getData(i).y; + + if (!(_yValueMax - _yValueMin)) { + innerGrade = 0.5; + } else { + innerGrade = (yValue - _yValueMin) / (_yValueMax - _yValueMin); + } + + int x = i * _xLabelWidth + _chartMarginLeft + _xLabelWidth / 2.0; + + int y = _chartCavanHeight - (innerGrade * _chartCavanHeight) + (_yLabelHeight / 2) + _chartMarginTop - _chartMarginBottom; + + // Circular point + if (chartData.inflexionPointStyle == PNLineChartPointStyleCircle) { + + CGRect circleRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth); + CGPoint circleCenter = CGPointMake(circleRect.origin.x + (circleRect.size.width / 2), circleRect.origin.y + (circleRect.size.height / 2)); + + [pointPath moveToPoint:CGPointMake(circleCenter.x + (inflexionWidth / 2), circleCenter.y)]; + [pointPath addArcWithCenter:circleCenter radius:inflexionWidth / 2 startAngle:0 endAngle:2 * M_PI clockwise:YES]; + + //jet text display text + if (chartData.showPointLabel) { + [gradePathArray addObject:[self createPointLabelFor:chartData.getData(i).rawY pointCenter:circleCenter width:inflexionWidth withChartData:chartData]]; + } + + if (i > 0) { + + // calculate the point for line + float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2)); + float last_x1 = last_x + (inflexionWidth / 2) / distance * (x - last_x); + float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y); + float x1 = x - (inflexionWidth / 2) / distance * (x - last_x); + float y1 = y - (inflexionWidth / 2) / distance * (y - last_y); + + [progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)], + @"to" : [NSValue valueWithCGPoint:CGPointMake(x1, y1)]}]; + } + } + // Square point + else if (chartData.inflexionPointStyle == PNLineChartPointStyleSquare) { + + CGRect squareRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth); + CGPoint squareCenter = CGPointMake(squareRect.origin.x + (squareRect.size.width / 2), squareRect.origin.y + (squareRect.size.height / 2)); + + [pointPath moveToPoint:CGPointMake(squareCenter.x - (inflexionWidth / 2), squareCenter.y - (inflexionWidth / 2))]; + [pointPath addLineToPoint:CGPointMake(squareCenter.x + (inflexionWidth / 2), squareCenter.y - (inflexionWidth / 2))]; + [pointPath addLineToPoint:CGPointMake(squareCenter.x + (inflexionWidth / 2), squareCenter.y + (inflexionWidth / 2))]; + [pointPath addLineToPoint:CGPointMake(squareCenter.x - (inflexionWidth / 2), squareCenter.y + (inflexionWidth / 2))]; + [pointPath closePath]; + + // text display text + if (chartData.showPointLabel) { + [gradePathArray addObject:[self createPointLabelFor:chartData.getData(i).rawY pointCenter:squareCenter width:inflexionWidth withChartData:chartData]]; + } + + if (i > 0) { + + // calculate the point for line + float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2)); + float last_x1 = last_x + (inflexionWidth / 2); + float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y); + float x1 = x - (inflexionWidth / 2); + float y1 = y - (inflexionWidth / 2) / distance * (y - last_y); + + [progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)], + @"to" : [NSValue valueWithCGPoint:CGPointMake(x1, y1)]}]; + } + } + // Triangle point + else if (chartData.inflexionPointStyle == PNLineChartPointStyleTriangle) { + + CGRect squareRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth); + + CGPoint startPoint = CGPointMake(squareRect.origin.x, squareRect.origin.y + squareRect.size.height); + CGPoint endPoint = CGPointMake(squareRect.origin.x + (squareRect.size.width / 2), squareRect.origin.y); + CGPoint middlePoint = CGPointMake(squareRect.origin.x + (squareRect.size.width), squareRect.origin.y + squareRect.size.height); + + [pointPath moveToPoint:startPoint]; + [pointPath addLineToPoint:middlePoint]; + [pointPath addLineToPoint:endPoint]; + [pointPath closePath]; + + // text display text + if (chartData.showPointLabel) { + [gradePathArray addObject:[self createPointLabelFor:chartData.getData(i).rawY pointCenter:middlePoint width:inflexionWidth withChartData:chartData]]; + } + + if (i > 0) { + // calculate the point for triangle + float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2)) * 1.4; + float last_x1 = last_x + (inflexionWidth / 2) / distance * (x - last_x); + float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y); + float x1 = x - (inflexionWidth / 2) / distance * (x - last_x); + float y1 = y - (inflexionWidth / 2) / distance * (y - last_y); + + [progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)], + @"to" : [NSValue valueWithCGPoint:CGPointMake(x1, y1)]}]; + } + } else { + + if (i > 0) { + [progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x, last_y)], + @"to" : [NSValue valueWithCGPoint:CGPointMake(x, y)]}]; + } + } + [linePointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]]; + last_x = x; + last_y = y; + } + + if (self.showSmoothLines && chartData.itemCount >= 4) { + [progressline moveToPoint:[progrssLinePaths[0][@"from"] CGPointValue]]; + for (NSDictionary *item in progrssLinePaths) { + CGPoint p1 = [item[@"from"] CGPointValue]; + CGPoint p2 = [item[@"to"] CGPointValue]; + [progressline moveToPoint:p1]; + CGPoint midPoint = [PNLineChart midPointBetweenPoint1:p1 andPoint2:p2]; + [progressline addQuadCurveToPoint:midPoint + controlPoint:[PNLineChart controlPointBetweenPoint1:midPoint andPoint2:p1]]; + [progressline addQuadCurveToPoint:p2 + controlPoint:[PNLineChart controlPointBetweenPoint1:midPoint andPoint2:p2]]; + } + } else { + for (NSDictionary *item in progrssLinePaths) { + if (item[@"from"]) { + [progressline moveToPoint:[item[@"from"] CGPointValue]]; + [lineStartEndPointsArray addObject:item[@"from"]]; + } + if (item[@"to"]) { + [progressline addLineToPoint:[item[@"to"] CGPointValue]]; + [lineStartEndPointsArray addObject:item[@"to"]]; + } + } + } + [pathPoints addObject:[linePointsArray copy]]; + [pointsOfPath addObject:[lineStartEndPointsArray copy]]; + } +} + +#pragma mark - Set Chart Data + +- (void)setChartData:(NSArray *)data { + if (data != _chartData) { + + // remove all shape layers before adding new ones + for (CALayer *layer in self.chartLineArray) { + [layer removeFromSuperlayer]; + } + for (CALayer *layer in self.chartPointArray) { + [layer removeFromSuperlayer]; + } + + self.chartLineArray = [NSMutableArray arrayWithCapacity:data.count]; + self.chartPointArray = [NSMutableArray arrayWithCapacity:data.count]; + + for (PNLineChartData *chartData in data) { + // create as many chart line layers as there are data-lines + CAShapeLayer *chartLine = [CAShapeLayer layer]; + chartLine.lineCap = kCALineCapButt; + chartLine.lineJoin = kCALineJoinMiter; + chartLine.fillColor = [[UIColor whiteColor] CGColor]; + chartLine.lineWidth = chartData.lineWidth; + chartLine.strokeEnd = 0.0; + [self.layer addSublayer:chartLine]; + [self.chartLineArray addObject:chartLine]; + + // create point + CAShapeLayer *pointLayer = [CAShapeLayer layer]; + pointLayer.strokeColor = [[chartData.color colorWithAlphaComponent:chartData.alpha] CGColor]; + pointLayer.lineCap = kCALineCapRound; + pointLayer.lineJoin = kCALineJoinBevel; + pointLayer.fillColor = nil; + pointLayer.lineWidth = chartData.lineWidth; + [self.layer addSublayer:pointLayer]; + [self.chartPointArray addObject:pointLayer]; + } + + _chartData = data; + + [self prepareYLabelsWithData:data]; + // Cavan height and width needs to be set before + // setNeedsDisplay is invoked because setNeedsDisplay + // will invoke drawRect and if Cavan dimensions is not + // set the chart will be misplaced + if (!_showLabel) { + _chartCavanHeight = self.frame.size.height - 2 * _yLabelHeight; + _chartCavanWidth = self.frame.size.width; + //_chartMargin = chartData.inflexionPointWidth; + _xLabelWidth = (_chartCavanWidth / ([_xLabels count])); + } + [self setNeedsDisplay]; + } +} + +- (void)prepareYLabelsWithData:(NSArray *)data { + CGFloat yMax = 0.0f; + CGFloat yMin = MAXFLOAT; + NSMutableArray *yLabelsArray = [NSMutableArray new]; + + for (PNLineChartData *chartData in data) { + // create as many chart line layers as there are data-lines + + for (NSUInteger i = 0; i < chartData.itemCount; i++) { + CGFloat yValue = chartData.getData(i).y; + [yLabelsArray addObject:[NSString stringWithFormat:@"%2f", yValue]]; + yMax = fmaxf(yMax, yValue); + yMin = fminf(yMin, yValue); + } + } + + + // Min value for Y label + if (yMax < 5) { + yMax = 5.0f; + } + + _yValueMin = (_yFixedValueMin > -FLT_MAX) ? _yFixedValueMin : yMin; + _yValueMax = (_yFixedValueMax > -FLT_MAX) ? _yFixedValueMax : yMax + yMax / 10.0; + + if (_showGenYLabels) { + [self setYLabels]; + } + +} + +#pragma mark - Update Chart Data + +- (void)updateChartData:(NSArray *)data { + _chartData = data; + + [self prepareYLabelsWithData:data]; + + [self calculateChartPath:_chartPath andPointsPath:_pointPath andPathKeyPoints:_pathPoints andPathStartEndPoints:_endPointsOfPath]; + + for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) { + + CAShapeLayer *chartLine = (CAShapeLayer *) self.chartLineArray[lineIndex]; + CAShapeLayer *pointLayer = (CAShapeLayer *) self.chartPointArray[lineIndex]; + + + UIBezierPath *progressline = [_chartPath objectAtIndex:lineIndex]; + UIBezierPath *pointPath = [_pointPath objectAtIndex:lineIndex]; + + + CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"]; + pathAnimation.fromValue = (id) chartLine.path; + pathAnimation.toValue = (id) [progressline CGPath]; + pathAnimation.duration = 0.5f; + pathAnimation.autoreverses = NO; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + [chartLine addAnimation:pathAnimation forKey:@"animationKey"]; + + + CABasicAnimation *pointPathAnimation = [CABasicAnimation animationWithKeyPath:@"path"]; + pointPathAnimation.fromValue = (id) pointLayer.path; + pointPathAnimation.toValue = (id) [pointPath CGPath]; + pointPathAnimation.duration = 0.5f; + pointPathAnimation.autoreverses = NO; + pointPathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + [pointLayer addAnimation:pointPathAnimation forKey:@"animationKey"]; + + chartLine.path = progressline.CGPath; + pointLayer.path = pointPath.CGPath; + + + } + +} + +#define IOS7_OR_LATER [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 + +- (void)drawRect:(CGRect)rect { + if (self.isShowCoordinateAxis) { + CGFloat yAxisOffset = 10.f; + + CGContextRef ctx = UIGraphicsGetCurrentContext(); + UIGraphicsPushContext(ctx); + CGContextSetLineWidth(ctx, self.axisWidth); + CGContextSetStrokeColorWithColor(ctx, [self.axisColor CGColor]); + + CGFloat xAxisWidth = CGRectGetWidth(rect) - (_chartMarginLeft + _chartMarginRight) / 2; + CGFloat yAxisHeight = _chartMarginBottom + _chartCavanHeight; + + // draw coordinate axis + CGContextMoveToPoint(ctx, _chartMarginBottom + yAxisOffset, 0); + CGContextAddLineToPoint(ctx, _chartMarginBottom + yAxisOffset, yAxisHeight); + CGContextAddLineToPoint(ctx, xAxisWidth, yAxisHeight); + CGContextStrokePath(ctx); + + // draw y axis arrow + CGContextMoveToPoint(ctx, _chartMarginBottom + yAxisOffset - 3, 6); + CGContextAddLineToPoint(ctx, _chartMarginBottom + yAxisOffset, 0); + CGContextAddLineToPoint(ctx, _chartMarginBottom + yAxisOffset + 3, 6); + CGContextStrokePath(ctx); + + // draw x axis arrow + CGContextMoveToPoint(ctx, xAxisWidth - 6, yAxisHeight - 3); + CGContextAddLineToPoint(ctx, xAxisWidth, yAxisHeight); + CGContextAddLineToPoint(ctx, xAxisWidth - 6, yAxisHeight + 3); + CGContextStrokePath(ctx); + + if (self.showLabel) { + + // draw x axis separator + CGPoint point; + for (NSUInteger i = 0; i < [self.xLabels count]; i++) { + point = CGPointMake(2 * _chartMarginLeft + (i * _xLabelWidth), _chartMarginBottom + _chartCavanHeight); + CGContextMoveToPoint(ctx, point.x, point.y - 2); + CGContextAddLineToPoint(ctx, point.x, point.y); + CGContextStrokePath(ctx); + } + + // draw y axis separator + CGFloat yStepHeight = _chartCavanHeight / _yLabelNum; + for (NSUInteger i = 0; i < [self.xLabels count]; i++) { + point = CGPointMake(_chartMarginBottom + yAxisOffset, (_chartCavanHeight - i * yStepHeight + _yLabelHeight / 2)); + CGContextMoveToPoint(ctx, point.x, point.y); + CGContextAddLineToPoint(ctx, point.x + 2, point.y); + CGContextStrokePath(ctx); + } + } + + UIFont *font = [UIFont systemFontOfSize:11]; + + // draw y unit + if ([self.yUnit length]) { + CGFloat height = [PNLineChart sizeOfString:self.yUnit withWidth:30.f font:font].height; + CGRect drawRect = CGRectMake(_chartMarginLeft + 10 + 5, 0, 30.f, height); + [self drawTextInContext:ctx text:self.yUnit inRect:drawRect font:font]; + } + + // draw x unit + if ([self.xUnit length]) { + CGFloat height = [PNLineChart sizeOfString:self.xUnit withWidth:30.f font:font].height; + CGRect drawRect = CGRectMake(CGRectGetWidth(rect) - _chartMarginLeft + 5, _chartMarginBottom + _chartCavanHeight - height / 2, 25.f, height); + [self drawTextInContext:ctx text:self.xUnit inRect:drawRect font:font]; + } + } + if (self.showYGridLines) { + CGContextRef ctx = UIGraphicsGetCurrentContext(); + CGFloat yAxisOffset = _showLabel ? 10.f : 0.0f; + CGPoint point; + CGFloat yStepHeight = _chartCavanHeight / _yLabelNum; + if (self.yGridLinesColor) { + CGContextSetStrokeColorWithColor(ctx, self.yGridLinesColor.CGColor); + } else { + CGContextSetStrokeColorWithColor(ctx, [UIColor lightGrayColor].CGColor); + } + for (NSUInteger i = 0; i < _yLabelNum; i++) { + point = CGPointMake(_chartMarginLeft + yAxisOffset, (_chartCavanHeight - i * yStepHeight + _yLabelHeight / 2)); + CGContextMoveToPoint(ctx, point.x, point.y); + // add dotted style grid + CGFloat dash[] = {6, 5}; + // dot diameter is 20 points + CGContextSetLineWidth(ctx, 0.5); + CGContextSetLineCap(ctx, kCGLineCapRound); + CGContextSetLineDash(ctx, 0.0, dash, 2); + CGContextAddLineToPoint(ctx, CGRectGetWidth(rect) - _chartMarginLeft + 5, point.y); + CGContextStrokePath(ctx); + } + } + + [super drawRect:rect]; +} + +#pragma mark private methods + +- (void)setupDefaultValues { + [super setupDefaultValues]; + // Initialization code + self.backgroundColor = [UIColor whiteColor]; + self.clipsToBounds = YES; + self.chartLineArray = [NSMutableArray new]; + _showLabel = YES; + _showGenYLabels = YES; + _pathPoints = [[NSMutableArray alloc] init]; + _endPointsOfPath = [[NSMutableArray alloc] init]; + self.userInteractionEnabled = YES; + + _yFixedValueMin = -FLT_MAX; + _yFixedValueMax = -FLT_MAX; + _yLabelNum = 5.0; + _yLabelHeight = [[[[PNChartLabel alloc] init] font] pointSize]; + +// _chartMargin = 40; + + _chartMarginLeft = 25.0; + _chartMarginRight = 25.0; + _chartMarginTop = 25.0; + _chartMarginBottom = 25.0; + + _yLabelFormat = @"%1.f"; + + _chartCavanWidth = self.frame.size.width - _chartMarginLeft - _chartMarginRight; + _chartCavanHeight = self.frame.size.height - _chartMarginBottom - _chartMarginTop; + + // Coordinate Axis Default Values + _showCoordinateAxis = NO; + _axisColor = [UIColor colorWithRed:0.4f green:0.4f blue:0.4f alpha:1.f]; + _axisWidth = 1.f; + + // do not create curved line chart by default + _showSmoothLines = NO; + +} + +#pragma mark - tools + ++ (CGSize)sizeOfString:(NSString *)text withWidth:(float)width font:(UIFont *)font { + CGSize size = CGSizeMake(width, MAXFLOAT); + + if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) { + NSDictionary *tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]; + size = [text boundingRectWithSize:size + options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading + attributes:tdic + context:nil].size; + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping]; +#pragma clang diagnostic pop + } + + return size; +} + ++ (CGPoint)midPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 { + return CGPointMake((point1.x + point2.x) / 2, (point1.y + point2.y) / 2); +} + ++ (CGPoint)controlPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 { + CGPoint controlPoint = [self midPointBetweenPoint1:point1 andPoint2:point2]; + CGFloat diffY = abs((int) (point2.y - controlPoint.y)); + if (point1.y < point2.y) + controlPoint.y += diffY; + else if (point1.y > point2.y) + controlPoint.y -= diffY; + return controlPoint; +} + +- (void)drawTextInContext:(CGContextRef)ctx text:(NSString *)text inRect:(CGRect)rect font:(UIFont *)font { + if (IOS7_OR_LATER) { + NSMutableParagraphStyle *priceParagraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; + priceParagraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; + priceParagraphStyle.alignment = NSTextAlignmentLeft; + + [text drawInRect:rect + withAttributes:@{NSParagraphStyleAttributeName : priceParagraphStyle, NSFontAttributeName : font}]; + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [text drawInRect:rect + withFont:font + lineBreakMode:NSLineBreakByTruncatingTail + alignment:NSTextAlignmentLeft]; +#pragma clang diagnostic pop + } +} + +- (NSString *)formatYLabel:(double)value { + + if (self.yLabelBlockFormatter) { + return self.yLabelBlockFormatter(value); + } + else { + if (!self.thousandsSeparator) { + NSString *format = self.yLabelFormat ?: @"%1.f"; + return [NSString stringWithFormat:format, value]; + } + + NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; + [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; + [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; + return [numberFormatter stringFromNumber:[NSNumber numberWithDouble:value]]; + } +} + +- (UIView *)getLegendWithMaxWidth:(CGFloat)mWidth { + if ([self.chartData count] < 1) { + return nil; + } + + /* This is a short line that refers to the chart data */ + CGFloat legendLineWidth = 40; + + /* x and y are the coordinates of the starting point of each legend item */ + CGFloat x = 0; + CGFloat y = 0; + + /* accumulated height */ + CGFloat totalHeight = 0; + CGFloat totalWidth = 0; + + NSMutableArray *legendViews = [[NSMutableArray alloc] init]; + + /* Determine the max width of each legend item */ + CGFloat maxLabelWidth; + if (self.legendStyle == PNLegendItemStyleStacked) { + maxLabelWidth = mWidth - legendLineWidth; + } else { + maxLabelWidth = MAXFLOAT; + } + + /* this is used when labels wrap text and the line + * should be in the middle of the first row */ + CGFloat singleRowHeight = [PNLineChart sizeOfString:@"Test" + withWidth:MAXFLOAT + font:self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]].height; + + NSUInteger counter = 0; + NSUInteger rowWidth = 0; + NSUInteger rowMaxHeight = 0; + + for (PNLineChartData *pdata in self.chartData) { + /* Expected label size*/ + CGSize labelsize = [PNLineChart sizeOfString:pdata.dataTitle + withWidth:maxLabelWidth + font:self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]]; + + /* draw lines */ + if ((rowWidth + labelsize.width + legendLineWidth > mWidth) && (self.legendStyle == PNLegendItemStyleSerial)) { + rowWidth = 0; + x = 0; + y += rowMaxHeight; + rowMaxHeight = 0; + } + rowWidth += labelsize.width + legendLineWidth; + totalWidth = self.legendStyle == PNLegendItemStyleSerial ? fmaxf(rowWidth, totalWidth) : fmaxf(totalWidth, labelsize.width + legendLineWidth); + + /* If there is inflection decorator, the line is composed of two lines + * and this is the space that separates two lines in order to put inflection + * decorator */ + + CGFloat inflexionWidthSpacer = pdata.inflexionPointStyle == PNLineChartPointStyleTriangle ? pdata.inflexionPointWidth / 2 : pdata.inflexionPointWidth; + + CGFloat halfLineLength; + + if (pdata.inflexionPointStyle != PNLineChartPointStyleNone) { + halfLineLength = (legendLineWidth * 0.8 - inflexionWidthSpacer) / 2; + } else { + halfLineLength = legendLineWidth * 0.8; + } + + UIView *line = [[UIView alloc] initWithFrame:CGRectMake(x + legendLineWidth * 0.1, y + (singleRowHeight - pdata.lineWidth) / 2, halfLineLength, pdata.lineWidth)]; + + line.backgroundColor = pdata.color; + line.alpha = pdata.alpha; + [legendViews addObject:line]; + + if (pdata.inflexionPointStyle != PNLineChartPointStyleNone) { + line = [[UIView alloc] initWithFrame:CGRectMake(x + legendLineWidth * 0.1 + halfLineLength + inflexionWidthSpacer, y + (singleRowHeight - pdata.lineWidth) / 2, halfLineLength, pdata.lineWidth)]; + line.backgroundColor = pdata.color; + line.alpha = pdata.alpha; + [legendViews addObject:line]; + } + + // Add inflexion type + UIColor *inflexionPointColor = pdata.inflexionPointColor; + if (!inflexionPointColor) { + inflexionPointColor = pdata.color; + } + [legendViews addObject:[self drawInflexion:pdata.inflexionPointWidth + center:CGPointMake(x + legendLineWidth / 2, y + singleRowHeight / 2) + strokeWidth:pdata.lineWidth + inflexionStyle:pdata.inflexionPointStyle + andColor:inflexionPointColor + andAlpha:pdata.alpha]]; + + UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x + legendLineWidth, y, labelsize.width, labelsize.height)]; + label.text = pdata.dataTitle; + label.textColor = self.legendFontColor ? self.legendFontColor : [UIColor blackColor]; + label.font = self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]; + label.lineBreakMode = NSLineBreakByWordWrapping; + label.numberOfLines = 0; + + rowMaxHeight = fmaxf(rowMaxHeight, labelsize.height); + x += self.legendStyle == PNLegendItemStyleStacked ? 0 : labelsize.width + legendLineWidth; + y += self.legendStyle == PNLegendItemStyleStacked ? labelsize.height : 0; + + + totalHeight = self.legendStyle == PNLegendItemStyleSerial ? fmaxf(totalHeight, rowMaxHeight + y) : totalHeight + labelsize.height; + + [legendViews addObject:label]; + counter++; + } + + UIView *legend = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mWidth, totalHeight)]; + + for (UIView *v in legendViews) { + [legend addSubview:v]; + } + return legend; +} + + +- (UIImageView *)drawInflexion:(CGFloat)size center:(CGPoint)center strokeWidth:(CGFloat)sw inflexionStyle:(PNLineChartPointStyle)type andColor:(UIColor *)color andAlpha:(CGFloat)alfa { + //Make the size a little bigger so it includes also border stroke + CGSize aSize = CGSizeMake(size + sw, size + sw); + + + UIGraphicsBeginImageContextWithOptions(aSize, NO, 0.0); + CGContextRef context = UIGraphicsGetCurrentContext(); + + + if (type == PNLineChartPointStyleCircle) { + CGContextAddArc(context, (size + sw) / 2, (size + sw) / 2, size / 2, 0, M_PI * 2, YES); + } else if (type == PNLineChartPointStyleSquare) { + CGContextAddRect(context, CGRectMake(sw / 2, sw / 2, size, size)); + } else if (type == PNLineChartPointStyleTriangle) { + CGContextMoveToPoint(context, sw / 2, size + sw / 2); + CGContextAddLineToPoint(context, size + sw / 2, size + sw / 2); + CGContextAddLineToPoint(context, size / 2 + sw / 2, sw / 2); + CGContextAddLineToPoint(context, sw / 2, size + sw / 2); + CGContextClosePath(context); + } + + //Set some stroke properties + CGContextSetLineWidth(context, sw); + CGContextSetAlpha(context, alfa); + CGContextSetStrokeColorWithColor(context, color.CGColor); + + //Finally draw + CGContextDrawPath(context, kCGPathStroke); + + //now get the image from the context + UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext(); + + UIGraphicsEndImageContext(); + + //// Translate origin + CGFloat originX = center.x - (size + sw) / 2.0; + CGFloat originY = center.y - (size + sw) / 2.0; + + UIImageView *squareImageView = [[UIImageView alloc] initWithImage:squareImage]; + [squareImageView setFrame:CGRectMake(originX, originY, size + sw, size + sw)]; + return squareImageView; +} + +#pragma mark setter and getter + +- (CATextLayer *)createPointLabelFor:(CGFloat)grade pointCenter:(CGPoint)pointCenter width:(CGFloat)width withChartData:(PNLineChartData *)chartData { + CATextLayer *textLayer = [[CATextLayer alloc] init]; + [textLayer setAlignmentMode:kCAAlignmentCenter]; + [textLayer setForegroundColor:[chartData.pointLabelColor CGColor]]; + [textLayer setBackgroundColor:[[[UIColor whiteColor] colorWithAlphaComponent:0.8] CGColor]]; + [textLayer setCornerRadius:textLayer.fontSize / 8.0]; + + if (chartData.pointLabelFont != nil) { + [textLayer setFont:(__bridge CFTypeRef) (chartData.pointLabelFont)]; + textLayer.fontSize = [chartData.pointLabelFont pointSize]; + } + + CGFloat textHeight = textLayer.fontSize * 1.1; + CGFloat textWidth = width * 8; + CGFloat textStartPosY; + + textStartPosY = pointCenter.y - textLayer.fontSize; + + [self.layer addSublayer:textLayer]; + + if (chartData.pointLabelFormat != nil) { + [textLayer setString:[[NSString alloc] initWithFormat:chartData.pointLabelFormat, grade]]; + } else { + [textLayer setString:[[NSString alloc] initWithFormat:_yLabelFormat, grade]]; + } + + [textLayer setFrame:CGRectMake(0, 0, textWidth, textHeight)]; + [textLayer setPosition:CGPointMake(pointCenter.x, textStartPosY)]; + textLayer.contentsScale = [UIScreen mainScreen].scale; + + return textLayer; +} + +- (CABasicAnimation *)fadeAnimation { + CABasicAnimation *fadeAnimation = nil; + if (self.displayAnimated) { + fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; + fadeAnimation.fromValue = [NSNumber numberWithFloat:0.0]; + fadeAnimation.toValue = [NSNumber numberWithFloat:1.0]; + fadeAnimation.duration = 2.0; + } + return fadeAnimation; +} + +- (CABasicAnimation *)pathAnimation { + if (self.displayAnimated && !_pathAnimation) { + _pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + _pathAnimation.duration = 1.0; + _pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + _pathAnimation.fromValue = @0.0f; + _pathAnimation.toValue = @1.0f; + } + return _pathAnimation; +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNLineChartData.h b/Statistics/Pods/PNChart/PNChart/PNLineChartData.h new file mode 100755 index 0000000..fc85a56 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNLineChartData.h @@ -0,0 +1,44 @@ +// +// Created by Jörg Polakowski on 14/12/13. +// Copyright (c) 2013 kevinzhow. All rights reserved. +// + +#import +#import + +typedef NS_ENUM(NSUInteger, PNLineChartPointStyle) { + PNLineChartPointStyleNone = 0, + PNLineChartPointStyleCircle = 1, + PNLineChartPointStyleSquare = 3, + PNLineChartPointStyleTriangle = 4 +}; + +@class PNLineChartDataItem; + +typedef PNLineChartDataItem *(^LCLineChartDataGetter)(NSUInteger item); + +@interface PNLineChartData : NSObject + +@property (strong) UIColor *color; +@property (nonatomic) CGFloat alpha; +@property NSUInteger itemCount; +@property (copy) LCLineChartDataGetter getData; +@property (strong, nonatomic) NSString *dataTitle; + +@property (nonatomic) BOOL showPointLabel; +@property (nonatomic) UIColor *pointLabelColor; +@property (nonatomic) UIFont *pointLabelFont; +@property (nonatomic) NSString *pointLabelFormat; + +@property (nonatomic, assign) PNLineChartPointStyle inflexionPointStyle; +@property (nonatomic) UIColor *inflexionPointColor; + +/** + * If PNLineChartPointStyle is circle, this returns the circle's diameter. + * If PNLineChartPointStyle is square, each point is a square with each side equal in length to this value. + */ +@property (nonatomic, assign) CGFloat inflexionPointWidth; + +@property (nonatomic, assign) CGFloat lineWidth; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNLineChartData.m b/Statistics/Pods/PNChart/PNChart/PNLineChartData.m new file mode 100755 index 0000000..6b697c7 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNLineChartData.m @@ -0,0 +1,31 @@ +// +// Created by Jörg Polakowski on 14/12/13. +// Copyright (c) 2013 kevinzhow. All rights reserved. +// + +#import "PNLineChartData.h" + +@implementation PNLineChartData + +- (id)init +{ + self = [super init]; + if (self) { + [self setupDefaultValues]; + } + + return self; +} + +- (void)setupDefaultValues +{ + _inflexionPointStyle = PNLineChartPointStyleNone; + _inflexionPointWidth = 6.f; + _lineWidth = 2.f; + _alpha = 1.f; + _showPointLabel = NO; + _pointLabelColor = [UIColor blackColor]; + _pointLabelFormat = @"%1.f"; +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNLineChartDataItem.h b/Statistics/Pods/PNChart/PNChart/PNLineChartDataItem.h new file mode 100755 index 0000000..ad2d23d --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNLineChartDataItem.h @@ -0,0 +1,17 @@ +// +// Created by Jörg Polakowski on 14/12/13. +// Copyright (c) 2013 kevinzhow. All rights reserved. +// + +#import +#import + +@interface PNLineChartDataItem : NSObject + ++ (PNLineChartDataItem *)dataItemWithY:(CGFloat)y; ++ (PNLineChartDataItem *)dataItemWithY:(CGFloat)y andRawY:(CGFloat)rawY; + +@property (readonly) CGFloat y; // should be within the y range +@property (readonly) CGFloat rawY; // this is the raw value, used for point label. + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNLineChartDataItem.m b/Statistics/Pods/PNChart/PNChart/PNLineChartDataItem.m new file mode 100755 index 0000000..1beea91 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNLineChartDataItem.m @@ -0,0 +1,38 @@ +// +// Created by Jörg Polakowski on 14/12/13. +// Copyright (c) 2013 kevinzhow. All rights reserved. +// + +#import "PNLineChartDataItem.h" + +@interface PNLineChartDataItem () + +- (id)initWithY:(CGFloat)y andRawY:(CGFloat)rawY; + +@property (readwrite) CGFloat y; // should be within the y range +@property (readwrite) CGFloat rawY; // this is the raw value, used for point label. + +@end + +@implementation PNLineChartDataItem + ++ (PNLineChartDataItem *)dataItemWithY:(CGFloat)y +{ + return [[PNLineChartDataItem alloc] initWithY:y andRawY:y]; +} + ++ (PNLineChartDataItem *)dataItemWithY:(CGFloat)y andRawY:(CGFloat)rawY { + return [[PNLineChartDataItem alloc] initWithY:y andRawY:rawY]; +} + +- (id)initWithY:(CGFloat)y andRawY:(CGFloat)rawY +{ + if ((self = [super init])) { + self.y = y; + self.rawY = rawY; + } + + return self; +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNPieChart.h b/Statistics/Pods/PNChart/PNChart/PNPieChart.h new file mode 100644 index 0000000..204afb5 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNPieChart.h @@ -0,0 +1,68 @@ +// +// PNPieChart.h +// PNChartDemo +// +// Created by Hang Zhang on 14-5-5. +// Copyright (c) 2014年 kevinzhow. All rights reserved. +// + +#import +#import "PNPieChartDataItem.h" +#import "PNGenericChart.h" +#import "PNChartDelegate.h" + +@interface PNPieChart : PNGenericChart + +- (id)initWithFrame:(CGRect)frame items:(NSArray *)items; + +@property (nonatomic, readonly) NSArray *items; + +/** Default is 18-point Avenir Medium. */ +@property (nonatomic) UIFont *descriptionTextFont; + +/** Default is white. */ +@property (nonatomic) UIColor *descriptionTextColor; + +/** Default is black, with an alpha of 0.4. */ +@property (nonatomic) UIColor *descriptionTextShadowColor; + +/** Default is CGSizeMake(0, 1). */ +@property (nonatomic) CGSize descriptionTextShadowOffset; + +/** Default is 1.0. */ +@property (nonatomic) NSTimeInterval duration; + +/** Show only values, this is useful when legend is present */ +@property (nonatomic) BOOL showOnlyValues; + +/** Show absolute values not relative i.e. percentages */ +@property (nonatomic) BOOL showAbsoluteValues; + +/** Hide percentage labels less than cutoff value */ +@property (nonatomic, assign) CGFloat labelPercentageCutoff; + +/** Default YES. */ +@property (nonatomic) BOOL shouldHighlightSectorOnTouch; + +/** Current outer radius. Override recompute() to change this. **/ +@property (nonatomic) CGFloat outerCircleRadius; + +/** Current inner radius. Override recompute() to change this. **/ +@property (nonatomic) CGFloat innerCircleRadius; + +@property (nonatomic, weak) id delegate; + +/** Update chart items. Does not update chart itself. */ +- (void)updateChartData:(NSArray *)data; + +/** Multiple selection */ +@property (nonatomic, assign) BOOL enableMultipleSelection; + +/** show only tiles, not values or percentage */ +@property (nonatomic) BOOL hideValues; + +- (void)strokeChart; + +- (void)recompute; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNPieChart.m b/Statistics/Pods/PNChart/PNChart/PNPieChart.m new file mode 100644 index 0000000..0715467 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNPieChart.m @@ -0,0 +1,498 @@ +// +// PNPieChart.m +// PNChartDemo +// +// Created by Hang Zhang on 14-5-5. +// Copyright (c) 2014年 kevinzhow. All rights reserved. +// + +#import "PNPieChart.h" +//needed for the expected label size +#import "PNLineChart.h" + +@interface PNPieChart() + +@property (nonatomic) NSArray *items; +@property (nonatomic) NSArray *endPercentages; + +@property (nonatomic) UIView *contentView; +@property (nonatomic) CAShapeLayer *pieLayer; +@property (nonatomic) NSMutableArray *descriptionLabels; +@property (strong, nonatomic) CAShapeLayer *sectorHighlight; + +@property (nonatomic, strong) NSMutableDictionary *selectedItems; + +- (void)loadDefault; + +- (UILabel *)descriptionLabelForItemAtIndex:(NSUInteger)index; +- (PNPieChartDataItem *)dataItemForIndex:(NSUInteger)index; +- (CGFloat)startPercentageForItemAtIndex:(NSUInteger)index; +- (CGFloat)endPercentageForItemAtIndex:(NSUInteger)index; +- (CGFloat)ratioForItemAtIndex:(NSUInteger)index; + +- (CAShapeLayer *)newCircleLayerWithRadius:(CGFloat)radius + borderWidth:(CGFloat)borderWidth + fillColor:(UIColor *)fillColor + borderColor:(UIColor *)borderColor + startPercentage:(CGFloat)startPercentage + endPercentage:(CGFloat)endPercentage; + + +@end + + +@implementation PNPieChart + +-(id)initWithFrame:(CGRect)frame items:(NSArray *)items{ + self = [self initWithFrame:frame]; + if(self){ + _items = [NSArray arrayWithArray:items]; + [self baseInit]; + } + + return self; +} + +- (void)awakeFromNib{ + [self baseInit]; +} + +- (void)baseInit{ + _selectedItems = [NSMutableDictionary dictionary]; + _outerCircleRadius = CGRectGetWidth(self.bounds) / 2; + _innerCircleRadius = CGRectGetWidth(self.bounds) / 6; + _descriptionTextColor = [UIColor whiteColor]; + _descriptionTextFont = [UIFont fontWithName:@"Avenir-Medium" size:18.0]; + _descriptionTextShadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.4]; + _descriptionTextShadowOffset = CGSizeMake(0, 1); + _duration = 1.0; + _shouldHighlightSectorOnTouch = YES; + _enableMultipleSelection = NO; + _hideValues = NO; + + [super setupDefaultValues]; + [self loadDefault]; +} + +- (void)loadDefault{ + __block CGFloat currentTotal = 0; + CGFloat total = [[self.items valueForKeyPath:@"@sum.value"] floatValue]; + NSMutableArray *endPercentages = [NSMutableArray new]; + [_items enumerateObjectsUsingBlock:^(PNPieChartDataItem *item, NSUInteger idx, BOOL *stop) { + if (total == 0){ + [endPercentages addObject:@(1.0 / _items.count * (idx + 1))]; + }else{ + currentTotal += item.value; + [endPercentages addObject:@(currentTotal / total)]; + } + }]; + self.endPercentages = [endPercentages copy]; + + [_contentView removeFromSuperview]; + _contentView = [[UIView alloc] initWithFrame:self.bounds]; + [self addSubview:_contentView]; + _descriptionLabels = [NSMutableArray new]; + + _pieLayer = [CAShapeLayer layer]; + [_contentView.layer addSublayer:_pieLayer]; + +} + +/** Override this to change how inner attributes are computed. **/ +- (void)recompute { + self.outerCircleRadius = CGRectGetWidth(self.bounds) / 2; + self.innerCircleRadius = CGRectGetWidth(self.bounds) / 6; +} + +#pragma mark - + +- (void)strokeChart{ + [self loadDefault]; + [self recompute]; + + PNPieChartDataItem *currentItem; + for (int i = 0; i < _items.count; i++) { + currentItem = [self dataItemForIndex:i]; + + + CGFloat startPercentage = [self startPercentageForItemAtIndex:i]; + CGFloat endPercentage = [self endPercentageForItemAtIndex:i]; + + CGFloat radius = _innerCircleRadius + (_outerCircleRadius - _innerCircleRadius) / 2; + CGFloat borderWidth = _outerCircleRadius - _innerCircleRadius; + + CAShapeLayer *currentPieLayer = [self newCircleLayerWithRadius:radius + borderWidth:borderWidth + fillColor:[UIColor clearColor] + borderColor:currentItem.color + startPercentage:startPercentage + endPercentage:endPercentage]; + [_pieLayer addSublayer:currentPieLayer]; + } + + [self maskChart]; + + for (int i = 0; i < _items.count; i++) { + UILabel *descriptionLabel = [self descriptionLabelForItemAtIndex:i]; + [_contentView addSubview:descriptionLabel]; + [_descriptionLabels addObject:descriptionLabel]; + } + + [self addAnimationIfNeeded]; +} + +- (UILabel *)descriptionLabelForItemAtIndex:(NSUInteger)index{ + PNPieChartDataItem *currentDataItem = [self dataItemForIndex:index]; + CGFloat distance = _innerCircleRadius + (_outerCircleRadius - _innerCircleRadius) / 2; + CGFloat centerPercentage = ([self startPercentageForItemAtIndex:index] + [self endPercentageForItemAtIndex:index])/ 2; + CGFloat rad = centerPercentage * 2 * M_PI; + + UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 80)]; + NSString *titleText = currentDataItem.textDescription; + + NSString *titleValue; + + if (self.showAbsoluteValues) { + titleValue = [NSString stringWithFormat:@"%.0f",currentDataItem.value]; + }else{ + titleValue = [NSString stringWithFormat:@"%.0f%%",[self ratioForItemAtIndex:index] * 100]; + } + + if (self.hideValues) + descriptionLabel.text = titleText; + else if(!titleText || self.showOnlyValues) + descriptionLabel.text = titleValue; + else { + NSString* str = [titleValue stringByAppendingString:[NSString stringWithFormat:@"\n%@",titleText]]; + descriptionLabel.text = str ; + } + + //If value is less than cutoff, show no label + if ([self ratioForItemAtIndex:index] < self.labelPercentageCutoff ) + { + descriptionLabel.text = nil; + } + + CGPoint center = CGPointMake(_outerCircleRadius + distance * sin(rad), + _outerCircleRadius - distance * cos(rad)); + + descriptionLabel.font = _descriptionTextFont; + CGSize labelSize = [descriptionLabel.text sizeWithAttributes:@{NSFontAttributeName:descriptionLabel.font}]; + descriptionLabel.frame = CGRectMake(descriptionLabel.frame.origin.x, descriptionLabel.frame.origin.y, + descriptionLabel.frame.size.width, labelSize.height); + descriptionLabel.numberOfLines = 0; + descriptionLabel.textColor = _descriptionTextColor; + descriptionLabel.shadowColor = _descriptionTextShadowColor; + descriptionLabel.shadowOffset = _descriptionTextShadowOffset; + descriptionLabel.textAlignment = NSTextAlignmentCenter; + descriptionLabel.center = center; + descriptionLabel.alpha = 0; + descriptionLabel.backgroundColor = [UIColor clearColor]; + return descriptionLabel; +} + +- (void)updateChartData:(NSArray *)items { + self.items = items; +} + +- (PNPieChartDataItem *)dataItemForIndex:(NSUInteger)index{ + return self.items[index]; +} + +- (CGFloat)startPercentageForItemAtIndex:(NSUInteger)index{ + if(index == 0){ + return 0; + } + + return [_endPercentages[index - 1] floatValue]; +} + +- (CGFloat)endPercentageForItemAtIndex:(NSUInteger)index{ + return [_endPercentages[index] floatValue]; +} + +- (CGFloat)ratioForItemAtIndex:(NSUInteger)index{ + return [self endPercentageForItemAtIndex:index] - [self startPercentageForItemAtIndex:index]; +} + +#pragma mark private methods + +- (CAShapeLayer *)newCircleLayerWithRadius:(CGFloat)radius + borderWidth:(CGFloat)borderWidth + fillColor:(UIColor *)fillColor + borderColor:(UIColor *)borderColor + startPercentage:(CGFloat)startPercentage + endPercentage:(CGFloat)endPercentage{ + CAShapeLayer *circle = [CAShapeLayer layer]; + + CGPoint center = CGPointMake(CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds)); + + UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center + radius:radius + startAngle:-M_PI_2 + endAngle:M_PI_2 * 3 + clockwise:YES]; + + circle.fillColor = fillColor.CGColor; + circle.strokeColor = borderColor.CGColor; + circle.strokeStart = startPercentage; + circle.strokeEnd = endPercentage; + circle.lineWidth = borderWidth; + circle.path = path.CGPath; + + return circle; +} + +- (void)maskChart{ + CGFloat radius = _innerCircleRadius + (_outerCircleRadius - _innerCircleRadius) / 2; + CGFloat borderWidth = _outerCircleRadius - _innerCircleRadius; + CAShapeLayer *maskLayer = [self newCircleLayerWithRadius:radius + borderWidth:borderWidth + fillColor:[UIColor clearColor] + borderColor:[UIColor blackColor] + startPercentage:0 + endPercentage:1]; + + _pieLayer.mask = maskLayer; +} + +- (void)addAnimationIfNeeded{ + if (self.displayAnimated) { + CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + animation.duration = _duration; + animation.fromValue = @0; + animation.toValue = @1; + animation.delegate = self; + animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + animation.removedOnCompletion = YES; + [_pieLayer.mask addAnimation:animation forKey:@"circleAnimation"]; + } + else { + // Add description labels since no animation is required + [_descriptionLabels enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [obj setAlpha:1]; + }]; + } +} + +- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{ + [_descriptionLabels enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [UIView animateWithDuration:0.2 animations:^(){ + [obj setAlpha:1]; + }]; + }]; +} + +- (void)didTouchAt:(CGPoint)touchLocation +{ + CGPoint circleCenter = CGPointMake(_contentView.bounds.size.width/2, _contentView.bounds.size.height/2); + + CGFloat distanceFromCenter = sqrtf(powf((touchLocation.y - circleCenter.y),2) + powf((touchLocation.x - circleCenter.x),2)); + + if (distanceFromCenter < _innerCircleRadius) { + if ([self.delegate respondsToSelector:@selector(didUnselectPieItem)]) { + [self.delegate didUnselectPieItem]; + } + [self.sectorHighlight removeFromSuperlayer]; + return; + } + + CGFloat percentage = [self findPercentageOfAngleInCircle:circleCenter fromPoint:touchLocation]; + int index = 0; + while (percentage > [self endPercentageForItemAtIndex:index]) { + index ++; + } + + if ([self.delegate respondsToSelector:@selector(userClickedOnPieIndexItem:)]) { + [self.delegate userClickedOnPieIndexItem:index]; + } + + if (self.shouldHighlightSectorOnTouch) + { + if (!self.enableMultipleSelection) + { + if (self.sectorHighlight) + [self.sectorHighlight removeFromSuperlayer]; + } + + PNPieChartDataItem *currentItem = [self dataItemForIndex:index]; + + CGFloat red,green,blue,alpha; + UIColor *old = currentItem.color; + [old getRed:&red green:&green blue:&blue alpha:&alpha]; + alpha /= 2; + UIColor *newColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; + + CGFloat startPercentage = [self startPercentageForItemAtIndex:index]; + CGFloat endPercentage = [self endPercentageForItemAtIndex:index]; + + self.sectorHighlight = [self newCircleLayerWithRadius:_outerCircleRadius + 5 + borderWidth:10 + fillColor:[UIColor clearColor] + borderColor:newColor + startPercentage:startPercentage + endPercentage:endPercentage]; + + if (self.enableMultipleSelection) + { + NSString *dictIndex = [NSString stringWithFormat:@"%d", index]; + CAShapeLayer *indexShape = [self.selectedItems valueForKey:dictIndex]; + if (indexShape) + { + [indexShape removeFromSuperlayer]; + [self.selectedItems removeObjectForKey:dictIndex]; + } + else + { + [self.selectedItems setObject:self.sectorHighlight forKey:dictIndex]; + [_contentView.layer addSublayer:self.sectorHighlight]; + } + } + else + { + [_contentView.layer addSublayer:self.sectorHighlight]; + } + } +} + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +{ + for (UITouch *touch in touches) { + CGPoint touchLocation = [touch locationInView:_contentView]; + [self didTouchAt:touchLocation]; + } +} + +- (CGFloat) findPercentageOfAngleInCircle:(CGPoint)center fromPoint:(CGPoint)reference{ + //Find angle of line Passing In Reference And Center + CGFloat angleOfLine = atanf((reference.y - center.y) / (reference.x - center.x)); + CGFloat percentage = (angleOfLine + M_PI/2)/(2 * M_PI); + return (reference.x - center.x) > 0 ? percentage : percentage + .5; +} + +- (UIView*) getLegendWithMaxWidth:(CGFloat)mWidth{ + if ([self.items count] < 1) { + return nil; + } + + /* This is a small circle that refers to the chart data */ + CGFloat legendCircle = 16; + + CGFloat hSpacing = 0; + + CGFloat beforeLabel = legendCircle + hSpacing; + + /* x and y are the coordinates of the starting point of each legend item */ + CGFloat x = 0; + CGFloat y = 0; + + /* accumulated width and height */ + CGFloat totalWidth = 0; + CGFloat totalHeight = 0; + + NSMutableArray *legendViews = [[NSMutableArray alloc] init]; + + /* Determine the max width of each legend item */ + CGFloat maxLabelWidth; + if (self.legendStyle == PNLegendItemStyleStacked) { + maxLabelWidth = mWidth - beforeLabel; + }else{ + maxLabelWidth = MAXFLOAT; + } + + /* this is used when labels wrap text and the line + * should be in the middle of the first row */ + CGFloat singleRowHeight = [PNLineChart sizeOfString:@"Test" + withWidth:MAXFLOAT + font:self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]].height; + + NSUInteger counter = 0; + NSUInteger rowWidth = 0; + NSUInteger rowMaxHeight = 0; + + for (PNPieChartDataItem *pdata in self.items) { + /* Expected label size*/ + CGSize labelsize = [PNLineChart sizeOfString:pdata.textDescription + withWidth:maxLabelWidth + font:self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]]; + + if ((rowWidth + labelsize.width + beforeLabel > mWidth)&&(self.legendStyle == PNLegendItemStyleSerial)) { + rowWidth = 0; + x = 0; + y += rowMaxHeight; + rowMaxHeight = 0; + } + rowWidth += labelsize.width + beforeLabel; + totalWidth = self.legendStyle == PNLegendItemStyleSerial ? fmaxf(rowWidth, totalWidth) : fmaxf(totalWidth, labelsize.width + beforeLabel); + // Add inflexion type + [legendViews addObject:[self drawInflexion:legendCircle * .6 + center:CGPointMake(x + legendCircle / 2, y + singleRowHeight / 2) + andColor:pdata.color]]; + + + UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x + beforeLabel, y, labelsize.width, labelsize.height)]; + label.text = pdata.textDescription; + label.textColor = self.legendFontColor ? self.legendFontColor : [UIColor blackColor]; + label.font = self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]; + label.lineBreakMode = NSLineBreakByWordWrapping; + label.numberOfLines = 0; + + + rowMaxHeight = fmaxf(rowMaxHeight, labelsize.height); + x += self.legendStyle == PNLegendItemStyleStacked ? 0 : labelsize.width + beforeLabel; + y += self.legendStyle == PNLegendItemStyleStacked ? labelsize.height : 0; + + + totalHeight = self.legendStyle == PNLegendItemStyleSerial ? fmaxf(totalHeight, rowMaxHeight + y) : totalHeight + labelsize.height; + [legendViews addObject:label]; + counter ++; + } + + UIView *legend = [[UIView alloc] initWithFrame:CGRectMake(0, 0, totalWidth, totalHeight)]; + + for (UIView* v in legendViews) { + [legend addSubview:v]; + } + return legend; +} + + +- (UIImageView*)drawInflexion:(CGFloat)size center:(CGPoint)center andColor:(UIColor*)color +{ + //Make the size a little bigger so it includes also border stroke + CGSize aSize = CGSizeMake(size, size); + + + UIGraphicsBeginImageContextWithOptions(aSize, NO, 0.0); + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextAddArc(context, size/2, size/ 2, size/2, 0, M_PI*2, YES); + + + //Set some fill color + CGContextSetFillColorWithColor(context, color.CGColor); + + //Finally draw + CGContextDrawPath(context, kCGPathFill); + + //now get the image from the context + UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext(); + + UIGraphicsEndImageContext(); + + //// Translate origin + CGFloat originX = center.x - (size) / 2.0; + CGFloat originY = center.y - (size) / 2.0; + + UIImageView *squareImageView = [[UIImageView alloc]initWithImage:squareImage]; + [squareImageView setFrame:CGRectMake(originX, originY, size, size)]; + return squareImageView; +} + +/* Redraw the chart on autolayout */ +-(void)layoutSubviews { + [super layoutSubviews]; + [self strokeChart]; +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNPieChartDataItem.h b/Statistics/Pods/PNChart/PNChart/PNPieChartDataItem.h new file mode 100644 index 0000000..08d48e9 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNPieChartDataItem.h @@ -0,0 +1,25 @@ +// +// PNPieChartDataItem.h +// PNChartDemo +// +// Created by Hang Zhang on 14-5-5. +// Copyright (c) 2014年 kevinzhow. All rights reserved. +// + +#import +#import + +@interface PNPieChartDataItem : NSObject + ++ (instancetype)dataItemWithValue:(CGFloat)value + color:(UIColor*)color; + ++ (instancetype)dataItemWithValue:(CGFloat)value + color:(UIColor*)color + description:(NSString *)description; + +@property (nonatomic) CGFloat value; +@property (nonatomic) UIColor *color; +@property (nonatomic) NSString *textDescription; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNPieChartDataItem.m b/Statistics/Pods/PNChart/PNChart/PNPieChartDataItem.m new file mode 100644 index 0000000..4bda818 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNPieChartDataItem.m @@ -0,0 +1,38 @@ +// +// PNPieChartDataItem.m +// PNChartDemo +// +// Created by Hang Zhang on 14-5-5. +// Copyright (c) 2014年 kevinzhow. All rights reserved. +// + +#import "PNPieChartDataItem.h" +#import + +@implementation PNPieChartDataItem + + ++ (instancetype)dataItemWithValue:(CGFloat)value + color:(UIColor*)color{ + PNPieChartDataItem *item = [PNPieChartDataItem new]; + item.value = value; + item.color = color; + return item; +} + ++ (instancetype)dataItemWithValue:(CGFloat)value + color:(UIColor*)color + description:(NSString *)description { + PNPieChartDataItem *item = [PNPieChartDataItem dataItemWithValue:value color:color]; + item.textDescription = description; + return item; +} + +- (void)setValue:(CGFloat)value{ + NSAssert(value >= 0, @"value should >= 0"); + if (value != _value){ + _value = value; + } +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNRadarChart.h b/Statistics/Pods/PNChart/PNChart/PNRadarChart.h new file mode 100644 index 0000000..87871d0 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNRadarChart.h @@ -0,0 +1,52 @@ +// +// PNRadarChart.h +// PNChartDemo +// +// Created by Lei on 15/7/1. +// Copyright (c) 2015年 kevinzhow. All rights reserved. +// + +#import +#import "PNGenericChart.h" +#import "PNRadarChartDataItem.h" + +#define MAXCIRCLE 20 + +typedef NS_ENUM(NSUInteger, PNRadarChartLabelStyle) { + PNRadarChartLabelStyleCircle = 0, + PNRadarChartLabelStyleHorizontal, + PNRadarChartLabelStyleHidden, +}; + +@interface PNRadarChart : PNGenericChart + +-(id)initWithFrame:(CGRect)frame items:(NSArray *)items valueDivider:(CGFloat)unitValue; +/** + *Draws the chart in an animated fashion. + */ +-(void)strokeChart; + +/** Array of `RadarChartDataItem` objects, one for each corner. */ +@property (nonatomic) NSArray *chartData; +/** The unit of this chart ,default is 1 */ +@property (nonatomic) CGFloat valueDivider; +/** The maximum for the range of values to display on the chart */ +@property (nonatomic) CGFloat maxValue; +/** Default is gray. */ +@property (nonatomic) UIColor *webColor; +/** Default is green , with an alpha of 0.7 */ +@property (nonatomic) UIColor *plotColor; +/** Default is black */ +@property (nonatomic) UIColor *fontColor; +/** Default is orange */ +@property (nonatomic) UIColor *graduationColor; +/** Default is 15 */ +@property (nonatomic) CGFloat fontSize; +/** Controls the labels display style that around chart */ +@property (nonatomic, assign) PNRadarChartLabelStyle labelStyle; +/** Tap the label will display detail value ,default is YES. */ +@property (nonatomic, assign) BOOL isLabelTouchable; +/** is show graduation on the chart ,default is NO. */ +@property (nonatomic, assign) BOOL isShowGraduation; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNRadarChart.m b/Statistics/Pods/PNChart/PNChart/PNRadarChart.m new file mode 100644 index 0000000..417b1ca --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNRadarChart.m @@ -0,0 +1,372 @@ +// +// PNRadarChart.m +// PNChartDemo +// +// Created by Lei on 15/7/1. +// Copyright (c) 2015年 kevinzhow. All rights reserved. +// + +#import "PNRadarChart.h" + +@interface PNRadarChart() + +@property (nonatomic) CGFloat centerX; +@property (nonatomic) CGFloat centerY; +@property (nonatomic) NSMutableArray *pointsToWebArrayArray; +@property (nonatomic) NSMutableArray *pointsToPlotArray; +@property (nonatomic) UILabel *detailLabel; +@property (nonatomic) CGFloat lengthUnit; +@property (nonatomic) CAShapeLayer *chartPlot; + +@end + + +@implementation PNRadarChart + +- (id)initWithFrame:(CGRect)frame items:(NSArray *)items valueDivider:(CGFloat)unitValue { + self=[super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor clearColor]; + self.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; + + //Public iVar + if ([items count]< 3)//At least three corners of A polygon ,If the count of items is less than 3 will add 3 default values + { + NSLog( @"At least three items!"); + NSArray *defaultArray = @[[PNRadarChartDataItem dataItemWithValue:0 description:@"Default"], + [PNRadarChartDataItem dataItemWithValue:0 description:@"Default"], + [PNRadarChartDataItem dataItemWithValue:0 description:@"Default"], + ]; + defaultArray = [defaultArray arrayByAddingObjectsFromArray:items]; + _chartData = [NSArray arrayWithArray:defaultArray]; + }else{ + _chartData = [NSArray arrayWithArray:items]; + } + _valueDivider = unitValue; + _maxValue = 1; + _webColor = [UIColor grayColor]; + _plotColor = [UIColor colorWithRed:.4 green:.8 blue:.4 alpha:.7]; + _fontColor = [UIColor blackColor]; + _graduationColor = [UIColor orangeColor]; + _fontSize = 15; + _labelStyle = PNRadarChartLabelStyleHorizontal; + _isLabelTouchable = YES; + _isShowGraduation = NO; + + //Private iVar + _centerX = frame.size.width/2; + _centerY = frame.size.height/2; + _pointsToWebArrayArray = [NSMutableArray array]; + _pointsToPlotArray = [NSMutableArray array]; + _lengthUnit = 0; + _chartPlot = [CAShapeLayer layer]; + _chartPlot.lineCap = kCALineCapButt; + _chartPlot.fillColor = _plotColor.CGColor; + _chartPlot.lineWidth = 1.0; + [self.layer addSublayer:_chartPlot]; + + [super setupDefaultValues]; + //init detailLabel + _detailLabel = [[UILabel alloc] init]; + _detailLabel.backgroundColor = [UIColor colorWithRed:.9 green:.9 blue:.1 alpha:.9]; + _detailLabel.textAlignment = NSTextAlignmentCenter; + _detailLabel.textColor = [UIColor colorWithWhite:1 alpha:1]; + _detailLabel.font = [UIFont systemFontOfSize:15]; + [_detailLabel setHidden:YES]; + [self addSubview:_detailLabel]; + + [self strokeChart]; + } + return self; +} + +#pragma mark - main +- (void)calculateChartPoints { + [_pointsToPlotArray removeAllObjects]; + [_pointsToWebArrayArray removeAllObjects]; + + //init Descriptions , Values and Angles. + NSMutableArray *descriptions = [NSMutableArray array]; + NSMutableArray *values = [NSMutableArray array]; + NSMutableArray *angles = [NSMutableArray array]; + for (int i=0;i<_chartData.count;i++) { + PNRadarChartDataItem *item = (PNRadarChartDataItem *)[_chartData objectAtIndex:i]; + [descriptions addObject:item.textDescription]; + [values addObject:[NSNumber numberWithFloat:item.value]]; + CGFloat angleValue = (float)i/(float)[_chartData count]*2*M_PI; + [angles addObject:[NSNumber numberWithFloat:angleValue]]; + } + + //calculate all the lengths + _maxValue = [self getMaxValueFromArray:values]; + CGFloat margin = 0; + if (_labelStyle==PNRadarChartLabelStyleCircle) { + margin = MIN(_centerX , _centerY)*3/10; + }else if (_labelStyle==PNRadarChartLabelStyleHorizontal) { + margin = [self getMaxWidthLabelFromArray:descriptions withFontSize:_fontSize]; + } + CGFloat maxLength = ceil(MIN(_centerX, _centerY) - margin); + int plotCircles = (_maxValue/_valueDivider); + if (plotCircles > MAXCIRCLE) { + NSLog(@"Circle number is higher than max"); + plotCircles = MAXCIRCLE; + _valueDivider = _maxValue/plotCircles; + } + _lengthUnit = maxLength/plotCircles; + NSArray *lengthArray = [self getLengthArrayWithCircleNum:(int)plotCircles]; + + //get all the points and plot + for (NSNumber *lengthNumber in lengthArray) { + CGFloat length = [lengthNumber floatValue]; + [_pointsToWebArrayArray addObject:[self getWebPointWithLength:length angleArray:angles]]; + } + int section = 0; + for (id value in values) { + CGFloat valueFloat = [value floatValue]; + if (valueFloat>_maxValue) { + NSString *reason = [NSString stringWithFormat:@"Value number is higher than max -value: %f - maxValue: %f",valueFloat,_maxValue]; + @throw [NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil]; + return; + } + + CGFloat length = valueFloat/_maxValue*maxLength; + CGFloat angle = [[angles objectAtIndex:section] floatValue]; + CGFloat x = _centerX +length*cos(angle); + CGFloat y = _centerY +length*sin(angle); + NSValue* point = [NSValue valueWithCGPoint:CGPointMake(x, y)]; + [_pointsToPlotArray addObject:point]; + section++; + } + //set the labels + [self drawLabelWithMaxLength:maxLength labelArray:descriptions angleArray:angles]; + + } +#pragma mark - Draw + +- (void)drawRect:(CGRect)rect { + // Drawing backgound + CGContextRef context = UIGraphicsGetCurrentContext(); + CGContextClearRect(context, rect); + int section = 0; + //circles + for(NSArray *pointArray in _pointsToWebArrayArray){ + //plot backgound + CGContextRef graphContext = UIGraphicsGetCurrentContext(); + CGContextBeginPath(graphContext); + CGPoint beginPoint = [[pointArray objectAtIndex:0] CGPointValue]; + CGContextMoveToPoint(graphContext, beginPoint.x, beginPoint.y); + for(NSValue* pointValue in pointArray){ + CGPoint point = [pointValue CGPointValue]; + CGContextAddLineToPoint(graphContext, point.x, point.y); + } + CGContextAddLineToPoint(graphContext, beginPoint.x, beginPoint.y); + CGContextSetStrokeColorWithColor(graphContext, _webColor.CGColor); + CGContextStrokePath(graphContext); + + } + //cuts + NSArray *largestPointArray = [_pointsToWebArrayArray lastObject]; + for (NSValue *pointValue in largestPointArray){ + section++; + if (section==1&&_isShowGraduation)continue; + + CGContextRef graphContext = UIGraphicsGetCurrentContext(); + CGContextBeginPath(graphContext); + CGContextMoveToPoint(graphContext, _centerX, _centerY); + CGPoint point = [pointValue CGPointValue]; + CGContextAddLineToPoint(graphContext, point.x, point.y); + CGContextSetStrokeColorWithColor(graphContext, _webColor.CGColor); + CGContextStrokePath(graphContext); + } + + +} + +- (void)strokeChart { + + [self calculateChartPoints]; + [self setNeedsDisplay]; + [_detailLabel setHidden:YES]; + + //Draw plot + [_chartPlot removeAllAnimations]; + UIBezierPath *plotline = [UIBezierPath bezierPath]; + CGPoint beginPoint = [[_pointsToPlotArray objectAtIndex:0] CGPointValue]; + [plotline moveToPoint:CGPointMake(beginPoint.x, beginPoint.y)]; + for(NSValue *pointValue in _pointsToPlotArray){ + CGPoint point = [pointValue CGPointValue]; + [plotline addLineToPoint:CGPointMake(point.x ,point.y)]; + + } + [plotline setLineWidth:1]; + [plotline setLineCapStyle:kCGLineCapButt]; + + _chartPlot.path = plotline.CGPath; + + [self addAnimationIfNeeded]; + [self showGraduation]; +} + +#pragma mark - Helper + +- (void)drawLabelWithMaxLength:(CGFloat)maxLength labelArray:(NSArray *)labelArray angleArray:(NSArray *)angleArray { + //set labels + int labelTag = 121; + while (true) { + UIView *label = [self viewWithTag:labelTag]; + if(!label)break; + [label removeFromSuperview]; + } + int section = 0; + CGFloat labelLength = maxLength + maxLength/10; + + for (NSString *labelString in labelArray) { + CGFloat angle = [[angleArray objectAtIndex:section] floatValue]; + CGFloat x = _centerX + labelLength *cos(angle); + CGFloat y = _centerY + labelLength *sin(angle); + + UILabel *label = [[UILabel alloc] init] ; + label.backgroundColor = [UIColor clearColor]; + label.font = [UIFont systemFontOfSize:_fontSize]; + label.text = labelString; + label.tag = labelTag; + CGSize detailSize = [labelString sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:_fontSize]}]; + + switch (_labelStyle) { + case PNRadarChartLabelStyleCircle: + label.frame = CGRectMake(x-5*_fontSize/2, y-_fontSize/2, 5*_fontSize, _fontSize); + label.transform = CGAffineTransformMakeRotation(((float)section/[labelArray count])*(2*M_PI)+M_PI_2); + label.textAlignment = NSTextAlignmentCenter; + + break; + case PNRadarChartLabelStyleHorizontal: + if (x<_centerX) { + label.frame = CGRectMake(x-detailSize.width, y-detailSize.height/2, detailSize.width, detailSize.height); + label.textAlignment = NSTextAlignmentRight; + }else{ + label.frame = CGRectMake(x, y-detailSize.height/2, detailSize.width , detailSize.height); + label.textAlignment = NSTextAlignmentLeft; + } + break; + case PNRadarChartLabelStyleHidden: + [label setHidden:YES]; + break; + default: + break; + } + [label sizeToFit]; + + label.userInteractionEnabled = YES; + UITapGestureRecognizer *tapLabelGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapLabel:)]; + [label addGestureRecognizer:tapLabelGesture]; + [self addSubview:label]; + + section ++; + } + +} + +- (void)tapLabel:(UITapGestureRecognizer *)recognizer { + UILabel *label=(UILabel*)recognizer.view; + _detailLabel.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y-30, 50, 25); + for (PNRadarChartDataItem *item in _chartData) { + if ([label.text isEqualToString:item.textDescription]) { + _detailLabel.text = [NSString stringWithFormat:@"%.2f", item.value]; + break; + } + } + [_detailLabel setHidden:NO]; + +} + +- (void)showGraduation { + int labelTag = 112; + while (true) { + UIView *label = [self viewWithTag:labelTag]; + if(!label)break; + [label removeFromSuperview]; + } + int section = 0; + for (NSArray *pointsArray in _pointsToWebArrayArray) { + section++; + CGPoint labelPoint = [[pointsArray objectAtIndex:0] CGPointValue]; + UILabel *graduationLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelPoint.x-_lengthUnit, labelPoint.y-_lengthUnit*5/8, _lengthUnit*5/8, _lengthUnit)]; + graduationLabel.adjustsFontSizeToFitWidth = YES; + graduationLabel.tag = labelTag; + graduationLabel.font = [UIFont systemFontOfSize:ceil(_lengthUnit)]; + graduationLabel.textColor = [UIColor orangeColor]; + graduationLabel.text = [NSString stringWithFormat:@"%.0f",_valueDivider*section]; + [self addSubview:graduationLabel]; + if (_isShowGraduation) { + [graduationLabel setHidden:NO]; + }else{ + [graduationLabel setHidden:YES];} + } + +} + +- (NSArray *)getWebPointWithLength:(CGFloat)length angleArray:(NSArray *)angleArray { + NSMutableArray *pointArray = [NSMutableArray array]; + for (NSNumber *angleNumber in angleArray) { + CGFloat angle = [angleNumber floatValue]; + CGFloat x = _centerX + length*cos(angle); + CGFloat y = _centerY + length*sin(angle); + [pointArray addObject:[NSValue valueWithCGPoint:CGPointMake(x,y)]]; + } + return pointArray; + +} + +- (NSArray *)getLengthArrayWithCircleNum:(int)plotCircles { + NSMutableArray *lengthArray = [NSMutableArray array]; + CGFloat length = 0; + for (int i = 0; i < plotCircles; i++) { + length += _lengthUnit; + [lengthArray addObject:[NSNumber numberWithFloat:length]]; + } + return lengthArray; +} + +- (CGFloat)getMaxWidthLabelFromArray:(NSArray *)keyArray withFontSize:(CGFloat)size { + CGFloat maxWidth = 0; + for (NSString *str in keyArray) { + CGSize detailSize = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:_fontSize]}]; + maxWidth = MAX(maxWidth, detailSize.width); + } + return maxWidth; +} + +- (CGFloat)getMaxValueFromArray:(NSArray *)valueArray { + CGFloat max = _maxValue; + for (NSNumber *valueNum in valueArray) { + CGFloat valueFloat = [valueNum floatValue]; + max = MAX(valueFloat, max); + } + return ceil(max); +} + +- (void)addAnimationIfNeeded +{ + if (self.displayAnimated) { + CABasicAnimation *animateScale = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; + animateScale.fromValue = [NSNumber numberWithFloat:0.f]; + animateScale.toValue = [NSNumber numberWithFloat:1.0f]; + + CABasicAnimation *animateMove = [CABasicAnimation animationWithKeyPath:@"position"]; + animateMove.fromValue = [NSValue valueWithCGPoint:CGPointMake(_centerX, _centerY)]; + animateMove.toValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)]; + + CABasicAnimation *animateAlpha = [CABasicAnimation animationWithKeyPath:@"opacity"]; + animateAlpha.fromValue = [NSNumber numberWithFloat:0.f]; + + CAAnimationGroup *aniGroup = [CAAnimationGroup animation]; + aniGroup.duration = 1.f; + aniGroup.repeatCount = 1; + aniGroup.animations = [NSArray arrayWithObjects:animateScale,animateMove,animateAlpha, nil]; + aniGroup.removedOnCompletion = YES; + + [_chartPlot addAnimation:aniGroup forKey:nil]; + } +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNRadarChartDataItem.h b/Statistics/Pods/PNChart/PNChart/PNRadarChartDataItem.h new file mode 100644 index 0000000..e67429c --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNRadarChartDataItem.h @@ -0,0 +1,19 @@ +// +// PNRadarChartDataItem.h +// PNChartDemo +// +// Created by Lei on 15/7/1. +// Copyright (c) 2015年 kevinzhow. All rights reserved. +// + +#import + +@interface PNRadarChartDataItem : NSObject + ++ (instancetype)dataItemWithValue:(CGFloat)value + description:(NSString *)description; + +@property (nonatomic) CGFloat value; +@property (nonatomic,copy) NSString *textDescription; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNRadarChartDataItem.m b/Statistics/Pods/PNChart/PNChart/PNRadarChartDataItem.m new file mode 100644 index 0000000..123ac73 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNRadarChartDataItem.m @@ -0,0 +1,29 @@ +// +// PNRadarChartDataItem.m +// PNChartDemo +// +// Created by Lei on 15/7/1. +// Copyright (c) 2015年 kevinzhow. All rights reserved. +// + +#import "PNRadarChartDataItem.h" + +@implementation PNRadarChartDataItem + ++ (instancetype)dataItemWithValue:(CGFloat)value + description:(NSString *)description { + PNRadarChartDataItem *item = [PNRadarChartDataItem new]; + item.value = value; + item.textDescription = description; + return item; +} + +- (void)setValue:(CGFloat)value { + if (value<0) { + _value = 0; + NSLog(@"Value value can not be negative"); + } + _value = value; +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNScatterChart.h b/Statistics/Pods/PNChart/PNChart/PNScatterChart.h new file mode 100644 index 0000000..aa4eab8 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNScatterChart.h @@ -0,0 +1,69 @@ +// +// PNScatterChart.h +// PNChartDemo +// +// Created by Alireza Arabi on 12/4/14. +// Copyright (c) 2014 kevinzhow. All rights reserved. +// + +#import +#import +#import "PNChartDelegate.h" +#import "PNGenericChart.h" +#import "PNScatterChartData.h" +#import "PNScatterChartDataItem.h" + +@interface PNScatterChart : PNGenericChart + +@property (nonatomic, retain) id delegate; + +/** Array of `ScatterChartData` objects, one for each line. */ +@property (nonatomic) NSArray *chartData; + +/** Controls whether to show the coordinate axis. Default is NO. */ +@property (nonatomic, getter = isShowCoordinateAxis) BOOL showCoordinateAxis; +@property (nonatomic) UIColor *axisColor; +@property (nonatomic) CGFloat axisWidth; + +/** String formatter for float values in x-axis/y-axis labels. If not set, defaults to @"%1.f" */ +@property (nonatomic, strong) NSString *xLabelFormat; +@property (nonatomic, strong) NSString *yLabelFormat; + +/** Default is true. */ +@property (nonatomic) BOOL showLabel; + +/** Default is 18-point Avenir Medium. */ +@property (nonatomic) UIFont *descriptionTextFont; + +/** Default is white. */ +@property (nonatomic) UIColor *descriptionTextColor; + +/** Default is black, with an alpha of 0.4. */ +@property (nonatomic) UIColor *descriptionTextShadowColor; + +/** Default is CGSizeMake(0, 1). */ +@property (nonatomic) CGSize descriptionTextShadowOffset; + +/** Default is 1.0. */ +@property (nonatomic) NSTimeInterval duration; + +@property (nonatomic) CGFloat AxisX_minValue; +@property (nonatomic) CGFloat AxisX_maxValue; + +@property (nonatomic) CGFloat AxisY_minValue; +@property (nonatomic) CGFloat AxisY_maxValue; + +- (void) setAxisXWithMinimumValue:(CGFloat)minVal andMaxValue:(CGFloat)maxVal toTicks:(int)numberOfTicks; +- (void) setAxisYWithMinimumValue:(CGFloat)minVal andMaxValue:(CGFloat)maxVal toTicks:(int)numberOfTicks; +- (void) setAxisXLabel:(NSArray *)array; +- (void) setAxisYLabel:(NSArray *)array; +- (void) setup; +- (void) drawLineFromPoint : (CGPoint) startPoint ToPoint : (CGPoint) endPoint WithLineWith : (CGFloat) lineWidth AndWithColor : (UIColor*) color; + +/** + * Update Chart Value + */ + +- (void)updateChartData:(NSArray *)data; + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNScatterChart.m b/Statistics/Pods/PNChart/PNChart/PNScatterChart.m new file mode 100644 index 0000000..a16cf85 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNScatterChart.m @@ -0,0 +1,445 @@ +// +// PNScatterChart.m +// PNChartDemo +// +// Created by Alireza Arabi on 12/4/14. +// Copyright (c) 2014 kevinzhow. All rights reserved. +// + +#import "PNScatterChart.h" +#import "PNColor.h" +#import "PNChartLabel.h" +#import "PNScatterChartData.h" +#import "PNScatterChartDataItem.h" + +@interface PNScatterChart () + +@property (nonatomic, weak) CAShapeLayer *pathLayer; +@property (nonatomic, weak) NSMutableArray *verticalLineLayer; +@property (nonatomic, weak) NSMutableArray *horizentalLinepathLayer; + +@property (nonatomic) CGPoint startPoint; + +@property (nonatomic) CGPoint startPointVectorX; +@property (nonatomic) CGPoint endPointVecotrX; + +@property (nonatomic) CGPoint startPointVectorY; +@property (nonatomic) CGPoint endPointVecotrY; + +@property (nonatomic) CGFloat vectorX_Steps; +@property (nonatomic) CGFloat vectorY_Steps; + +@property (nonatomic) CGFloat vectorX_Size; +@property (nonatomic) CGFloat vectorY_Size; + +@property (nonatomic) NSMutableArray *axisX_labels; +@property (nonatomic) NSMutableArray *axisY_labels; + +@property (nonatomic) int AxisX_partNumber ; +@property (nonatomic) int AxisY_partNumber ; + +@property (nonatomic) CGFloat AxisX_step ; +@property (nonatomic) CGFloat AxisY_step ; + +@property (nonatomic) CGFloat AxisX_Margin; +@property (nonatomic) CGFloat AxisY_Margin; + +@property (nonatomic) BOOL isForUpdate; + +@end + + +@implementation PNScatterChart + +#pragma mark initialization + +- (id)initWithCoder:(NSCoder *)coder +{ + self = [super initWithCoder:coder]; + + if (self) { + [self setupDefaultValues]; + } + return self; +} + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + + if (self) { + [self setupDefaultValues]; + } + return self; +} + +- (void) setup +{ + [self vectorXSetup]; + [self vectorYSetup]; +} + +- (void)setupDefaultValues +{ + [super setupDefaultValues]; + + // Initialization code + self.backgroundColor = [UIColor whiteColor]; + self.clipsToBounds = YES; + _showLabel = YES; + _isForUpdate = NO; + self.userInteractionEnabled = YES; + + // Coordinate Axis Default Values + _showCoordinateAxis = YES; + _axisColor = [UIColor colorWithRed:0.4f green:0.4f blue:0.4f alpha:1.f]; + _axisWidth = 1.f; + + // Initialization code + _AxisX_Margin = 30 ; + _AxisY_Margin = 30 ; + +// self.frame = CGRectMake((SCREEN_WIDTH - self.frame.size.width) / 2, 200, self.frame.size.width, self.frame.size.height) ; + self.backgroundColor = [UIColor clearColor]; + + _startPoint.y = self.frame.size.height - self.AxisY_Margin ; + _startPoint.x = self.AxisX_Margin ; + + _axisX_labels = [NSMutableArray array]; + _axisY_labels = [NSMutableArray array]; + + _descriptionTextColor = [UIColor blackColor]; + _descriptionTextFont = [UIFont fontWithName:@"Avenir-Medium" size:9.0]; + _descriptionTextShadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.4]; + _descriptionTextShadowOffset = CGSizeMake(0, 1); + _duration = 1.0; + +} + +#pragma mark calculating axis + +- (void) setAxisXWithMinimumValue:(CGFloat)minVal andMaxValue:(CGFloat)maxVal toTicks:(int)numberOfTicks +{ + _AxisX_minValue = minVal ; + _AxisX_maxValue = maxVal ; + _AxisX_partNumber = numberOfTicks - 1; + _AxisX_step = (float)((maxVal - minVal)/_AxisX_partNumber); + + NSString *LabelFormat = self.xLabelFormat ? : @"%1.f"; + CGFloat tempValue = minVal ; + UILabel *label = [[UILabel alloc] init]; + label.text = [NSString stringWithFormat:LabelFormat,minVal] ; + [_axisX_labels addObject:label]; + for (int i = 0 ; i < _AxisX_partNumber; i++) { + tempValue = tempValue + _AxisX_step; + UILabel *tempLabel = [[UILabel alloc] init]; + tempLabel.text = [NSString stringWithFormat:LabelFormat,tempValue] ; + [_axisX_labels addObject:tempLabel]; + } +} + +- (void) setAxisYWithMinimumValue:(CGFloat)minVal andMaxValue:(CGFloat)maxVal toTicks:(int)numberOfTicks +{ + _AxisY_minValue = minVal ; + _AxisY_maxValue = maxVal ; + _AxisY_partNumber = numberOfTicks - 1; + _AxisY_step = (float)((maxVal - minVal)/_AxisY_partNumber); + + NSString *LabelFormat = self.yLabelFormat ? : @"%1.f"; + CGFloat tempValue = minVal ; + UILabel *label = [[UILabel alloc] init]; + label.text = [NSString stringWithFormat:LabelFormat,minVal] ; + [_axisY_labels addObject:label]; + for (int i = 0 ; i < _AxisY_partNumber; i++) { + tempValue = tempValue + _AxisY_step; + UILabel *tempLabel = [[UILabel alloc] init]; + tempLabel.text = [NSString stringWithFormat:LabelFormat,tempValue] ; + [_axisY_labels addObject:tempLabel]; + } +} + +- (NSArray*) getAxisMinMax:(NSArray*)xValues +{ + float min = [xValues[0] floatValue]; + float max = [xValues[0] floatValue]; + for (NSNumber *number in xValues) + { + if ([number floatValue] > max) + max = [number floatValue]; + + if ([number floatValue] < min) + min = [number floatValue]; + } + NSArray *result = @[[NSNumber numberWithFloat:min], [NSNumber numberWithFloat:max]]; + + + return result; +} + +- (void)setAxisXLabel:(NSArray *)array { + if(array.count == ++_AxisX_partNumber){ + [_axisX_labels removeAllObjects]; + for(int i=0;i= _AxisX_minValue && xValue <= _AxisX_maxValue) || !(yValue >= _AxisY_minValue && yValue <= _AxisY_maxValue)) { + NSLog(@"input is not in correct range."); + exit(0); + } + xFinilizeValue = [self mappingIsForAxisX:true WithValue:xValue]; + yFinilizeValue = [self mappingIsForAxisX:false WithValue:yValue]; + CAShapeLayer *shape = [self drawingPointsForChartData:chartData AndWithX:xFinilizeValue AndWithY:yFinilizeValue]; + self.pathLayer = shape ; + [self.layer addSublayer:self.pathLayer]; + + [self addAnimationIfNeeded]; + } + } + }); + }); +} + +- (void)addAnimationIfNeeded{ + + if (self.displayAnimated) { + CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; + pathAnimation.duration = _duration; + pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + pathAnimation.fromValue = @(0.0f); + pathAnimation.toValue = @(1.0f); + pathAnimation.fillMode = kCAFillModeForwards; + self.layer.opacity = 1; + [self.pathLayer addAnimation:pathAnimation forKey:@"fade"]; + } +} + +- (CGFloat) mappingIsForAxisX : (BOOL) isForAxisX WithValue : (CGFloat) value{ + + if (isForAxisX) { + float temp = _startPointVectorX.x + (_vectorX_Steps / 2) ; + CGFloat xPos = temp + (((value - _AxisX_minValue)/_AxisX_step) * _vectorX_Steps) ; + return xPos; + } + else { + float temp = _startPointVectorY.y - (_vectorY_Steps / 2) ; + CGFloat yPos = temp - (((value - _AxisY_minValue) /_AxisY_step) * _vectorY_Steps); + return yPos; + } + return 0; +} + +#pragma mark - Update Chart Data + +- (void)updateChartData:(NSArray *)data +{ + _chartData = data; + + // will be work in future. +} + +#pragma drawing methods + +- (void)drawRect:(CGRect)rect +{ + [super drawRect:rect]; + + CGContextRef context = UIGraphicsGetCurrentContext(); + if (_showCoordinateAxis) { + CGContextSetStrokeColorWithColor(context, [_axisColor CGColor]); + CGContextSetLineWidth(context, _axisWidth); + //drawing x vector + CGContextMoveToPoint(context, _startPoint.x, _startPoint.y); + CGContextAddLineToPoint(context, _endPointVecotrX.x, _endPointVecotrX.y); + //drawing y vector + CGContextMoveToPoint(context, _startPoint.x, _startPoint.y); + CGContextAddLineToPoint(context, _endPointVecotrY.x, _endPointVecotrY.y); + //drawing x arrow vector + CGContextMoveToPoint(context, _endPointVecotrX.x, _endPointVecotrX.y); + CGContextAddLineToPoint(context, _endPointVecotrX.x - 5, _endPointVecotrX.y + 3); + CGContextMoveToPoint(context, _endPointVecotrX.x, _endPointVecotrX.y); + CGContextAddLineToPoint(context, _endPointVecotrX.x - 5, _endPointVecotrX.y - 3); + //drawing y arrow vector + CGContextMoveToPoint(context, _endPointVecotrY.x, _endPointVecotrY.y); + CGContextAddLineToPoint(context, _endPointVecotrY.x - 3, _endPointVecotrY.y + 5); + CGContextMoveToPoint(context, _endPointVecotrY.x, _endPointVecotrY.y); + CGContextAddLineToPoint(context, _endPointVecotrY.x + 3, _endPointVecotrY.y + 5); + } + + if (_showLabel) { + //drawing x steps vector and putting axis x labels + float temp = _startPointVectorX.x + (_vectorX_Steps / 2) ; + for (int i = 0; i < _axisX_labels.count; i++) { + UIBezierPath *path = [UIBezierPath bezierPath]; + [path moveToPoint:CGPointMake(temp, _startPointVectorX.y - 2)]; + [path addLineToPoint:CGPointMake(temp, _startPointVectorX.y + 3)]; + CAShapeLayer *shapeLayer = [CAShapeLayer layer]; + shapeLayer.path = [path CGPath]; + shapeLayer.strokeColor = [_axisColor CGColor]; + shapeLayer.lineWidth = _axisWidth; + shapeLayer.fillColor = [_axisColor CGColor]; + [self.horizentalLinepathLayer addObject:shapeLayer]; + [self.layer addSublayer:shapeLayer]; + UILabel *lb = [_axisX_labels objectAtIndex:i] ; + [self showXLabel:lb InPosition:CGPointMake(temp - 15, _startPointVectorX.y + 10 )]; + temp = temp + _vectorX_Steps ; + } + //drawing y steps vector and putting axis x labels + temp = _startPointVectorY.y - (_vectorY_Steps / 2) ; + for (int i = 0; i < _axisY_labels.count; i++) { + UIBezierPath *path = [UIBezierPath bezierPath]; + [path moveToPoint:CGPointMake(_startPointVectorY.x - 3, temp)]; + [path addLineToPoint:CGPointMake( _startPointVectorY.x + 2, temp)]; + CAShapeLayer *shapeLayer = [CAShapeLayer layer]; + shapeLayer.path = [path CGPath]; + shapeLayer.strokeColor = [_axisColor CGColor]; + shapeLayer.lineWidth = _axisWidth; + shapeLayer.fillColor = [_axisColor CGColor]; + [self.verticalLineLayer addObject:shapeLayer]; + [self.layer addSublayer:shapeLayer]; + UILabel *lb = [_axisY_labels objectAtIndex:i]; + [self showXLabel:lb InPosition:CGPointMake(_startPointVectorY.x - 30, temp - 5)]; + temp = temp - _vectorY_Steps ; + } + } + CGContextDrawPath(context, kCGPathStroke); +} + +- (CAShapeLayer*) drawingPointsForChartData : (PNScatterChartData *) chartData AndWithX : (CGFloat) X AndWithY : (CGFloat) Y +{ + if (chartData.inflexionPointStyle == PNScatterChartPointStyleCircle) { + float radius = chartData.size; + CAShapeLayer *circle = [CAShapeLayer layer]; + // Make a circular shape + circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(X - radius, Y - radius, 2.0*radius, 2.0*radius) + cornerRadius:radius].CGPath; + // Configure the appearence of the circle + circle.fillColor = [chartData.fillColor CGColor]; + circle.strokeColor = [chartData.strokeColor CGColor]; + circle.lineWidth = 1; + + // Add to parent layer + return circle; + } + else if (chartData.inflexionPointStyle == PNScatterChartPointStyleSquare) { + float side = chartData.size; + CAShapeLayer *square = [CAShapeLayer layer]; + // Make a circular shape + square.path = [UIBezierPath bezierPathWithRect:CGRectMake(X - (side/2) , Y - (side/2), side, side)].CGPath ; + // Configure the apperence of the circle + square.fillColor = [chartData.fillColor CGColor]; + square.strokeColor = [chartData.strokeColor CGColor]; + square.lineWidth = 1; + + // Add to parent layer + return square; + } + else { + // you cann add your own scatter chart point here + } + return nil ; +} + +- (void) drawLineFromPoint : (CGPoint) startPoint ToPoint : (CGPoint) endPoint WithLineWith : (CGFloat) lineWidth AndWithColor : (UIColor*) color{ + + // call the same method on a background thread + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + if (self.displayAnimated) { + [NSThread sleepForTimeInterval:2]; + } + // calculating start and end point + __block CGFloat startX = [self mappingIsForAxisX:true WithValue:startPoint.x]; + __block CGFloat startY = [self mappingIsForAxisX:false WithValue:startPoint.y]; + __block CGFloat endX = [self mappingIsForAxisX:true WithValue:endPoint.x]; + __block CGFloat endY = [self mappingIsForAxisX:false WithValue:endPoint.y]; + // update UI on the main thread + dispatch_async(dispatch_get_main_queue(), ^{ + // drawing path between two points + UIBezierPath *path = [UIBezierPath bezierPath]; + [path moveToPoint:CGPointMake(startX, startY)]; + [path addLineToPoint:CGPointMake(endX, endY)]; + CAShapeLayer *shapeLayer = [CAShapeLayer layer]; + shapeLayer.path = [path CGPath]; + shapeLayer.strokeColor = [color CGColor]; + shapeLayer.lineWidth = lineWidth; + shapeLayer.fillColor = [color CGColor]; + // adding animation to path + [self addStrokeEndAnimationIfNeededToLayer:shapeLayer]; + [self.layer addSublayer:shapeLayer]; + }); + }); +} + +- (void)addStrokeEndAnimationIfNeededToLayer:(CAShapeLayer *)shapeLayer{ + + if (self.displayAnimated) { + CABasicAnimation *animateStrokeEnd = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; + animateStrokeEnd.duration = _duration; + animateStrokeEnd.fromValue = [NSNumber numberWithFloat:0.0f]; + animateStrokeEnd.toValue = [NSNumber numberWithFloat:1.0f]; + [shapeLayer addAnimation:animateStrokeEnd forKey:nil]; + } +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNScatterChartData.h b/Statistics/Pods/PNChart/PNChart/PNScatterChartData.h new file mode 100644 index 0000000..40b7b0e --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNScatterChartData.h @@ -0,0 +1,38 @@ +// +// PNScatterChartData.h +// PNChartDemo +// +// Created by Alireza Arabi on 12/4/14. +// Copyright (c) 2014 kevinzhow. All rights reserved. +// + +#import +#import + +typedef NS_ENUM(NSUInteger, PNScatterChartPointStyle) { + PNScatterChartPointStyleCircle = 0, + PNScatterChartPointStyleSquare = 1, +}; + +@class PNScatterChartDataItem; + +typedef PNScatterChartDataItem *(^LCScatterChartDataGetter)(NSUInteger item); + +@interface PNScatterChartData : NSObject + +@property (strong) UIColor *fillColor; +@property (strong) UIColor *strokeColor; + +@property NSUInteger itemCount; +@property (copy) LCScatterChartDataGetter getData; + +@property (nonatomic, assign) PNScatterChartPointStyle inflexionPointStyle; + +/** + * If PNLineChartPointStyle is circle, this returns the circle's diameter. + * If PNLineChartPointStyle is square, each point is a square with each side equal in length to this value. + */ +@property (nonatomic, assign) CGFloat size; + + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNScatterChartData.m b/Statistics/Pods/PNChart/PNChart/PNScatterChartData.m new file mode 100644 index 0000000..a53a5c2 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNScatterChartData.m @@ -0,0 +1,31 @@ +// +// PNScatterChartData.m +// PNChartDemo +// +// Created by Alireza Arabi on 12/4/14. +// Copyright (c) 2014 kevinzhow. All rights reserved. +// + +#import "PNScatterChartData.h" + +@implementation PNScatterChartData + +- (id)init +{ + self = [super init]; + if (self) { + [self setupDefaultValues]; + } + + return self; +} + +- (void)setupDefaultValues +{ + _inflexionPointStyle = PNScatterChartPointStyleCircle; + _fillColor = [UIColor grayColor]; + _strokeColor = [UIColor clearColor]; + _size = 3 ; +} + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNScatterChartDataItem.h b/Statistics/Pods/PNChart/PNChart/PNScatterChartDataItem.h new file mode 100644 index 0000000..f38ee4e --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNScatterChartDataItem.h @@ -0,0 +1,19 @@ +// +// PNScatterChartDataItem.h +// PNChartDemo +// +// Created by Alireza Arabi on 12/4/14. +// Copyright (c) 2014 kevinzhow. All rights reserved. +// + +#import +#import + +@interface PNScatterChartDataItem : NSObject + ++ (PNScatterChartDataItem *)dataItemWithX:(CGFloat)x AndWithY:(CGFloat)y; + +@property (readonly) CGFloat x; // should be within the x range +@property (readonly) CGFloat y; // should be within the y range + +@end diff --git a/Statistics/Pods/PNChart/PNChart/PNScatterChartDataItem.m b/Statistics/Pods/PNChart/PNChart/PNScatterChartDataItem.m new file mode 100644 index 0000000..a454459 --- /dev/null +++ b/Statistics/Pods/PNChart/PNChart/PNScatterChartDataItem.m @@ -0,0 +1,37 @@ +// +// PNScatterChartDataItem.m +// PNChartDemo +// +// Created by Alireza Arabi on 12/4/14. +// Copyright (c) 2014 kevinzhow. All rights reserved. +// + +#import "PNScatterChartDataItem.h" + +@interface PNScatterChartDataItem () + +- (id)initWithX:(CGFloat)x AndWithY:(CGFloat)y; + +@property (readwrite) CGFloat x; // should be within the x range +@property (readwrite) CGFloat y; // should be within the y range + +@end + +@implementation PNScatterChartDataItem + ++ (PNScatterChartDataItem *)dataItemWithX:(CGFloat)x AndWithY:(CGFloat)y +{ + return [[PNScatterChartDataItem alloc] initWithX:x AndWithY:y]; +} + +- (id)initWithX:(CGFloat)x AndWithY:(CGFloat)y +{ + if ((self = [super init])) { + self.x = x; + self.y = y; + } + + return self; +} + +@end diff --git a/Statistics/Pods/PNChart/README.md b/Statistics/Pods/PNChart/README.md new file mode 100644 index 0000000..c1d7f94 --- /dev/null +++ b/Statistics/Pods/PNChart/README.md @@ -0,0 +1,311 @@ +#PNChart + +[![Build Status](https://travis-ci.org/kevinzhow/PNChart.png?branch=master)](https://travis-ci.org/kevinzhow/PNChart) + +You can also find swift version at here https://github.com/kevinzhow/PNChart-Swift + +A simple and beautiful chart lib with **animation** used in [Piner](https://itunes.apple.com/us/app/piner/id637706410) and [CoinsMan](https://itunes.apple.com/us/app/coinsman/id772163893) for iOS + +[![](https://dl.dropboxusercontent.com/u/1599662/pnchart.gif)](https://dl.dropboxusercontent.com/u/1599662/pnchart.gif) + +## Requirements + +PNChart works on iOS 7.0+ and is compatible with ARC projects. +If you need support for iOS 6, use PNChart <= 0.8.1. Note that 0.8.2 supports iOS 8.0+ only, 0.8.3 and newer supports iOS 7.0+. + +It depends on the following Apple frameworks, which should already be included with most Xcode templates: + +* Foundation.framework +* UIKit.framework +* CoreGraphics.framework +* QuartzCore.framework + +You will need LLVM 3.0 or later in order to build PNChart. + + +## Usage + +### Cocoapods + +[CocoaPods](http://cocoapods.org) is the recommended way to add PNChart to your project. + +1. Add a pod entry for PNChart to your Podfile `pod 'PNChart'` +2. Install the pod(s) by running `pod install`. +3. Include PNChart wherever you need it with `#import "PNChart.h"`. + + +### Copy the PNChart folder to your project + + +[![](https://dl.dropboxusercontent.com/u/1599662/line.png)](https://dl.dropboxusercontent.com/u/1599662/line.png) + +```objective-c +#import "PNChart.h" + +//For Line Chart +PNLineChart * lineChart = [[PNLineChart alloc] initWithFrame:CGRectMake(0, 135.0, SCREEN_WIDTH, 200.0)]; +[lineChart setXLabels:@[@"SEP 1",@"SEP 2",@"SEP 3",@"SEP 4",@"SEP 5"]]; + +// Line Chart No.1 +NSArray * data01Array = @[@60.1, @160.1, @126.4, @262.2, @186.2]; +PNLineChartData *data01 = [PNLineChartData new]; +data01.color = PNFreshGreen; +data01.itemCount = lineChart.xLabels.count; +data01.getData = ^(NSUInteger index) { + CGFloat yValue = [data01Array[index] floatValue]; + return [PNLineChartDataItem dataItemWithY:yValue]; +}; +// Line Chart No.2 +NSArray * data02Array = @[@20.1, @180.1, @26.4, @202.2, @126.2]; +PNLineChartData *data02 = [PNLineChartData new]; +data02.color = PNTwitterColor; +data02.itemCount = lineChart.xLabels.count; +data02.getData = ^(NSUInteger index) { + CGFloat yValue = [data02Array[index] floatValue]; + return [PNLineChartDataItem dataItemWithY:yValue]; +}; + +lineChart.chartData = @[data01, data02]; +[lineChart strokeChart]; +``` + +[![](https://www.dropbox.com/s/ra9ivyh2e0hkbqt/pnchart-linechart-smooth.png)](https://www.dropbox.com/s/ra9ivyh2e0hkbqt/pnchart-linechart-smooth.png) + +You can choose to show smooth lines. + +```objective-c +lineChart.showSmoothLines = YES; +``` + +[![](https://dl.dropboxusercontent.com/u/1599662/bar.png)](https://dl.dropboxusercontent.com/u/1599662/bar.png) + +```objective-c +#import "PNChart.h" + +//For BarC hart +PNBarChart * barChart = [[PNBarChart alloc] initWithFrame:CGRectMake(0, 135.0, SCREEN_WIDTH, 200.0)]; +[barChart setXLabels:@[@"SEP 1",@"SEP 2",@"SEP 3",@"SEP 4",@"SEP 5"]]; +[barChart setYValues:@[@1, @10, @2, @6, @3]]; +[barChart strokeChart]; + +``` + +[![](https://dl.dropboxusercontent.com/u/1599662/circle.png)](https://dl.dropboxusercontent.com/u/1599662/circle.png) + + +```objective-c +#import "PNChart.h" + +//For Circle Chart + +PNCircleChart * circleChart = [[PNCircleChart alloc] initWithFrame:CGRectMake(0, 80.0, SCREEN_WIDTH, 100.0) total:[NSNumber numberWithInt:100] current:[NSNumber numberWithInt:60] clockwise:NO shadow:NO]; +circleChart.backgroundColor = [UIColor clearColor]; +[circleChart setStrokeColor:PNGreen]; +[circleChart strokeChart]; + +``` + + +[![](https://dl.dropboxusercontent.com/u/1599662/pie.png)](https://dl.dropboxusercontent.com/u/1599662/pie.png) + +```objective-c +# import "PNChart.h" +//For Pie Chart +NSArray *items = @[[PNPieChartDataItem dataItemWithValue:10 color:PNRed], + [PNPieChartDataItem dataItemWithValue:20 color:PNBlue description:@"WWDC"], + [PNPieChartDataItem dataItemWithValue:40 color:PNGreen description:@"GOOL I/O"], + ]; + + + +PNPieChart *pieChart = [[PNPieChart alloc] initWithFrame:CGRectMake(40.0, 155.0, 240.0, 240.0) items:items]; +pieChart.descriptionTextColor = [UIColor whiteColor]; +pieChart.descriptionTextFont = [UIFont fontWithName:@"Avenir-Medium" size:14.0]; +[pieChart strokeChart]; +``` + +[![](https://dl.dropboxusercontent.com/u/1599662/scatter.png)](https://dl.dropboxusercontent.com/u/1599662/scatter.png) + +```objective-c +# import "PNChart.h" +//For Scatter Chart + +PNScatterChart *scatterChart = [[PNScatterChart alloc] initWithFrame:CGRectMake(SCREEN_WIDTH /6.0 - 30, 135, 280, 200)]; +[scatterChart setAxisXWithMinimumValue:20 andMaxValue:100 toTicks:6]; +[scatterChart setAxisYWithMinimumValue:30 andMaxValue:50 toTicks:5]; + +NSArray * data01Array = [self randomSetOfObjects]; +PNScatterChartData *data01 = [PNScatterChartData new]; +data01.strokeColor = PNGreen; +data01.fillColor = PNFreshGreen; +data01.size = 2; +data01.itemCount = [[data01Array objectAtIndex:0] count]; +data01.inflexionPointStyle = PNScatterChartPointStyleCircle; +__block NSMutableArray *XAr1 = [NSMutableArray arrayWithArray:[data01Array objectAtIndex:0]]; +__block NSMutableArray *YAr1 = [NSMutableArray arrayWithArray:[data01Array objectAtIndex:1]]; +data01.getData = ^(NSUInteger index) { + CGFloat xValue = [[XAr1 objectAtIndex:index] floatValue]; + CGFloat yValue = [[YAr1 objectAtIndex:index] floatValue]; + return [PNScatterChartDataItem dataItemWithX:xValue AndWithY:yValue]; +}; + +[scatterChart setup]; +self.scatterChart.chartData = @[data01]; +/*** +this is for drawing line to compare +CGPoint start = CGPointMake(20, 35); +CGPoint end = CGPointMake(80, 45); +[scatterChart drawLineFromPoint:start ToPoint:end WithLineWith:2 AndWithColor:PNBlack]; +***/ +scatterChart.delegate = self; +``` + +#### Legend + +Legend has been added to PNChart for Line and Pie Charts. Legend items position can be stacked or in series. + +[![](https://dl.dropboxusercontent.com/u/4904447/pnchart_legend_1.png)](https://dl.dropboxusercontent.com/u/4904447/pnchart_legend_1.png) + +[![](https://dl.dropboxusercontent.com/u/4904447/pnchart_legend_2.png)](https://dl.dropboxusercontent.com/u/4904447/pnchart_legend_2.png) + +```objective-c +#import "PNChart.h" + +//For Line Chart + +//Add Line Titles for the Legend +data01.dataTitle = @"Alpha"; +data02.dataTitle = @"Beta Beta Beta Beta"; + +//Build the legend +self.lineChart.legendStyle = PNLegendItemStyleSerial; +self.lineChart.legendFontSize = 12.0; +UIView *legend = [self.lineChart getLegendWithMaxWidth:320]; + +//Move legend to the desired position and add to view +[legend setFrame:CGRectMake(100, 400, legend.frame.size.width, legend.frame.size.height)]; +[self.view addSubview:legend]; + + +//For Pie Chart + +//Build the legend +self.pieChart.legendStyle = PNLegendItemStyleStacked; +self.pieChart.legendFontSize = 12.0; +UIView *legend = [self.pieChart getLegendWithMaxWidth:200]; + +//Move legend to the desired position and add to view +[legend setFrame:CGRectMake(130, 350, legend.frame.size.width, legend.frame.size.height)]; +[self.view addSubview:legend]; +``` + +#### Grid Lines + +Grid lines have been added to PNChart for Line Chart. + +```objective-c +lineChart.showYGridLines = YES; +lineChart.yGridLinesColor = [UIColor grayColor]; +``` + +[![](https://www.dropbox.com/s/sxptjpwgtk32sod/pnchart-gridline.png)](https://www.dropbox.com/s/sxptjpwgtk32sod/pnchart-gridline.png) + +#### Update Value + +Now it's easy to update value in real time + +```objective-c +if ([self.title isEqualToString:@"Line Chart"]) { + + // Line Chart #1 + NSArray * data01Array = @[@(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300)]; + PNLineChartData *data01 = [PNLineChartData new]; + data01.color = PNFreshGreen; + data01.itemCount = data01Array.count; + data01.inflexionPointStyle = PNLineChartPointStyleTriangle; + data01.getData = ^(NSUInteger index) { + CGFloat yValue = [data01Array[index] floatValue]; + return [PNLineChartDataItem dataItemWithY:yValue]; + }; + + // Line Chart #2 + NSArray * data02Array = @[@(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300), @(arc4random() % 300)]; + PNLineChartData *data02 = [PNLineChartData new]; + data02.color = PNTwitterColor; + data02.itemCount = data02Array.count; + data02.inflexionPointStyle = PNLineChartPointStyleSquare; + data02.getData = ^(NSUInteger index) { + CGFloat yValue = [data02Array[index] floatValue]; + return [PNLineChartDataItem dataItemWithY:yValue]; + }; + + [self.lineChart setXLabels:@[@"DEC 1",@"DEC 2",@"DEC 3",@"DEC 4",@"DEC 5",@"DEC 6",@"DEC 7"]]; + [self.lineChart updateChartData:@[data01, data02]]; + +} +else if ([self.title isEqualToString:@"Bar Chart"]) +{ + [self.barChart setXLabels:@[@"Jan 1",@"Jan 2",@"Jan 3",@"Jan 4",@"Jan 5",@"Jan 6",@"Jan 7"]]; + [self.barChart updateChartData:@[@(arc4random() % 30),@(arc4random() % 30),@(arc4random() % 30),@(arc4random() % 30),@(arc4random() % 30),@(arc4random() % 30),@(arc4random() % 30)]]; +} +else if ([self.title isEqualToString:@"Circle Chart"]) +{ + [self.circleChart updateChartByCurrent:@(arc4random() % 100)]; +} +``` + +#### Callback + +```objective-c +#import "PNChart.h" + +//For LineChart + +lineChart.delegate = self; + + +``` + +#### Animation + +Animation is enabled by default when drawing all charts. It can be disabled by setting `displayAnimation = NO`. + +```objective-c +#import "PNChart.h" + +//For LineChart + +lineChart.displayAnimation = NO; + +``` + + + +```objective-c + +//For DelegateMethod + + +-(void)userClickedOnLineKeyPoint:(CGPoint)point lineIndex:(NSInteger)lineIndex pointIndex:(NSInteger)pointIndex{ + NSLog(@"Click Key on line %f, %f line index is %d and point index is %d",point.x, point.y,(int)lineIndex, (int)pointIndex); +} + +-(void)userClickedOnLinePoint:(CGPoint)point lineIndex:(NSInteger)lineIndex{ + NSLog(@"Click on line %f, %f, line index is %d",point.x, point.y, (int)lineIndex); +} + +``` + + +## License + +This code is distributed under the terms and conditions of the [MIT license](LICENSE). + +## SpecialThanks + +[@lexrus](http://twitter.com/lexrus) CocoaPods Spec +[ZhangHang](http://zhanghang.github.com) Pie Chart +[MrWooj](https://github.com/MrWooJ) Scatter Chart + + + diff --git a/Statistics/Pods/Pods.xcodeproj/project.pbxproj b/Statistics/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..1f35128 --- /dev/null +++ b/Statistics/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1122 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 48; + objects = { + +/* Begin PBXBuildFile section */ + 01862E3DCB91BDA0B2F9BF024438DF78 /* PNChart.h in Headers */ = {isa = PBXBuildFile; fileRef = 82AABAD9039A4B89DB215D3B581A3CD0 /* PNChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 06724437C19D93B32D7704B0C849BCB6 /* PNPieChart.h in Headers */ = {isa = PBXBuildFile; fileRef = C88A705D029A08EE26337853E44DEC8C /* PNPieChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0E9A8FBCF70E343103AB476F5BDA9ABE /* PNChart-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E45E5DF839FBB38DE40AC6058147CBA1 /* PNChart-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0F398E26AE00E6F38D5806634A484BFC /* PNRadarChartDataItem.h in Headers */ = {isa = PBXBuildFile; fileRef = 27D52CE5783D84B89AB3B946F5841D50 /* PNRadarChartDataItem.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 417229E1ED51DE115E3B6AD7C1E59B1A /* Timeline.swift */; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7B974F66D49AA5B7C1E4478248C76976 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 216CA8950CE758C7F3C2D6958D5553BA /* Pods-Statistics-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 36788E2CF71665CF4B2A33CF6B7A254D /* Pods-Statistics-dummy.m */; }; + 228396459A5DFEE20A11FCBE2322446B /* UICountingLabel.m in Sources */ = {isa = PBXBuildFile; fileRef = CBED02E08CEA3C991DC56AE134CA2766 /* UICountingLabel.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 23507D26F66CCB366FE0F6C1A0D185D1 /* PNScatterChartDataItem.m in Sources */ = {isa = PBXBuildFile; fileRef = FF9F1EE3B0B15245A7FC3F0539FE134E /* PNScatterChartDataItem.m */; }; + 275CDB94DE5627044CA1E5689E71006A /* PNScatterChartData.m in Sources */ = {isa = PBXBuildFile; fileRef = 0E20F8080D5B6784CA2E2FCF2D03B09B /* PNScatterChartData.m */; }; + 2A670F9A61E0A74AE89985B0AB73EBD8 /* PNPieChartDataItem.h in Headers */ = {isa = PBXBuildFile; fileRef = 7155943CF73184BC116F287CD9253F5C /* PNPieChartDataItem.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30D3210324DB17502F91862D181A5DAA /* PNBar.m in Sources */ = {isa = PBXBuildFile; fileRef = 972FCEBFA0819A1DF937E111DB7E3ADC /* PNBar.m */; }; + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA2CDB07E26CA14AC911709DD27DEBC3 /* TaskDelegate.swift */; }; + 3951AA0F503376DDF9D6FF81717EC1DB /* PNScatterChart.h in Headers */ = {isa = PBXBuildFile; fileRef = 608EDBA789ECC8C3EEFEAE6320C3940B /* PNScatterChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3AFD533C942D8681B68B17BCD3C995F6 /* PNGenericChart.m in Sources */ = {isa = PBXBuildFile; fileRef = 1C56CA57677603736E5C6201C5CBFBDD /* PNGenericChart.m */; }; + 3F006C5DA2EEA45E157440B08535F16C /* PNScatterChartDataItem.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A04C9C5E668A33E10074709A246794C /* PNScatterChartDataItem.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 415EFB6537A3F68F71C09A5B099DCC8A /* PNColor.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BDBDBDC53143F1112688468082F1213 /* PNColor.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 43108E20843C6A047C34B89A63CDE9C6 /* PNChart-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 08CB6A27D678798F50DCA4BAA58BE6B5 /* PNChart-dummy.m */; }; + 47EB05F507CC96A5A8778049FA04E494 /* PNLineChart.m in Sources */ = {isa = PBXBuildFile; fileRef = 5793313679BEC3A3EBE360414C7D9382 /* PNLineChart.m */; }; + 49DBBCC302C3055F99A1F860042CC4CE /* PNBarChart.h in Headers */ = {isa = PBXBuildFile; fileRef = 93C95ED14572694F6028C9C47A43A363 /* PNBarChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4D871E78B0F660F6B50FC41EF7462E97 /* PNRadarChart.m in Sources */ = {isa = PBXBuildFile; fileRef = E31E1DE0CB21A920421D2BF5DEFBA7EA /* PNRadarChart.m */; }; + 4E546FE3E7EC37C7300F189766082A39 /* UICountingLabel.h in Headers */ = {isa = PBXBuildFile; fileRef = E35A98585D4E8B8DEA4D2F7DB454E74B /* UICountingLabel.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8805159646FD72987D881B7221B7D449 /* Request.swift */; }; + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9124BEB2A7092D04EE40A333EADECC0D /* DispatchQueue+Alamofire.swift */; }; + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F560B1EFBDAECB3926D85A45AEE36A9 /* ServerTrustPolicy.swift */; }; + 63B2B60C4E0425695947C754528998EA /* PNScatterChartData.h in Headers */ = {isa = PBXBuildFile; fileRef = FC72DDEE0958EEB5FF7918AEF6322272 /* PNScatterChartData.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6D791026E20DF9A2B254FD7D11D6DB39 /* PNRadarChartDataItem.m in Sources */ = {isa = PBXBuildFile; fileRef = C54890DECEF3CF0CD770F07028965494 /* PNRadarChartDataItem.m */; }; + 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE4A990FF58368664D6B75F3465171E3 /* Foundation.framework */; }; + 79A1A20C26E7759F31EE5A64D90F8E6F /* PNLineChartData.h in Headers */ = {isa = PBXBuildFile; fileRef = D2C2B516724E6D34E85B16FC38D84AF2 /* PNLineChartData.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CCE268C7FB6576150B0DBA92BAEA103 /* SessionDelegate.swift */; }; + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96B7B6366A8D83FB673A49EB5B29E7A1 /* Result.swift */; }; + 83CA2377B55DD2D5EB6DE486AC459A54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE4A990FF58368664D6B75F3465171E3 /* Foundation.framework */; }; + 884AA25551C1E0897CB5332890C4A400 /* UICountingLabel-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED54F46B0A280FE581A269B122359AB /* UICountingLabel-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8D0A8407E6C2577C48DEDBF16BF8B469 /* PNLineChart.h in Headers */ = {isa = PBXBuildFile; fileRef = 40954A2A3FB7A109909D4FD6169A677D /* PNLineChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8E1DEC97CC5767A4B537AA988BE21B6D /* PNPieChart.m in Sources */ = {isa = PBXBuildFile; fileRef = F7CBA821CAA08137AE42C0A8F2FBD55A /* PNPieChart.m */; }; + 8ED82E4BB5088B3BC288B53EFD9B9106 /* PNLineChartData.m in Sources */ = {isa = PBXBuildFile; fileRef = 679382CD9F1D26EA0D42B763C11E6129 /* PNLineChartData.m */; }; + 975E65AF5274D9E271902795BBE5AD9B /* UICountingLabel.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B9103AD49AA73F4AFAC5A6BD63F2B787 /* UICountingLabel.framework */; }; + 9A188B2744B9ADBAE00CA89FF8A04B16 /* PNCircleChart.h in Headers */ = {isa = PBXBuildFile; fileRef = D2CEC0A546DD1879053180C732FA15EC /* PNCircleChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9BADCA5679C8A8A66E61ADDDB0632098 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 10089A14B451E9A962D07579E4163155 /* CoreGraphics.framework */; }; + 9D463C13702FAEA9AA93F1FC99655BD8 /* PNChartLabel.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BD12B94B13C099FDF15EDECCFAEADF5 /* PNChartLabel.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFE8EA9C6AE4B6CF98F417C1E8321CAD /* AFError.swift */; }; + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74840868C78D7FE167A4813D8A48B278 /* NetworkReachabilityManager.swift */; }; + A82EC72D21AA1A6C2B032151382074BE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE4A990FF58368664D6B75F3465171E3 /* Foundation.framework */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 29DB46C2E9C4F5AE998D11599A8B6A0D /* Alamofire-dummy.m */; }; + ADB66EDB01E996BC6F5BFFD4534B6C21 /* PNLineChartDataItem.h in Headers */ = {isa = PBXBuildFile; fileRef = A8DB161F9C399E5D50657218B93DB310 /* PNLineChartDataItem.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FA12CDC0A64206F040E73B49024483 /* SessionManager.swift */; }; + B3174CE1F7CEC7E4986A14E9C4EAA5ED /* UICountingLabel-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0696B77774737F2E9D57C8E5BA420C15 /* UICountingLabel-dummy.m */; }; + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2DE35F2A3E68E17A04C6F0E5E938D3C /* MultipartFormData.swift */; }; + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C67BDFEFC7E4BF3FB6363BA1CEDA9332 /* Validation.swift */; }; + BCA98672348F4BE5B74F67CCEB68B3AE /* PNBar.h in Headers */ = {isa = PBXBuildFile; fileRef = 769F565368991094EA39D7DA612D454F /* PNBar.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = B02FD91CE4256FD0A0F9E077BA583CAB /* ParameterEncoding.swift */; }; + C344EA4B1862D8F0074DAE36CE9F08A2 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67942C696292CC592FBEE3BA3005E34E /* UIKit.framework */; }; + CA847ADF445C8C5454B1999A89D1F137 /* PNChartDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 5827840B9987E14FAD556D34EB853E22 /* PNChartDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A05340EB416AB78BDC3412F3A1E0D32 /* Response.swift */; }; + D46DF427577E7AB87ED36E29CD8937D9 /* PNLineChartDataItem.m in Sources */ = {isa = PBXBuildFile; fileRef = 246A54566A9307FD647B948AE1BE0FDE /* PNLineChartDataItem.m */; }; + D5B80188A15B27E153C28E008225B9D8 /* Pods-Statistics-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 899923C6DD73F81E357A0D9959037D1C /* Pods-Statistics-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DAAB15D1FF9B62D061DF3A73E8D11050 /* PNRadarChart.h in Headers */ = {isa = PBXBuildFile; fileRef = E99C697703CFC70C75665A53DB805D4D /* PNRadarChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DCB7CC08FC235B33EDC5F8957848B565 /* PNGenericChart.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B08C36F21E09C1106B8CBB3AD0586AA /* PNGenericChart.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DF8F4C447D73F08682A89276EB7924E7 /* PNPieChartDataItem.m in Sources */ = {isa = PBXBuildFile; fileRef = 814FDC817016644683D16EB5C144EB8C /* PNPieChartDataItem.m */; }; + E6543B0E8A962B065B29B9E4EE1A904D /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 203ED675A3265A07DB1F1BB031CD518C /* QuartzCore.framework */; }; + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D512D43A199B45420206C9D76F8FE09 /* Notifications.swift */; }; + F3B69FAAAA7F3B62E1130C2DD172C986 /* PNScatterChart.m in Sources */ = {isa = PBXBuildFile; fileRef = FE181AAE66703920B646270DBFC62BEC /* PNScatterChart.m */; }; + F518C92F8521475ACF30FA6ABCB4768F /* PNCircleChart.m in Sources */ = {isa = PBXBuildFile; fileRef = D1B022C9D4A47987CB9165AFF15EF68A /* PNCircleChart.m */; }; + F6437A9168D825D17B7E2BF5C1C2E81D /* PNChartLabel.m in Sources */ = {isa = PBXBuildFile; fileRef = 82C992F8626DBBD574AFF921B4768D03 /* PNChartLabel.m */; }; + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C0FEB369051A169F69EAB63B14669D6 /* ResponseSerialization.swift */; }; + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA42D9C719D12755378822CD9D82A941 /* Alamofire.swift */; }; + FC0638C57BE88E9577E9989B97D1E099 /* PNBarChart.m in Sources */ = {isa = PBXBuildFile; fileRef = 674275BD2E47A19982861853EC545218 /* PNBarChart.m */; }; + FCC1436792EA4C37502DE74FC2DCDEF4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE4A990FF58368664D6B75F3465171E3 /* Foundation.framework */; }; + FF884F1ECBE6F4B32FB84E46AD8C28A9 /* PNColor.m in Sources */ = {isa = PBXBuildFile; fileRef = ECBBEA32A45B2380858A4472074AD34B /* PNColor.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 2331FC354592179C10840D17D20A7DB0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = DA392EE8E5B24D16FB9910405A0AFC2E; + remoteInfo = UICountingLabel; + }; + 35DD533EFC779F022F1DBC6A54439038 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; + BAC05021060300E06F62A85C4689E1EE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0FC1CB21D1B64FAAC47A6478616DA728; + remoteInfo = PNChart; + }; + DE1DD72CBE9AF5DF2A79E56A1829F476 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = DA392EE8E5B24D16FB9910405A0AFC2E; + remoteInfo = UICountingLabel; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 06349363AE8DE31E79184A782F13A33E /* PNChart.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PNChart.framework; path = PNChart.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0696B77774737F2E9D57C8E5BA420C15 /* UICountingLabel-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "UICountingLabel-dummy.m"; sourceTree = ""; }; + 06BAD70572D37CCCBDE6781063A69DA3 /* Pods-Statistics-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Statistics-resources.sh"; sourceTree = ""; }; + 08CB6A27D678798F50DCA4BAA58BE6B5 /* PNChart-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PNChart-dummy.m"; sourceTree = ""; }; + 0A04C9C5E668A33E10074709A246794C /* PNScatterChartDataItem.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNScatterChartDataItem.h; path = PNChart/PNScatterChartDataItem.h; sourceTree = ""; }; + 0E20F8080D5B6784CA2E2FCF2D03B09B /* PNScatterChartData.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNScatterChartData.m; path = PNChart/PNScatterChartData.m; sourceTree = ""; }; + 0F18AF982D6C17AF24D414537E0D9FB5 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; + 10089A14B451E9A962D07579E4163155 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/CoreGraphics.framework; sourceTree = DEVELOPER_DIR; }; + 13F7CE1C4258F44867B671A7AC903043 /* PNChart.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PNChart.xcconfig; sourceTree = ""; }; + 1C56CA57677603736E5C6201C5CBFBDD /* PNGenericChart.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNGenericChart.m; path = PNChart/PNGenericChart.m; sourceTree = ""; }; + 203ED675A3265A07DB1F1BB031CD518C /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; + 246A54566A9307FD647B948AE1BE0FDE /* PNLineChartDataItem.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNLineChartDataItem.m; path = PNChart/PNLineChartDataItem.m; sourceTree = ""; }; + 278A6DADF8B259450E4EC2320F5AF032 /* UICountingLabel.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = UICountingLabel.xcconfig; sourceTree = ""; }; + 27D52CE5783D84B89AB3B946F5841D50 /* PNRadarChartDataItem.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNRadarChartDataItem.h; path = PNChart/PNRadarChartDataItem.h; sourceTree = ""; }; + 29DB46C2E9C4F5AE998D11599A8B6A0D /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 2CBB0997F236FB50E2AFD52CD87050C0 /* Pods-Statistics-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Statistics-acknowledgements.plist"; sourceTree = ""; }; + 35FA12CDC0A64206F040E73B49024483 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 36788E2CF71665CF4B2A33CF6B7A254D /* Pods-Statistics-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Statistics-dummy.m"; sourceTree = ""; }; + 3BD12B94B13C099FDF15EDECCFAEADF5 /* PNChartLabel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNChartLabel.h; path = PNChart/PNChartLabel.h; sourceTree = ""; }; + 3D512D43A199B45420206C9D76F8FE09 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 3F560B1EFBDAECB3926D85A45AEE36A9 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 40954A2A3FB7A109909D4FD6169A677D /* PNLineChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNLineChart.h; path = PNChart/PNLineChart.h; sourceTree = ""; }; + 417229E1ED51DE115E3B6AD7C1E59B1A /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 4B08C36F21E09C1106B8CBB3AD0586AA /* PNGenericChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNGenericChart.h; path = PNChart/PNGenericChart.h; sourceTree = ""; }; + 4E0FFC53AD0935BB532896433248FBAF /* Pods-Statistics.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-Statistics.modulemap"; sourceTree = ""; }; + 4FA6478BC6E814050715F99257E8DCE7 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 54EA2BB9B8AF50358EA4929CAA8CD991 /* Pods-Statistics-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Statistics-acknowledgements.markdown"; sourceTree = ""; }; + 5707CD5148C2CD5C4A94F58B8E476D50 /* UICountingLabel.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = UICountingLabel.modulemap; sourceTree = ""; }; + 5793313679BEC3A3EBE360414C7D9382 /* PNLineChart.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNLineChart.m; path = PNChart/PNLineChart.m; sourceTree = ""; }; + 5827840B9987E14FAD556D34EB853E22 /* PNChartDelegate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNChartDelegate.h; path = PNChart/PNChartDelegate.h; sourceTree = ""; }; + 5A05340EB416AB78BDC3412F3A1E0D32 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 608EDBA789ECC8C3EEFEAE6320C3940B /* PNScatterChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNScatterChart.h; path = PNChart/PNScatterChart.h; sourceTree = ""; }; + 66A3ED553EA08463C9CD7D19E6FD6E4D /* Pods-Statistics.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Statistics.debug.xcconfig"; sourceTree = ""; }; + 674275BD2E47A19982861853EC545218 /* PNBarChart.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNBarChart.m; path = PNChart/PNBarChart.m; sourceTree = ""; }; + 679382CD9F1D26EA0D42B763C11E6129 /* PNLineChartData.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNLineChartData.m; path = PNChart/PNLineChartData.m; sourceTree = ""; }; + 67942C696292CC592FBEE3BA3005E34E /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 7155943CF73184BC116F287CD9253F5C /* PNPieChartDataItem.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNPieChartDataItem.h; path = PNChart/PNPieChartDataItem.h; sourceTree = ""; }; + 74840868C78D7FE167A4813D8A48B278 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 769F565368991094EA39D7DA612D454F /* PNBar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNBar.h; path = PNChart/PNBar.h; sourceTree = ""; }; + 7B375706E13615EDD0BDB36E7B7734C5 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7B974F66D49AA5B7C1E4478248C76976 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 7C0FEB369051A169F69EAB63B14669D6 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 7CD5FAB5F43BF79E752880E03B08AC4A /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 7ED54F46B0A280FE581A269B122359AB /* UICountingLabel-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "UICountingLabel-umbrella.h"; sourceTree = ""; }; + 7F35D67BE24CA8FE9E8F1E585A4E62FE /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 7F9F21F1099336ED8B2A04AC5EC8487A /* PNChart.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = PNChart.modulemap; sourceTree = ""; }; + 814FDC817016644683D16EB5C144EB8C /* PNPieChartDataItem.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNPieChartDataItem.m; path = PNChart/PNPieChartDataItem.m; sourceTree = ""; }; + 82AABAD9039A4B89DB215D3B581A3CD0 /* PNChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNChart.h; path = PNChart/PNChart.h; sourceTree = ""; }; + 82C992F8626DBBD574AFF921B4768D03 /* PNChartLabel.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNChartLabel.m; path = PNChart/PNChartLabel.m; sourceTree = ""; }; + 856E53DD6BFA402426D8F7BAF677AFB3 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 8805159646FD72987D881B7221B7D449 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 899923C6DD73F81E357A0D9959037D1C /* Pods-Statistics-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Statistics-umbrella.h"; sourceTree = ""; }; + 9117010FD8486E6E87181C159BA18EA7 /* Pods-Statistics.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Statistics.release.xcconfig"; sourceTree = ""; }; + 9124BEB2A7092D04EE40A333EADECC0D /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 93C95ED14572694F6028C9C47A43A363 /* PNBarChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNBarChart.h; path = PNChart/PNBarChart.h; sourceTree = ""; }; + 96B7B6366A8D83FB673A49EB5B29E7A1 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 972FCEBFA0819A1DF937E111DB7E3ADC /* PNBar.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNBar.m; path = PNChart/PNBar.m; sourceTree = ""; }; + 9BDBDBDC53143F1112688468082F1213 /* PNColor.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNColor.h; path = PNChart/PNColor.h; sourceTree = ""; }; + 9CCE268C7FB6576150B0DBA92BAEA103 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 9E9822CBD56525BA9332CE44F629491A /* Pods-Statistics-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Statistics-frameworks.sh"; sourceTree = ""; }; + A1EE057330F117D05270AEB3803EB099 /* UICountingLabel-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "UICountingLabel-prefix.pch"; sourceTree = ""; }; + A8DB161F9C399E5D50657218B93DB310 /* PNLineChartDataItem.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNLineChartDataItem.h; path = PNChart/PNLineChartDataItem.h; sourceTree = ""; }; + AE4A990FF58368664D6B75F3465171E3 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + B02FD91CE4256FD0A0F9E077BA583CAB /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + B9103AD49AA73F4AFAC5A6BD63F2B787 /* UICountingLabel.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = UICountingLabel.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + BFE8EA9C6AE4B6CF98F417C1E8321CAD /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + C54890DECEF3CF0CD770F07028965494 /* PNRadarChartDataItem.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNRadarChartDataItem.m; path = PNChart/PNRadarChartDataItem.m; sourceTree = ""; }; + C67BDFEFC7E4BF3FB6363BA1CEDA9332 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + C88A705D029A08EE26337853E44DEC8C /* PNPieChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNPieChart.h; path = PNChart/PNPieChart.h; sourceTree = ""; }; + CA42D9C719D12755378822CD9D82A941 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + CBB9B54EC06AC4CE952639F6EABAE76A /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + CBED02E08CEA3C991DC56AE134CA2766 /* UICountingLabel.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = UICountingLabel.m; sourceTree = ""; }; + CF3D102FA39A274EA09BE2C4E6BF823C /* UICountingLabel.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = UICountingLabel.framework; path = UICountingLabel.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D1B022C9D4A47987CB9165AFF15EF68A /* PNCircleChart.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNCircleChart.m; path = PNChart/PNCircleChart.m; sourceTree = ""; }; + D2C2B516724E6D34E85B16FC38D84AF2 /* PNLineChartData.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNLineChartData.h; path = PNChart/PNLineChartData.h; sourceTree = ""; }; + D2CEC0A546DD1879053180C732FA15EC /* PNCircleChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNCircleChart.h; path = PNChart/PNCircleChart.h; sourceTree = ""; }; + D609EA77E9707F94DA7606959196074F /* Pods_Statistics.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_Statistics.framework; path = "Pods-Statistics.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + E2DE35F2A3E68E17A04C6F0E5E938D3C /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + E31E1DE0CB21A920421D2BF5DEFBA7EA /* PNRadarChart.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNRadarChart.m; path = PNChart/PNRadarChart.m; sourceTree = ""; }; + E35A98585D4E8B8DEA4D2F7DB454E74B /* UICountingLabel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = UICountingLabel.h; sourceTree = ""; }; + E45E5DF839FBB38DE40AC6058147CBA1 /* PNChart-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PNChart-umbrella.h"; sourceTree = ""; }; + E57FC0CA252F2210BCFB78114B97735A /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E99C697703CFC70C75665A53DB805D4D /* PNRadarChart.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNRadarChart.h; path = PNChart/PNRadarChart.h; sourceTree = ""; }; + EA2CDB07E26CA14AC911709DD27DEBC3 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + ECBBEA32A45B2380858A4472074AD34B /* PNColor.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNColor.m; path = PNChart/PNColor.m; sourceTree = ""; }; + F7CBA821CAA08137AE42C0A8F2FBD55A /* PNPieChart.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNPieChart.m; path = PNChart/PNPieChart.m; sourceTree = ""; }; + FBD1805DA7C25DDEC0FD7242E9562EF7 /* PNChart-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PNChart-prefix.pch"; sourceTree = ""; }; + FC72DDEE0958EEB5FF7918AEF6322272 /* PNScatterChartData.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PNScatterChartData.h; path = PNChart/PNScatterChartData.h; sourceTree = ""; }; + FE181AAE66703920B646270DBFC62BEC /* PNScatterChart.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNScatterChart.m; path = PNChart/PNScatterChart.m; sourceTree = ""; }; + FF9F1EE3B0B15245A7FC3F0539FE134E /* PNScatterChartDataItem.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = PNScatterChartDataItem.m; path = PNChart/PNScatterChartDataItem.m; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 560B48E5B735F6ABF54BFBC98984163E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A82EC72D21AA1A6C2B032151382074BE /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5C90B6B33EA9D9A517DF08F0116E9AC9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + FCC1436792EA4C37502DE74FC2DCDEF4 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 848FFABBBE25F555B7C8843674FAB8E0 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 9BADCA5679C8A8A66E61ADDDB0632098 /* CoreGraphics.framework in Frameworks */, + 83CA2377B55DD2D5EB6DE486AC459A54 /* Foundation.framework in Frameworks */, + E6543B0E8A962B065B29B9E4EE1A904D /* QuartzCore.framework in Frameworks */, + 975E65AF5274D9E271902795BBE5AD9B /* UICountingLabel.framework in Frameworks */, + C344EA4B1862D8F0074DAE36CE9F08A2 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0028FFF65D2C0A793D30000BC75ACE86 /* PNChart */ = { + isa = PBXGroup; + children = ( + 769F565368991094EA39D7DA612D454F /* PNBar.h */, + 972FCEBFA0819A1DF937E111DB7E3ADC /* PNBar.m */, + 93C95ED14572694F6028C9C47A43A363 /* PNBarChart.h */, + 674275BD2E47A19982861853EC545218 /* PNBarChart.m */, + 82AABAD9039A4B89DB215D3B581A3CD0 /* PNChart.h */, + 5827840B9987E14FAD556D34EB853E22 /* PNChartDelegate.h */, + 3BD12B94B13C099FDF15EDECCFAEADF5 /* PNChartLabel.h */, + 82C992F8626DBBD574AFF921B4768D03 /* PNChartLabel.m */, + D2CEC0A546DD1879053180C732FA15EC /* PNCircleChart.h */, + D1B022C9D4A47987CB9165AFF15EF68A /* PNCircleChart.m */, + 9BDBDBDC53143F1112688468082F1213 /* PNColor.h */, + ECBBEA32A45B2380858A4472074AD34B /* PNColor.m */, + 4B08C36F21E09C1106B8CBB3AD0586AA /* PNGenericChart.h */, + 1C56CA57677603736E5C6201C5CBFBDD /* PNGenericChart.m */, + 40954A2A3FB7A109909D4FD6169A677D /* PNLineChart.h */, + 5793313679BEC3A3EBE360414C7D9382 /* PNLineChart.m */, + D2C2B516724E6D34E85B16FC38D84AF2 /* PNLineChartData.h */, + 679382CD9F1D26EA0D42B763C11E6129 /* PNLineChartData.m */, + A8DB161F9C399E5D50657218B93DB310 /* PNLineChartDataItem.h */, + 246A54566A9307FD647B948AE1BE0FDE /* PNLineChartDataItem.m */, + C88A705D029A08EE26337853E44DEC8C /* PNPieChart.h */, + F7CBA821CAA08137AE42C0A8F2FBD55A /* PNPieChart.m */, + 7155943CF73184BC116F287CD9253F5C /* PNPieChartDataItem.h */, + 814FDC817016644683D16EB5C144EB8C /* PNPieChartDataItem.m */, + E99C697703CFC70C75665A53DB805D4D /* PNRadarChart.h */, + E31E1DE0CB21A920421D2BF5DEFBA7EA /* PNRadarChart.m */, + 27D52CE5783D84B89AB3B946F5841D50 /* PNRadarChartDataItem.h */, + C54890DECEF3CF0CD770F07028965494 /* PNRadarChartDataItem.m */, + 608EDBA789ECC8C3EEFEAE6320C3940B /* PNScatterChart.h */, + FE181AAE66703920B646270DBFC62BEC /* PNScatterChart.m */, + FC72DDEE0958EEB5FF7918AEF6322272 /* PNScatterChartData.h */, + 0E20F8080D5B6784CA2E2FCF2D03B09B /* PNScatterChartData.m */, + 0A04C9C5E668A33E10074709A246794C /* PNScatterChartDataItem.h */, + FF9F1EE3B0B15245A7FC3F0539FE134E /* PNScatterChartDataItem.m */, + 98C36A616C8DFA1CB74B3573B8DADCE0 /* Support Files */, + ); + name = PNChart; + path = PNChart; + sourceTree = ""; + }; + 15FB84CF6A35C99D23A5CE574ECF26C0 /* Pods-Statistics */ = { + isa = PBXGroup; + children = ( + CBB9B54EC06AC4CE952639F6EABAE76A /* Info.plist */, + 4E0FFC53AD0935BB532896433248FBAF /* Pods-Statistics.modulemap */, + 54EA2BB9B8AF50358EA4929CAA8CD991 /* Pods-Statistics-acknowledgements.markdown */, + 2CBB0997F236FB50E2AFD52CD87050C0 /* Pods-Statistics-acknowledgements.plist */, + 36788E2CF71665CF4B2A33CF6B7A254D /* Pods-Statistics-dummy.m */, + 9E9822CBD56525BA9332CE44F629491A /* Pods-Statistics-frameworks.sh */, + 06BAD70572D37CCCBDE6781063A69DA3 /* Pods-Statistics-resources.sh */, + 899923C6DD73F81E357A0D9959037D1C /* Pods-Statistics-umbrella.h */, + 66A3ED553EA08463C9CD7D19E6FD6E4D /* Pods-Statistics.debug.xcconfig */, + 9117010FD8486E6E87181C159BA18EA7 /* Pods-Statistics.release.xcconfig */, + ); + name = "Pods-Statistics"; + path = "Target Support Files/Pods-Statistics"; + sourceTree = ""; + }; + 56297B450AF0D3009B32107F491F2EAC /* Pods */ = { + isa = PBXGroup; + children = ( + 8C16811D57A93B3EDF68A907335681C0 /* Alamofire */, + 0028FFF65D2C0A793D30000BC75ACE86 /* PNChart */, + 565B5DEC4CF23E1AA385253F58D5FAED /* UICountingLabel */, + ); + name = Pods; + sourceTree = ""; + }; + 565B5DEC4CF23E1AA385253F58D5FAED /* UICountingLabel */ = { + isa = PBXGroup; + children = ( + E35A98585D4E8B8DEA4D2F7DB454E74B /* UICountingLabel.h */, + CBED02E08CEA3C991DC56AE134CA2766 /* UICountingLabel.m */, + E26BBD6DE373D24E4A062EA872CCFFC4 /* Support Files */, + ); + name = UICountingLabel; + path = UICountingLabel; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + E7558378B05AD4CBD1053EABE1357F06 /* Frameworks */, + 56297B450AF0D3009B32107F491F2EAC /* Pods */, + F2ACF58923632D7C39593AE7728CBC96 /* Products */, + C8ACFF41D75460933D845F1134FE030C /* Targets Support Files */, + ); + sourceTree = ""; + }; + 7E8DD510386F2532AE6A6B8A7FCDE421 /* iOS */ = { + isa = PBXGroup; + children = ( + 10089A14B451E9A962D07579E4163155 /* CoreGraphics.framework */, + AE4A990FF58368664D6B75F3465171E3 /* Foundation.framework */, + 203ED675A3265A07DB1F1BB031CD518C /* QuartzCore.framework */, + 67942C696292CC592FBEE3BA3005E34E /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 8C16811D57A93B3EDF68A907335681C0 /* Alamofire */ = { + isa = PBXGroup; + children = ( + BFE8EA9C6AE4B6CF98F417C1E8321CAD /* AFError.swift */, + CA42D9C719D12755378822CD9D82A941 /* Alamofire.swift */, + 9124BEB2A7092D04EE40A333EADECC0D /* DispatchQueue+Alamofire.swift */, + E2DE35F2A3E68E17A04C6F0E5E938D3C /* MultipartFormData.swift */, + 74840868C78D7FE167A4813D8A48B278 /* NetworkReachabilityManager.swift */, + 3D512D43A199B45420206C9D76F8FE09 /* Notifications.swift */, + B02FD91CE4256FD0A0F9E077BA583CAB /* ParameterEncoding.swift */, + 8805159646FD72987D881B7221B7D449 /* Request.swift */, + 5A05340EB416AB78BDC3412F3A1E0D32 /* Response.swift */, + 7C0FEB369051A169F69EAB63B14669D6 /* ResponseSerialization.swift */, + 96B7B6366A8D83FB673A49EB5B29E7A1 /* Result.swift */, + 3F560B1EFBDAECB3926D85A45AEE36A9 /* ServerTrustPolicy.swift */, + 9CCE268C7FB6576150B0DBA92BAEA103 /* SessionDelegate.swift */, + 35FA12CDC0A64206F040E73B49024483 /* SessionManager.swift */, + EA2CDB07E26CA14AC911709DD27DEBC3 /* TaskDelegate.swift */, + 417229E1ED51DE115E3B6AD7C1E59B1A /* Timeline.swift */, + C67BDFEFC7E4BF3FB6363BA1CEDA9332 /* Validation.swift */, + 9FAB5003C18BBC885B6611BEB32215E8 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + 98C36A616C8DFA1CB74B3573B8DADCE0 /* Support Files */ = { + isa = PBXGroup; + children = ( + 856E53DD6BFA402426D8F7BAF677AFB3 /* Info.plist */, + 7F9F21F1099336ED8B2A04AC5EC8487A /* PNChart.modulemap */, + 13F7CE1C4258F44867B671A7AC903043 /* PNChart.xcconfig */, + 08CB6A27D678798F50DCA4BAA58BE6B5 /* PNChart-dummy.m */, + FBD1805DA7C25DDEC0FD7242E9562EF7 /* PNChart-prefix.pch */, + E45E5DF839FBB38DE40AC6058147CBA1 /* PNChart-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/PNChart"; + sourceTree = ""; + }; + 9FAB5003C18BBC885B6611BEB32215E8 /* Support Files */ = { + isa = PBXGroup; + children = ( + 0F18AF982D6C17AF24D414537E0D9FB5 /* Alamofire.modulemap */, + 7F35D67BE24CA8FE9E8F1E585A4E62FE /* Alamofire.xcconfig */, + 29DB46C2E9C4F5AE998D11599A8B6A0D /* Alamofire-dummy.m */, + 7CD5FAB5F43BF79E752880E03B08AC4A /* Alamofire-prefix.pch */, + 7B974F66D49AA5B7C1E4478248C76976 /* Alamofire-umbrella.h */, + E57FC0CA252F2210BCFB78114B97735A /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + C8ACFF41D75460933D845F1134FE030C /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 15FB84CF6A35C99D23A5CE574ECF26C0 /* Pods-Statistics */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + E26BBD6DE373D24E4A062EA872CCFFC4 /* Support Files */ = { + isa = PBXGroup; + children = ( + 7B375706E13615EDD0BDB36E7B7734C5 /* Info.plist */, + 5707CD5148C2CD5C4A94F58B8E476D50 /* UICountingLabel.modulemap */, + 278A6DADF8B259450E4EC2320F5AF032 /* UICountingLabel.xcconfig */, + 0696B77774737F2E9D57C8E5BA420C15 /* UICountingLabel-dummy.m */, + A1EE057330F117D05270AEB3803EB099 /* UICountingLabel-prefix.pch */, + 7ED54F46B0A280FE581A269B122359AB /* UICountingLabel-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/UICountingLabel"; + sourceTree = ""; + }; + E7558378B05AD4CBD1053EABE1357F06 /* Frameworks */ = { + isa = PBXGroup; + children = ( + B9103AD49AA73F4AFAC5A6BD63F2B787 /* UICountingLabel.framework */, + 7E8DD510386F2532AE6A6B8A7FCDE421 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + F2ACF58923632D7C39593AE7728CBC96 /* Products */ = { + isa = PBXGroup; + children = ( + 4FA6478BC6E814050715F99257E8DCE7 /* Alamofire.framework */, + 06349363AE8DE31E79184A782F13A33E /* PNChart.framework */, + D609EA77E9707F94DA7606959196074F /* Pods_Statistics.framework */, + CF3D102FA39A274EA09BE2C4E6BF823C /* UICountingLabel.framework */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 211C4D1C0ADFD781AD42B45CE9C134F1 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + BCA98672348F4BE5B74F67CCEB68B3AE /* PNBar.h in Headers */, + 49DBBCC302C3055F99A1F860042CC4CE /* PNBarChart.h in Headers */, + 0E9A8FBCF70E343103AB476F5BDA9ABE /* PNChart-umbrella.h in Headers */, + 01862E3DCB91BDA0B2F9BF024438DF78 /* PNChart.h in Headers */, + CA847ADF445C8C5454B1999A89D1F137 /* PNChartDelegate.h in Headers */, + 9D463C13702FAEA9AA93F1FC99655BD8 /* PNChartLabel.h in Headers */, + 9A188B2744B9ADBAE00CA89FF8A04B16 /* PNCircleChart.h in Headers */, + 415EFB6537A3F68F71C09A5B099DCC8A /* PNColor.h in Headers */, + DCB7CC08FC235B33EDC5F8957848B565 /* PNGenericChart.h in Headers */, + 8D0A8407E6C2577C48DEDBF16BF8B469 /* PNLineChart.h in Headers */, + 79A1A20C26E7759F31EE5A64D90F8E6F /* PNLineChartData.h in Headers */, + ADB66EDB01E996BC6F5BFFD4534B6C21 /* PNLineChartDataItem.h in Headers */, + 06724437C19D93B32D7704B0C849BCB6 /* PNPieChart.h in Headers */, + 2A670F9A61E0A74AE89985B0AB73EBD8 /* PNPieChartDataItem.h in Headers */, + DAAB15D1FF9B62D061DF3A73E8D11050 /* PNRadarChart.h in Headers */, + 0F398E26AE00E6F38D5806634A484BFC /* PNRadarChartDataItem.h in Headers */, + 3951AA0F503376DDF9D6FF81717EC1DB /* PNScatterChart.h in Headers */, + 63B2B60C4E0425695947C754528998EA /* PNScatterChartData.h in Headers */, + 3F006C5DA2EEA45E157440B08535F16C /* PNScatterChartDataItem.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 89C3E02DAFB3D0F4AF244CFA0D86EF4C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 884AA25551C1E0897CB5332890C4A400 /* UICountingLabel-umbrella.h in Headers */, + 4E546FE3E7EC37C7300F189766082A39 /* UICountingLabel.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AB2862E61D92B95A63494C763093D377 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + D5B80188A15B27E153C28E008225B9D8 /* Pods-Statistics-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 0FC1CB21D1B64FAAC47A6478616DA728 /* PNChart */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6A92B5FD027CE987470A48E671364959 /* Build configuration list for PBXNativeTarget "PNChart" */; + buildPhases = ( + 5EADEFF53DB0153A85451A7650D5A735 /* Sources */, + 848FFABBBE25F555B7C8843674FAB8E0 /* Frameworks */, + 211C4D1C0ADFD781AD42B45CE9C134F1 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + B6E55E784799B63E23A928EA091109E7 /* PBXTargetDependency */, + ); + name = PNChart; + productName = PNChart; + productReference = 06349363AE8DE31E79184A782F13A33E /* PNChart.framework */; + productType = "com.apple.product-type.framework"; + }; + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 32B9974868188C4803318E36329C87FE /* Sources */, + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 4FA6478BC6E814050715F99257E8DCE7 /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + D4FFAFAEFE0F87BF6FEF4F5BAA66F4C1 /* Pods-Statistics */ = { + isa = PBXNativeTarget; + buildConfigurationList = 76021F35178C17DBECFE29E5681829C1 /* Build configuration list for PBXNativeTarget "Pods-Statistics" */; + buildPhases = ( + 236B9F5AF2A4534C95D23F486E47E8E1 /* Sources */, + 560B48E5B735F6ABF54BFBC98984163E /* Frameworks */, + AB2862E61D92B95A63494C763093D377 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 1B729C0463346838068098A4B437DAE4 /* PBXTargetDependency */, + 8C4570491CFBB36A8FE3BB1E56CC059A /* PBXTargetDependency */, + 0D042F6E4C509AE913E3A90AEDD57AEB /* PBXTargetDependency */, + ); + name = "Pods-Statistics"; + productName = "Pods-Statistics"; + productReference = D609EA77E9707F94DA7606959196074F /* Pods_Statistics.framework */; + productType = "com.apple.product-type.framework"; + }; + DA392EE8E5B24D16FB9910405A0AFC2E /* UICountingLabel */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9A22DE6618BE94C542426A3608C6D3E5 /* Build configuration list for PBXNativeTarget "UICountingLabel" */; + buildPhases = ( + B1C9814C48D22FEA9B79FC3347917297 /* Sources */, + 5C90B6B33EA9D9A517DF08F0116E9AC9 /* Frameworks */, + 89C3E02DAFB3D0F4AF244CFA0D86EF4C /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = UICountingLabel; + productName = UICountingLabel; + productReference = CF3D102FA39A274EA09BE2C4E6BF823C /* UICountingLabel.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0830; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = F2ACF58923632D7C39593AE7728CBC96 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, + 0FC1CB21D1B64FAAC47A6478616DA728 /* PNChart */, + D4FFAFAEFE0F87BF6FEF4F5BAA66F4C1 /* Pods-Statistics */, + DA392EE8E5B24D16FB9910405A0AFC2E /* UICountingLabel */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 236B9F5AF2A4534C95D23F486E47E8E1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 216CA8950CE758C7F3C2D6958D5553BA /* Pods-Statistics-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 32B9974868188C4803318E36329C87FE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5EADEFF53DB0153A85451A7650D5A735 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 30D3210324DB17502F91862D181A5DAA /* PNBar.m in Sources */, + FC0638C57BE88E9577E9989B97D1E099 /* PNBarChart.m in Sources */, + 43108E20843C6A047C34B89A63CDE9C6 /* PNChart-dummy.m in Sources */, + F6437A9168D825D17B7E2BF5C1C2E81D /* PNChartLabel.m in Sources */, + F518C92F8521475ACF30FA6ABCB4768F /* PNCircleChart.m in Sources */, + FF884F1ECBE6F4B32FB84E46AD8C28A9 /* PNColor.m in Sources */, + 3AFD533C942D8681B68B17BCD3C995F6 /* PNGenericChart.m in Sources */, + 47EB05F507CC96A5A8778049FA04E494 /* PNLineChart.m in Sources */, + 8ED82E4BB5088B3BC288B53EFD9B9106 /* PNLineChartData.m in Sources */, + D46DF427577E7AB87ED36E29CD8937D9 /* PNLineChartDataItem.m in Sources */, + 8E1DEC97CC5767A4B537AA988BE21B6D /* PNPieChart.m in Sources */, + DF8F4C447D73F08682A89276EB7924E7 /* PNPieChartDataItem.m in Sources */, + 4D871E78B0F660F6B50FC41EF7462E97 /* PNRadarChart.m in Sources */, + 6D791026E20DF9A2B254FD7D11D6DB39 /* PNRadarChartDataItem.m in Sources */, + F3B69FAAAA7F3B62E1130C2DD172C986 /* PNScatterChart.m in Sources */, + 275CDB94DE5627044CA1E5689E71006A /* PNScatterChartData.m in Sources */, + 23507D26F66CCB366FE0F6C1A0D185D1 /* PNScatterChartDataItem.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B1C9814C48D22FEA9B79FC3347917297 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B3174CE1F7CEC7E4986A14E9C4EAA5ED /* UICountingLabel-dummy.m in Sources */, + 228396459A5DFEE20A11FCBE2322446B /* UICountingLabel.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 0D042F6E4C509AE913E3A90AEDD57AEB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = UICountingLabel; + target = DA392EE8E5B24D16FB9910405A0AFC2E /* UICountingLabel */; + targetProxy = DE1DD72CBE9AF5DF2A79E56A1829F476 /* PBXContainerItemProxy */; + }; + 1B729C0463346838068098A4B437DAE4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = 35DD533EFC779F022F1DBC6A54439038 /* PBXContainerItemProxy */; + }; + 8C4570491CFBB36A8FE3BB1E56CC059A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PNChart; + target = 0FC1CB21D1B64FAAC47A6478616DA728 /* PNChart */; + targetProxy = BAC05021060300E06F62A85C4689E1EE /* PBXContainerItemProxy */; + }; + B6E55E784799B63E23A928EA091109E7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = UICountingLabel; + target = DA392EE8E5B24D16FB9910405A0AFC2E /* UICountingLabel */; + targetProxy = 2331FC354592179C10840D17D20A7DB0 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 0B5A8DE2EC6E5A64185B0A167D0A4AD1 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.2; + ONLY_ACTIVE_ARCH = YES; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 234B6F835FC64190C4DF39F2A6FBC615 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 13F7CE1C4258F44867B671A7AC903043 /* PNChart.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PNChart/PNChart-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PNChart/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/PNChart/PNChart.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PNChart; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 25450ECF8D66B6094B445612FA6A454C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 13F7CE1C4258F44867B671A7AC903043 /* PNChart.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PNChart/PNChart-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PNChart/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/PNChart/PNChart.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PNChart; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 33438886A67081D4A3928F13FAC504D2 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 278A6DADF8B259450E4EC2320F5AF032 /* UICountingLabel.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/UICountingLabel/UICountingLabel-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/UICountingLabel/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/UICountingLabel/UICountingLabel.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = UICountingLabel; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3AFCA3D2FED6EFF6D20A4F798A5D193F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 66A3ED553EA08463C9CD7D19E6FD6E4D /* Pods-Statistics.debug.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-Statistics/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 11.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Statistics/Pods-Statistics.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_Statistics; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 5A920F1FCF095A15DBC53389015546B3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7F35D67BE24CA8FE9E8F1E585A4E62FE /* Alamofire.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + ABC1C622E3A94D5EFA80B6DBB5E64193 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.2; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + AC579C955FDF47B6D3FA4A750BEB6BF1 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9117010FD8486E6E87181C159BA18EA7 /* Pods-Statistics.release.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-Statistics/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 11.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Statistics/Pods-Statistics.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_Statistics; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + E0407B57523C522425418F440403048D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7F35D67BE24CA8FE9E8F1E585A4E62FE /* Alamofire.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + E28F6ED3ECBB1D8F764A9931002DC0D7 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 278A6DADF8B259450E4EC2320F5AF032 /* UICountingLabel.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/UICountingLabel/UICountingLabel-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/UICountingLabel/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/UICountingLabel/UICountingLabel.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = UICountingLabel; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0B5A8DE2EC6E5A64185B0A167D0A4AD1 /* Debug */, + ABC1C622E3A94D5EFA80B6DBB5E64193 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5A920F1FCF095A15DBC53389015546B3 /* Debug */, + E0407B57523C522425418F440403048D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6A92B5FD027CE987470A48E671364959 /* Build configuration list for PBXNativeTarget "PNChart" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 25450ECF8D66B6094B445612FA6A454C /* Debug */, + 234B6F835FC64190C4DF39F2A6FBC615 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 76021F35178C17DBECFE29E5681829C1 /* Build configuration list for PBXNativeTarget "Pods-Statistics" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3AFCA3D2FED6EFF6D20A4F798A5D193F /* Debug */, + AC579C955FDF47B6D3FA4A750BEB6BF1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9A22DE6618BE94C542426A3608C6D3E5 /* Build configuration list for PBXNativeTarget "UICountingLabel" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E28F6ED3ECBB1D8F764A9931002DC0D7 /* Debug */, + 33438886A67081D4A3928F13FAC504D2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/Alamofire.xcscheme b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 0000000..44dc41e --- /dev/null +++ b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/PNChart.xcscheme b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/PNChart.xcscheme new file mode 100644 index 0000000..1b12dcb --- /dev/null +++ b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/PNChart.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/Pods-Statistics.xcscheme b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/Pods-Statistics.xcscheme new file mode 100644 index 0000000..77a6ff5 --- /dev/null +++ b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/Pods-Statistics.xcscheme @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/UICountingLabel.xcscheme b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/UICountingLabel.xcscheme new file mode 100644 index 0000000..52ea22b --- /dev/null +++ b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/UICountingLabel.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/xcschememanagement.plist b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..24b8ae4 --- /dev/null +++ b/Statistics/Pods/Pods.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,39 @@ + + + + + SchemeUserState + + Alamofire.xcscheme + + isShown + + orderHint + 0 + + PNChart.xcscheme + + isShown + + orderHint + 1 + + Pods-Statistics.xcscheme + + isShown + + orderHint + 2 + + UICountingLabel.xcscheme + + isShown + + orderHint + 3 + + + SuppressBuildableAutocreation + + + diff --git a/Statistics/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Statistics/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/Statistics/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/Statistics/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Statistics/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Statistics/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/Statistics/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Statistics/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..00014e3 --- /dev/null +++ b/Statistics/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/Statistics/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Statistics/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/Statistics/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/Statistics/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/Statistics/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000..619e5f4 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Statistics/Pods/Target Support Files/Alamofire/Info.plist b/Statistics/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000..3d018f8 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.6.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Statistics/Pods/Target Support Files/PNChart/Info.plist b/Statistics/Pods/Target Support Files/PNChart/Info.plist new file mode 100644 index 0000000..6ff6311 --- /dev/null +++ b/Statistics/Pods/Target Support Files/PNChart/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.8.9 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Statistics/Pods/Target Support Files/PNChart/PNChart-dummy.m b/Statistics/Pods/Target Support Files/PNChart/PNChart-dummy.m new file mode 100644 index 0000000..dc84d20 --- /dev/null +++ b/Statistics/Pods/Target Support Files/PNChart/PNChart-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_PNChart : NSObject +@end +@implementation PodsDummy_PNChart +@end diff --git a/Statistics/Pods/Target Support Files/PNChart/PNChart-prefix.pch b/Statistics/Pods/Target Support Files/PNChart/PNChart-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Statistics/Pods/Target Support Files/PNChart/PNChart-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/Statistics/Pods/Target Support Files/PNChart/PNChart-umbrella.h b/Statistics/Pods/Target Support Files/PNChart/PNChart-umbrella.h new file mode 100644 index 0000000..da86964 --- /dev/null +++ b/Statistics/Pods/Target Support Files/PNChart/PNChart-umbrella.h @@ -0,0 +1,34 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "PNBar.h" +#import "PNBarChart.h" +#import "PNChart.h" +#import "PNChartDelegate.h" +#import "PNChartLabel.h" +#import "PNCircleChart.h" +#import "PNColor.h" +#import "PNGenericChart.h" +#import "PNLineChart.h" +#import "PNLineChartData.h" +#import "PNLineChartDataItem.h" +#import "PNPieChart.h" +#import "PNPieChartDataItem.h" +#import "PNRadarChart.h" +#import "PNRadarChartDataItem.h" +#import "PNScatterChart.h" +#import "PNScatterChartData.h" +#import "PNScatterChartDataItem.h" + +FOUNDATION_EXPORT double PNChartVersionNumber; +FOUNDATION_EXPORT const unsigned char PNChartVersionString[]; + diff --git a/Statistics/Pods/Target Support Files/PNChart/PNChart.modulemap b/Statistics/Pods/Target Support Files/PNChart/PNChart.modulemap new file mode 100644 index 0000000..1165d73 --- /dev/null +++ b/Statistics/Pods/Target Support Files/PNChart/PNChart.modulemap @@ -0,0 +1,6 @@ +framework module PNChart { + umbrella header "PNChart-umbrella.h" + + export * + module * { export * } +} diff --git a/Statistics/Pods/Target Support Files/PNChart/PNChart.xcconfig b/Statistics/Pods/Target Support Files/PNChart/PNChart.xcconfig new file mode 100644 index 0000000..9848c86 --- /dev/null +++ b/Statistics/Pods/Target Support Files/PNChart/PNChart.xcconfig @@ -0,0 +1,11 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PNChart +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/UICountingLabel" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "CoreGraphics" -framework "Foundation" -framework "QuartzCore" -framework "UIKit" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/PNChart +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Info.plist b/Statistics/Pods/Target Support Files/Pods-Statistics/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/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/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-acknowledgements.markdown b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-acknowledgements.markdown new file mode 100644 index 0000000..c89cb92 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-acknowledgements.markdown @@ -0,0 +1,74 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2017 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. + + +## PNChart + +The MIT License (MIT) + +Copyright (c) 2013 Kevin + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +## UICountingLabel + +The MIT License (MIT) + +Copyright (c) 2013 Tim Gostony + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +Generated by CocoaPods - https://cocoapods.org diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-acknowledgements.plist b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-acknowledgements.plist new file mode 100644 index 0000000..5d90a44 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-acknowledgements.plist @@ -0,0 +1,118 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014-2017 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) 2013 Kevin + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION 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 + PNChart + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2013 Tim Gostony + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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 + UICountingLabel + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-dummy.m b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-dummy.m new file mode 100644 index 0000000..4da167d --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_Statistics : NSObject +@end +@implementation PodsDummy_Pods_Statistics +@end diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-frameworks.sh b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-frameworks.sh new file mode 100755 index 0000000..477a666 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-frameworks.sh @@ -0,0 +1,103 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PNChart/PNChart.framework" + install_framework "$BUILT_PRODUCTS_DIR/UICountingLabel/UICountingLabel.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PNChart/PNChart.framework" + install_framework "$BUILT_PRODUCTS_DIR/UICountingLabel/UICountingLabel.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-resources.sh b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-resources.sh new file mode 100755 index 0000000..aed060f --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + 3) + TARGET_DEVICE_ARGS="--target-device tv" + ;; + 4) + TARGET_DEVICE_ARGS="--target-device watch" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-umbrella.h b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-umbrella.h new file mode 100644 index 0000000..20d453b --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-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_StatisticsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_StatisticsVersionString[]; + diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.debug.xcconfig b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.debug.xcconfig new file mode 100644 index 0000000..6abc7c2 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.debug.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PNChart" "$PODS_CONFIGURATION_BUILD_DIR/UICountingLabel" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PNChart/PNChart.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/UICountingLabel/UICountingLabel.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PNChart" -framework "UICountingLabel" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.modulemap b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.modulemap new file mode 100644 index 0000000..4eb9dc0 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.modulemap @@ -0,0 +1,6 @@ +framework module Pods_Statistics { + umbrella header "Pods-Statistics-umbrella.h" + + export * + module * { export * } +} diff --git a/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.release.xcconfig b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.release.xcconfig new file mode 100644 index 0000000..6abc7c2 --- /dev/null +++ b/Statistics/Pods/Target Support Files/Pods-Statistics/Pods-Statistics.release.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PNChart" "$PODS_CONFIGURATION_BUILD_DIR/UICountingLabel" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PNChart/PNChart.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/UICountingLabel/UICountingLabel.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PNChart" -framework "UICountingLabel" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Statistics/Pods/Target Support Files/UICountingLabel/Info.plist b/Statistics/Pods/Target Support Files/UICountingLabel/Info.plist new file mode 100644 index 0000000..2a9158a --- /dev/null +++ b/Statistics/Pods/Target Support Files/UICountingLabel/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.2.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-dummy.m b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-dummy.m new file mode 100644 index 0000000..8e827c4 --- /dev/null +++ b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_UICountingLabel : NSObject +@end +@implementation PodsDummy_UICountingLabel +@end diff --git a/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-prefix.pch b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-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/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-umbrella.h b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-umbrella.h new file mode 100644 index 0000000..05f2381 --- /dev/null +++ b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel-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 "UICountingLabel.h" + +FOUNDATION_EXPORT double UICountingLabelVersionNumber; +FOUNDATION_EXPORT const unsigned char UICountingLabelVersionString[]; + diff --git a/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel.modulemap b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel.modulemap new file mode 100644 index 0000000..435158f --- /dev/null +++ b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel.modulemap @@ -0,0 +1,6 @@ +framework module UICountingLabel { + umbrella header "UICountingLabel-umbrella.h" + + export * + module * { export * } +} diff --git a/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel.xcconfig b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel.xcconfig new file mode 100644 index 0000000..d91f25c --- /dev/null +++ b/Statistics/Pods/Target Support Files/UICountingLabel/UICountingLabel.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/UICountingLabel +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/UICountingLabel +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Statistics/Pods/UICountingLabel/LICENSE b/Statistics/Pods/UICountingLabel/LICENSE new file mode 100644 index 0000000..5b7a743 --- /dev/null +++ b/Statistics/Pods/UICountingLabel/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Tim Gostony + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/Statistics/Pods/UICountingLabel/README.md b/Statistics/Pods/UICountingLabel/README.md new file mode 100644 index 0000000..8b0e60c --- /dev/null +++ b/Statistics/Pods/UICountingLabel/README.md @@ -0,0 +1,82 @@ +# UICountingLabel #### + +Adds animated counting support to `UILabel`. + +## CocoaPods ###### +UICountingLabel is available on CocoaPods. +Add this to your Podfile: + +`pod 'UICountingLabel'` + +And then run: + +`$ pod install` + +## Setup ###### +Simply initialize a `UICountingLabel` the same way you set up a regular `UILabel`: + + UICountingLabel* myLabel = [[UICountingLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)]; + [self.view addSubview:myLabel]; + [myLabel release]; + +You can also add it to your XIB file, just make sure you set the class type to `UICountingLabel` instead of `UILabel` and be sure to `#import "UICountingLabel.h"` in the header file. + +## Use ##### + +Set the format of your label. This will be filled with a single int or float (depending on how you format it) when it updates: + + myLabel.format = @"%d"; + +Optionally, set the mode. The default is `UILabelCountingMethodEaseInOut`, which will start slow, speed up, and then slow down as it reaches the end. Other options are described below in the Methods section. + + myLabel.method = UILabelCountingMethodLinear; + +When you want the label to start counting, just call: + + [myLabel countFrom:50 to:100]; + +You can also specify the duration. The default is 2.0 seconds. + + [myLabel countFrom:50 to:100 withDuration:5.0f]; + +Additionally, there is `animationDuration` property which you can use to override the default animation duration. + + myLabel.animationDuration = 1.0; + +You can use common convinient methods for counting, such as: + + [myLabel countFromCurrentValueTo:100]; + [myLabel countFromZeroTo:100]; + +Behind the scenes, these convinient methods use one base method, which has the following full signature: + + [myLabel countFrom:(float)startValue + to:(float)endValue + withDuration:(NSTimeInterval)duration]; + +You can get current value of your label using `-currentValue` method (works correctly in the process of animation too): + + CGFloat currentValue = [myLabel currentValue]; + +## Formats ##### + +When you set the `format` property, the label will look for the presence of `%(.*)d` or `%(.*)i`, and if found, will cast the value to `int` before formatting the string. Otherwise, it will format it using a `float`. + +If you're using a `float` value, it's recommended to limit the number of digits with a format string, such as `@"%.1f"` for one decimal place. + +Because it uses the standard `stringWithFormat:` method, you can also include arbitrary text in your format, such as `@"Points: %i"`. + +## Modes ##### +There are currently four modes of counting. + +### `UILabelCountingMethodLinear` ##### +Counts linearly from the start to the end. + +### `UILabelCountingMethodEaseIn` ##### +Ease In starts out slow and speeds up counting as it gets to the end, stopping suddenly at the final value. + +### `UILabelCountingMethodEaseOut` ##### +Ease Out starts out fast and slows down as it gets to the destination value. + +### `UILabelCountingMethodEaseInOut` ##### +Ease In/Out starts out slow, speeds up towards the middle, and then slows down as it approaches the destination. It is a nice, smooth curve that looks great, and is the default method. diff --git a/Statistics/Pods/UICountingLabel/UICountingLabel.h b/Statistics/Pods/UICountingLabel/UICountingLabel.h new file mode 100755 index 0000000..c840454 --- /dev/null +++ b/Statistics/Pods/UICountingLabel/UICountingLabel.h @@ -0,0 +1,36 @@ +#import +#import + +typedef enum { + UILabelCountingMethodEaseInOut, + UILabelCountingMethodEaseIn, + UILabelCountingMethodEaseOut, + UILabelCountingMethodLinear +} UILabelCountingMethod; + +typedef NSString* (^UICountingLabelFormatBlock)(float value); +typedef NSAttributedString* (^UICountingLabelAttributedFormatBlock)(float value); + +@interface UICountingLabel : UILabel + +@property (nonatomic, strong) NSString *format; +@property (nonatomic, assign) UILabelCountingMethod method; +@property (nonatomic, assign) NSTimeInterval animationDuration; + +@property (nonatomic, copy) UICountingLabelFormatBlock formatBlock; +@property (nonatomic, copy) UICountingLabelAttributedFormatBlock attributedFormatBlock; +@property (nonatomic, copy) void (^completionBlock)(); + +-(void)countFrom:(float)startValue to:(float)endValue; +-(void)countFrom:(float)startValue to:(float)endValue withDuration:(NSTimeInterval)duration; + +-(void)countFromCurrentValueTo:(float)endValue; +-(void)countFromCurrentValueTo:(float)endValue withDuration:(NSTimeInterval)duration; + +-(void)countFromZeroTo:(float)endValue; +-(void)countFromZeroTo:(float)endValue withDuration:(NSTimeInterval)duration; + +- (CGFloat)currentValue; + +@end + diff --git a/Statistics/Pods/UICountingLabel/UICountingLabel.m b/Statistics/Pods/UICountingLabel/UICountingLabel.m new file mode 100755 index 0000000..6cf3b7c --- /dev/null +++ b/Statistics/Pods/UICountingLabel/UICountingLabel.m @@ -0,0 +1,245 @@ +#import "UICountingLabel.h" + +#if !__has_feature(objc_arc) +#error UICountingLabel is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +#pragma mark - UILabelCounter + +// This whole class & subclasses are private to UICountingLabel, which is why they are declared here in the .m file + +@interface UILabelCounter : NSObject + +-(float)update:(float)t; + +@property float rate; + +@end + +@interface UILabelCounterLinear : UILabelCounter + +@end + +@interface UILabelCounterEaseIn : UILabelCounter + +@end + +@interface UILabelCounterEaseOut : UILabelCounter + +@end + +@interface UILabelCounterEaseInOut : UILabelCounter + +@end + +@implementation UILabelCounter + +-(float)update:(float)t{ + return 0; +} + +@end + +@implementation UILabelCounterLinear + +-(float)update:(float)t +{ + return t; +} + +@end + +@implementation UILabelCounterEaseIn + +-(float)update:(float)t +{ + return powf(t, self.rate); +} + +@end + +@implementation UILabelCounterEaseOut + +-(float)update:(float)t{ + return 1.0-powf((1.0-t), self.rate); +} + +@end + +@implementation UILabelCounterEaseInOut + +-(float) update: (float) t +{ + int sign =1; + int r = (int) self.rate; + if (r % 2 == 0) + sign = -1; + t *= 2; + if (t < 1) + return 0.5f * powf (t, self.rate); + else + return sign*0.5f * (powf (t-2, self.rate) + sign*2); +} + +@end + +#pragma mark - UICountingLabel + +@interface UICountingLabel () + +@property float startingValue; +@property float destinationValue; +@property NSTimeInterval progress; +@property NSTimeInterval lastUpdate; +@property NSTimeInterval totalTime; +@property float easingRate; + +@property (nonatomic, weak) NSTimer *timer; +@property (nonatomic, strong) UILabelCounter *counter; + +@end + +@implementation UICountingLabel + +-(void)countFrom:(float)value to:(float)endValue { + + if (self.animationDuration == 0.0f) { + self.animationDuration = 2.0f; + } + + [self countFrom:value to:endValue withDuration:self.animationDuration]; +} + +-(void)countFrom:(float)startValue to:(float)endValue withDuration:(NSTimeInterval)duration { + + self.startingValue = startValue; + self.destinationValue = endValue; + + // remove any (possible) old timers + [self.timer invalidate]; + self.timer = nil; + + if (duration == 0.0) { + // No animation + [self setTextValue:endValue]; + [self runCompletionBlock]; + return; + } + + self.easingRate = 3.0f; + self.progress = 0; + self.totalTime = duration; + self.lastUpdate = [NSDate timeIntervalSinceReferenceDate]; + + if(self.format == nil) + self.format = @"%f"; + + switch(self.method) + { + case UILabelCountingMethodLinear: + self.counter = [[UILabelCounterLinear alloc] init]; + break; + case UILabelCountingMethodEaseIn: + self.counter = [[UILabelCounterEaseIn alloc] init]; + break; + case UILabelCountingMethodEaseOut: + self.counter = [[UILabelCounterEaseOut alloc] init]; + break; + case UILabelCountingMethodEaseInOut: + self.counter = [[UILabelCounterEaseInOut alloc] init]; + break; + } + + self.counter.rate = 3.0f; + + NSTimer *timer = [NSTimer timerWithTimeInterval:(1.0f/30.0f) target:self selector:@selector(updateValue:) userInfo:nil repeats:YES]; + [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + [[NSRunLoop mainRunLoop] addTimer:timer forMode:UITrackingRunLoopMode]; + self.timer = timer; +} + +- (void)countFromCurrentValueTo:(float)endValue { + [self countFrom:[self currentValue] to:endValue]; +} + +- (void)countFromCurrentValueTo:(float)endValue withDuration:(NSTimeInterval)duration { + [self countFrom:[self currentValue] to:endValue withDuration:duration]; +} + +- (void)countFromZeroTo:(float)endValue { + [self countFrom:0.0f to:endValue]; +} + +- (void)countFromZeroTo:(float)endValue withDuration:(NSTimeInterval)duration { + [self countFrom:0.0f to:endValue withDuration:duration]; +} + +- (void)updateValue:(NSTimer *)timer { + + // update progress + NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate]; + self.progress += now - self.lastUpdate; + self.lastUpdate = now; + + if (self.progress >= self.totalTime) { + [self.timer invalidate]; + self.timer = nil; + self.progress = self.totalTime; + } + + [self setTextValue:[self currentValue]]; + + if (self.progress == self.totalTime) { + [self runCompletionBlock]; + } +} + +- (void)setTextValue:(float)value +{ + if (self.attributedFormatBlock != nil) { + self.attributedText = self.attributedFormatBlock(value); + } + else if(self.formatBlock != nil) + { + self.text = self.formatBlock(value); + } + else + { + // check if counting with ints - cast to int + if([self.format rangeOfString:@"%(.*)d" options:NSRegularExpressionSearch].location != NSNotFound || [self.format rangeOfString:@"%(.*)i"].location != NSNotFound ) + { + self.text = [NSString stringWithFormat:self.format,(int)value]; + } + else + { + self.text = [NSString stringWithFormat:self.format,value]; + } + } +} + +- (void)setFormat:(NSString *)format { + _format = format; + // update label with new format + [self setTextValue:self.currentValue]; +} + +- (void)runCompletionBlock { + + if (self.completionBlock) { + self.completionBlock(); + self.completionBlock = nil; + } +} + +- (CGFloat)currentValue { + + if (self.progress >= self.totalTime) { + return self.destinationValue; + } + + CGFloat percent = self.progress / self.totalTime; + CGFloat updateVal = [self.counter update:percent]; + return self.startingValue + (updateVal * (self.destinationValue - self.startingValue)); +} + +@end diff --git a/Statistics/Statistics.xcodeproj/project.pbxproj b/Statistics/Statistics.xcodeproj/project.pbxproj new file mode 100644 index 0000000..1f7ff65 --- /dev/null +++ b/Statistics/Statistics.xcodeproj/project.pbxproj @@ -0,0 +1,416 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 48; + objects = { + +/* Begin PBXBuildFile section */ + 4C3E3839201B58E300739BD4 /* RequestManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3E3838201B58E300739BD4 /* RequestManager.swift */; }; + 4C3E383B201B5D9E00739BD4 /* MainCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3E383A201B5D9E00739BD4 /* MainCollectionViewCell.swift */; }; + 4C3E383D201B5DE100739BD4 /* MainCollectionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3E383C201B5DE100739BD4 /* MainCollectionViewController.swift */; }; + 4C3E3843201B709D00739BD4 /* TopCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3E3842201B709D00739BD4 /* TopCollectionViewCell.swift */; }; + 4CCC8944201B583200AED9C4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CCC8943201B583200AED9C4 /* AppDelegate.swift */; }; + 4CCC8949201B583200AED9C4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4CCC8947201B583200AED9C4 /* Main.storyboard */; }; + 4CCC894B201B583200AED9C4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 4CCC894A201B583200AED9C4 /* Assets.xcassets */; }; + 4CCC894E201B583200AED9C4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4CCC894C201B583200AED9C4 /* LaunchScreen.storyboard */; }; + 7F9132CA801315152E35FB57 /* Pods_Statistics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C4F8552B7CC2079B07B36B68 /* Pods_Statistics.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 4C3E3838201B58E300739BD4 /* RequestManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestManager.swift; sourceTree = ""; }; + 4C3E383A201B5D9E00739BD4 /* MainCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainCollectionViewCell.swift; sourceTree = ""; }; + 4C3E383C201B5DE100739BD4 /* MainCollectionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainCollectionViewController.swift; sourceTree = ""; }; + 4C3E3842201B709D00739BD4 /* TopCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TopCollectionViewCell.swift; sourceTree = ""; }; + 4CCC8940201B583200AED9C4 /* Statistics.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Statistics.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 4CCC8943201B583200AED9C4 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 4CCC8948201B583200AED9C4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 4CCC894A201B583200AED9C4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 4CCC894D201B583200AED9C4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 4CCC894F201B583200AED9C4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 9855632C7F597BFA3FE138BD /* Pods-Statistics.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Statistics.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Statistics/Pods-Statistics.debug.xcconfig"; sourceTree = ""; }; + C4F8552B7CC2079B07B36B68 /* Pods_Statistics.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Statistics.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D5F9E8256E1E50DD385DB3AE /* Pods-Statistics.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Statistics.release.xcconfig"; path = "Pods/Target Support Files/Pods-Statistics/Pods-Statistics.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 4CCC893D201B583200AED9C4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7F9132CA801315152E35FB57 /* Pods_Statistics.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 142D38CBEC34C617DC350A2B /* Pods */ = { + isa = PBXGroup; + children = ( + 9855632C7F597BFA3FE138BD /* Pods-Statistics.debug.xcconfig */, + D5F9E8256E1E50DD385DB3AE /* Pods-Statistics.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + 4CCC8937201B583200AED9C4 = { + isa = PBXGroup; + children = ( + 4CCC8942201B583200AED9C4 /* Statistics */, + 4CCC8941201B583200AED9C4 /* Products */, + 142D38CBEC34C617DC350A2B /* Pods */, + 80BCC4B1F4CEFB2A726EF7D0 /* Frameworks */, + ); + sourceTree = ""; + }; + 4CCC8941201B583200AED9C4 /* Products */ = { + isa = PBXGroup; + children = ( + 4CCC8940201B583200AED9C4 /* Statistics.app */, + ); + name = Products; + sourceTree = ""; + }; + 4CCC8942201B583200AED9C4 /* Statistics */ = { + isa = PBXGroup; + children = ( + 4CCC8943201B583200AED9C4 /* AppDelegate.swift */, + 4C3E3838201B58E300739BD4 /* RequestManager.swift */, + 4CCC8947201B583200AED9C4 /* Main.storyboard */, + 4CCC894A201B583200AED9C4 /* Assets.xcassets */, + 4CCC894C201B583200AED9C4 /* LaunchScreen.storyboard */, + 4CCC894F201B583200AED9C4 /* Info.plist */, + 4C3E383A201B5D9E00739BD4 /* MainCollectionViewCell.swift */, + 4C3E383C201B5DE100739BD4 /* MainCollectionViewController.swift */, + 4C3E3842201B709D00739BD4 /* TopCollectionViewCell.swift */, + ); + path = Statistics; + sourceTree = ""; + }; + 80BCC4B1F4CEFB2A726EF7D0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + C4F8552B7CC2079B07B36B68 /* Pods_Statistics.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 4CCC893F201B583200AED9C4 /* Statistics */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4CCC8952201B583200AED9C4 /* Build configuration list for PBXNativeTarget "Statistics" */; + buildPhases = ( + AE64D8D1143384D5A1661DE3 /* [CP] Check Pods Manifest.lock */, + 4CCC893C201B583200AED9C4 /* Sources */, + 4CCC893D201B583200AED9C4 /* Frameworks */, + 4CCC893E201B583200AED9C4 /* Resources */, + DB5CA8E1051AA56F514B671D /* [CP] Embed Pods Frameworks */, + 979A728258E11177246B7EE4 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Statistics; + productName = Statistics; + productReference = 4CCC8940201B583200AED9C4 /* Statistics.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 4CCC8938201B583200AED9C4 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 0920; + ORGANIZATIONNAME = dp; + TargetAttributes = { + 4CCC893F201B583200AED9C4 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 4CCC893B201B583200AED9C4 /* Build configuration list for PBXProject "Statistics" */; + compatibilityVersion = "Xcode 8.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 4CCC8937201B583200AED9C4; + productRefGroup = 4CCC8941201B583200AED9C4 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 4CCC893F201B583200AED9C4 /* Statistics */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 4CCC893E201B583200AED9C4 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4CCC894E201B583200AED9C4 /* LaunchScreen.storyboard in Resources */, + 4CCC894B201B583200AED9C4 /* Assets.xcassets in Resources */, + 4CCC8949201B583200AED9C4 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 979A728258E11177246B7EE4 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + AE64D8D1143384D5A1661DE3 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_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"; + showEnvVarsInLog = 0; + }; + DB5CA8E1051AA56F514B671D /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Statistics/Pods-Statistics-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 4CCC893C201B583200AED9C4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4C3E3839201B58E300739BD4 /* RequestManager.swift in Sources */, + 4C3E383D201B5DE100739BD4 /* MainCollectionViewController.swift in Sources */, + 4C3E3843201B709D00739BD4 /* TopCollectionViewCell.swift in Sources */, + 4CCC8944201B583200AED9C4 /* AppDelegate.swift in Sources */, + 4C3E383B201B5D9E00739BD4 /* MainCollectionViewCell.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 4CCC8947201B583200AED9C4 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 4CCC8948201B583200AED9C4 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 4CCC894C201B583200AED9C4 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 4CCC894D201B583200AED9C4 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 4CCC8950201B583200AED9C4 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.2; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 4CCC8951201B583200AED9C4 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.2; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 4CCC8953201B583200AED9C4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9855632C7F597BFA3FE138BD /* Pods-Statistics.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = HL9M7KB7DT; + INFOPLIST_FILE = Statistics/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.dp.Statistics; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 4CCC8954201B583200AED9C4 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D5F9E8256E1E50DD385DB3AE /* Pods-Statistics.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = HL9M7KB7DT; + INFOPLIST_FILE = Statistics/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.dp.Statistics; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 4CCC893B201B583200AED9C4 /* Build configuration list for PBXProject "Statistics" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4CCC8950201B583200AED9C4 /* Debug */, + 4CCC8951201B583200AED9C4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4CCC8952201B583200AED9C4 /* Build configuration list for PBXNativeTarget "Statistics" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4CCC8953201B583200AED9C4 /* Debug */, + 4CCC8954201B583200AED9C4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 4CCC8938201B583200AED9C4 /* Project object */; +} diff --git a/Statistics/Statistics.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Statistics/Statistics.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..8fa6d2c --- /dev/null +++ b/Statistics/Statistics.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Statistics/Statistics.xcodeproj/project.xcworkspace/xcuserdata/florini.xcuserdatad/UserInterfaceState.xcuserstate b/Statistics/Statistics.xcodeproj/project.xcworkspace/xcuserdata/florini.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..b0f55f1 Binary files /dev/null and b/Statistics/Statistics.xcodeproj/project.xcworkspace/xcuserdata/florini.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Statistics/Statistics.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/xcschememanagement.plist b/Statistics/Statistics.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..327704d --- /dev/null +++ b/Statistics/Statistics.xcodeproj/xcuserdata/florini.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + Statistics.xcscheme + + orderHint + 4 + + + + diff --git a/Statistics/Statistics.xcworkspace/contents.xcworkspacedata b/Statistics/Statistics.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..a8ecbc7 --- /dev/null +++ b/Statistics/Statistics.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Statistics/Statistics.xcworkspace/xcuserdata/florini.xcuserdatad/UserInterfaceState.xcuserstate b/Statistics/Statistics.xcworkspace/xcuserdata/florini.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..4e7b550 Binary files /dev/null and b/Statistics/Statistics.xcworkspace/xcuserdata/florini.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Statistics/Statistics.xcworkspace/xcuserdata/florini.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/Statistics/Statistics.xcworkspace/xcuserdata/florini.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..ffa58f6 --- /dev/null +++ b/Statistics/Statistics.xcworkspace/xcuserdata/florini.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Statistics/AppDelegate.swift b/Statistics/Statistics/AppDelegate.swift new file mode 100644 index 0000000..70838eb --- /dev/null +++ b/Statistics/Statistics/AppDelegate.swift @@ -0,0 +1,48 @@ +// +// AppDelegate.swift +// Statistics +// +// Created by Florin Ionita on 1/26/18. +// Copyright © 2018 dp. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + RequestManager.sharedInstance() + + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + +} + diff --git a/Statistics/Statistics/Assets.xcassets/AppIcon.appiconset/Contents.json b/Statistics/Statistics/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d8db8d6 --- /dev/null +++ b/Statistics/Statistics/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + }, + { + "idiom" : "ios-marketing", + "size" : "1024x1024", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Statistics/Statistics/Base.lproj/LaunchScreen.storyboard b/Statistics/Statistics/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f83f6fd --- /dev/null +++ b/Statistics/Statistics/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Statistics/Base.lproj/Main.storyboard b/Statistics/Statistics/Base.lproj/Main.storyboard new file mode 100644 index 0000000..366d7ac --- /dev/null +++ b/Statistics/Statistics/Base.lproj/Main.storyboard @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Statistics/CollectionViewCell.swift b/Statistics/Statistics/CollectionViewCell.swift new file mode 100644 index 0000000..ee22219 --- /dev/null +++ b/Statistics/Statistics/CollectionViewCell.swift @@ -0,0 +1,18 @@ +// +// CollectionViewCell.swift +// Statistics +// +// Created by Florin Ionita on 1/26/18. +// Copyright © 2018 dp. All rights reserved. +// + +import UIKit + +class CollectionViewCell: UICollectionViewCell { + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + +} diff --git a/Statistics/Statistics/CollectionViewCell.xib b/Statistics/Statistics/CollectionViewCell.xib new file mode 100644 index 0000000..1b5cbb6 --- /dev/null +++ b/Statistics/Statistics/CollectionViewCell.xib @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Statistics/Statistics/Info.plist b/Statistics/Statistics/Info.plist new file mode 100644 index 0000000..16be3b6 --- /dev/null +++ b/Statistics/Statistics/Info.plist @@ -0,0 +1,45 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/Statistics/Statistics/MainCollectionViewCell.swift b/Statistics/Statistics/MainCollectionViewCell.swift new file mode 100644 index 0000000..1f3d764 --- /dev/null +++ b/Statistics/Statistics/MainCollectionViewCell.swift @@ -0,0 +1,151 @@ +// +// MainCollectionViewCell.swift +// Statistics +// +// Created by Florin Ionita on 1/26/18. +// Copyright © 2018 dp. All rights reserved. +// + +import UIKit +import PNChart + +let TopCollectionViewCellIdentifier = "TopCollectionViewCellIdentifier" + +class MainCollectionViewCell: UICollectionViewCell { + + @IBOutlet weak var topCollectionView: UICollectionView! + @IBOutlet weak var chartsHolderView: UIView! + + var items = 0 + var pieChart: PNPieChart! + + override func awakeFromNib() { + self.layoutIfNeeded() + + self.topCollectionView.backgroundView = UIView.init(frame: .zero) + self.topCollectionView.backgroundColor = .clear + + self.topCollectionView.dataSource = self + self.topCollectionView.delegate = self + + RequestManager.sharedInstance().makeCoursesRequest { (success) in + self.items = RequestManager.sharedInstance().courses.count + 1 + self.topCollectionView.reloadData() + } + + RequestManager.sharedInstance().makeFeedbackStudentsRequest { (success) in + + } + + RequestManager.sharedInstance().makeFeedbackTeachersRequest { (success) in + + } + + RequestManager.sharedInstance().makeAllAssigmentsNumberRequest { (success) in + + } + + RequestManager.sharedInstance().makeMaxAttachementsNumberForFile { (success) in + + } + + RequestManager.sharedInstance().makeNrAssigmentsThatHaveFileRequest { (success) in + + } + } + +} + +extension MainCollectionViewCell: UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return self.items + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TopCollectionViewCellIdentifier, for: indexPath) + + if let topCell = cell as? TopCollectionViewCell { + if indexPath.item < self.items - 1 { + let course = RequestManager.sharedInstance().courses[indexPath.row] + topCell.titleLabel.text = course[Parser.name] as? String + topCell.nameLabel.text = course[Parser.teacherName] as? String + topCell.startsLabel.text = course[Parser.startDate] as? String + topCell.endsLabel.text = course[Parser.endDate] as? String + topCell.yearLabel.text = course[Parser.yearOfStudy] as? String + + self.generateChartForCourse(course) + } else { + topCell.titleLabel.text = "General" + topCell.titleLabel.text = "Info" + topCell.startsLabel.isHidden = true + topCell.endsLabel.isHidden = true + topCell.yearLabel.isHidden = true + + self.generateChartForGeneral() + } + } + + return cell + } + + fileprivate func generateChartForCourse(_ course: [String: Any]) { + + if let chart = self.pieChart { + chart.removeFromSuperview() + } + + let items = [ + PNPieChartDataItem(value: CGFloat(course[Parser.completed] as! Int), color: .green, description: "Completed"), + PNPieChartDataItem(value: CGFloat(course[Parser.notCompleted] as! Int), color: .red, description: "Not completed"), + ] + + self.pieChart = PNPieChart.init(frame: self.chartsHolderView.bounds, items: items)! + self.pieChart.descriptionTextColor = .black + self.pieChart.descriptionTextFont = UIFont.init(name: "Avenir-Medium", size: 14) + self.pieChart.stroke() + + + self.chartsHolderView.addSubview(pieChart) + } + + + fileprivate func generateChartForGeneral() { + + if let chart = self.pieChart { + chart.removeFromSuperview() + } + + let items = [ + PNPieChartDataItem(value: CGFloat(RequestManager.sharedInstance().assigmentsThatHaveAttachements), color: .green, description: "Assigments with attachments."), + PNPieChartDataItem(value: CGFloat(RequestManager.sharedInstance().feedbackStudents), color: .blue, description: "Feedback from Students"), + PNPieChartDataItem(value: CGFloat(RequestManager.sharedInstance().feedbackTeachers), color: .yellow, description: "Feedback from Teachers"), + PNPieChartDataItem(value: CGFloat(RequestManager.sharedInstance().totalAttachments), color: .lightGray, description: "Total attachments"), + PNPieChartDataItem(value: CGFloat(RequestManager.sharedInstance().maxAttachments), color: .gray, description: "Max attachments"), + ] + + self.pieChart = PNPieChart.init(frame: self.chartsHolderView.bounds, items: items)! + self.pieChart.descriptionTextColor = .black + self.pieChart.descriptionTextFont = UIFont.init(name: "Avenir-Medium", size: 14) + self.pieChart.stroke() + + + self.chartsHolderView.addSubview(pieChart) + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + return collectionView.bounds.size + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { + return .zero + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { + return 0 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { + return 0 + } + +} diff --git a/Statistics/Statistics/MainCollectionViewController.swift b/Statistics/Statistics/MainCollectionViewController.swift new file mode 100644 index 0000000..0496875 --- /dev/null +++ b/Statistics/Statistics/MainCollectionViewController.swift @@ -0,0 +1,61 @@ +// +// MainCollectionViewController.swift +// Statistics +// +// Created by Florin Ionita on 1/26/18. +// Copyright © 2018 dp. All rights reserved. +// + +import UIKit + +private let reuseIdentifier = "MainCollectionViewCellIdentifier" + +class MainCollectionViewController: UICollectionViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + self.collectionView!.layoutIfNeeded() + + // Register cell classes + self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) + } + // MARK: UICollectionViewDataSource + + override func numberOfSections(in collectionView: UICollectionView) -> Int { + return 1 + } + + + override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 1 + } + + override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) + + // Configure the cell + + return cell + } + +} + +extension MainCollectionViewController: UICollectionViewDelegateFlowLayout { + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + return collectionView.bounds.size + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { + return .zero + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { + return 0 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { + return 0 + } + +} diff --git a/Statistics/Statistics/RequestManager.swift b/Statistics/Statistics/RequestManager.swift new file mode 100644 index 0000000..6ade045 --- /dev/null +++ b/Statistics/Statistics/RequestManager.swift @@ -0,0 +1,137 @@ +// +// RequestManager.swift +// ExamTest +// +// Created by Florin Ionita on 1/25/18. +// Copyright © 2018 mobile. All rights reserved. +// + +import UIKit +import Alamofire + +struct Parser { + static let teacherName = "teacher" + static let yearOfStudy = "yearOfStudy" + static let startDate = "starDate" + static let endDate = "endDate" + static let completed = "completedAssignments" + static let notCompleted = "unfinishedAssignments" + static let name = "name" + + static let nr = "nr" + static let total_attachments = "total_attachments" + static let nr_max = "nr_max" +} + +let baseUrl = "http://192.168.100.9:8080" +let coursesURL = "\(baseUrl)/courses" +let feedbackTeachersURL = "\(baseUrl)/feedback_teachers" +let feedbackStudentsURL = "\(baseUrl)/feedback_students" +let assignmentsFileAllURL = "\(baseUrl)/assignments_file_all" +let assignmentsFileMaxURL = "\(baseUrl)/assignments_file_max" +let assignmentsFileHaveURL = "\(baseUrl)/assignements_have_files" + +class RequestManager: NSObject { + + var courses: [[String: Any]]! + var feedbackTeachers: Int! + var feedbackStudents: Int! + var totalAttachments: Int! + var maxAttachments: Int! + var assigmentsThatHaveAttachements: Int! + + static private let shared = RequestManager.init() + + static func sharedInstance() -> RequestManager { + return self.shared + } + + private override init() { + super.init() + } + + func makeCoursesRequest(completion: @escaping (Bool) -> Void) { + Alamofire.request(coursesURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in + switch response.result { + case .success(let json): + if let data = json as? [[String: Any]] { + self.courses = data + completion(true) + } + case .failure: + completion(false) + } + } + } + + func makeFeedbackTeachersRequest(completion: @escaping (Bool) -> Void) { + Alamofire.request(feedbackTeachersURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in + switch response.result { + case .success(let json): + if let data = json as? Int { + self.feedbackTeachers = data + completion(true) + } + case .failure: + completion(false) + } + } + } + + func makeFeedbackStudentsRequest(completion: @escaping (Bool) -> Void) { + Alamofire.request(feedbackStudentsURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in + switch response.result { + case .success(let json): + if let data = json as? Int { + self.feedbackStudents = data + completion(true) + } + case .failure: + completion(false) + } + } + } + + func makeAllAssigmentsNumberRequest(completion: @escaping (Bool) -> Void) { + Alamofire.request(assignmentsFileAllURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in + switch response.result { + case .success(let json): + if let data = json as? Int { + self.totalAttachments = data + completion(true) + } + case .failure: + completion(false) + } + } + } + + func makeMaxAttachementsNumberForFile(completion: @escaping (Bool) -> Void) { + Alamofire.request(assignmentsFileMaxURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in + switch response.result { + case .success(let json): + if let data = json as? Int { + self.maxAttachments = data + completion(true) + } + case .failure: + completion(false) + } + } + } + + func makeNrAssigmentsThatHaveFileRequest(completion: @escaping (Bool) -> Void) { + Alamofire.request(assignmentsFileHaveURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in + switch response.result { + case .success(let json): + if let data = json as? Int { + self.assigmentsThatHaveAttachements = data + completion(true) + } + case .failure: + completion(false) + } + } + } + +} diff --git a/Statistics/Statistics/TopCollectionViewCell.swift b/Statistics/Statistics/TopCollectionViewCell.swift new file mode 100644 index 0000000..b51247e --- /dev/null +++ b/Statistics/Statistics/TopCollectionViewCell.swift @@ -0,0 +1,20 @@ +// +// TopCollectionViewCell.swift +// Statistics +// +// Created by Florin Ionita on 1/26/18. +// Copyright © 2018 dp. All rights reserved. +// + +import UIKit + +class TopCollectionViewCell: UICollectionViewCell { + + @IBOutlet weak var titleLabel: UILabel! + @IBOutlet weak var nameLabel: UILabel! + @IBOutlet weak var yearLabel: UILabel! + @IBOutlet weak var startsLabel: UILabel! + @IBOutlet weak var endsLabel: UILabel! + + @IBOutlet weak var titleLabelTopConstraint: NSLayoutConstraint! +} diff --git a/Statistics/Statistics/ViewController.swift b/Statistics/Statistics/ViewController.swift new file mode 100644 index 0000000..57583b9 --- /dev/null +++ b/Statistics/Statistics/ViewController.swift @@ -0,0 +1,25 @@ +// +// ViewController.swift +// Statistics +// +// Created by Florin Ionita on 1/26/18. +// Copyright © 2018 dp. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + +} + diff --git a/assignment_related_analytics/build.gradle b/assignment_related_analytics/build.gradle new file mode 100644 index 0000000..3cf35a2 --- /dev/null +++ b/assignment_related_analytics/build.gradle @@ -0,0 +1,38 @@ +group 'ro.ubb' +version '0.0.1-SNAPSHOT' + +//buildscript { +// ext { springBootVersion = '1.5.7.RELEASE' } +// repositories { mavenCentral() } +// dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } +//} + +apply plugin: 'java' +apply plugin: 'org.springframework.boot' + +sourceCompatibility = 1.8 + +buildscript { + repositories { mavenCentral() } +} + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.12' + compile('org.springframework.boot:spring-boot-starter-data-jpa') + compile('org.springframework.boot:spring-boot-starter-web') +// compile('org.springframework.boot:spring-boot-starter-data-mongodb') + compileOnly 'org.projectlombok:lombok:1.16.18' + runtime('com.h2database:h2') + runtime('mysql:mysql-connector-java') + testCompile('org.springframework.boot:spring-boot-starter-test') + + // jUnit 5 + testCompile("org.junit.jupiter:junit-jupiter-api:5.0.1") + testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.1") + testCompile("org.junit.platform:junit-platform-launcher:1.0.0") +// testCompile("com.github.sbrannen:spring-test-junit5:1.0.0") +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/IStudentApplication.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/IStudentApplication.java new file mode 100644 index 0000000..705faf5 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/IStudentApplication.java @@ -0,0 +1,14 @@ +package ro.ubb.istudent; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ro.ubb.istudent.util.MockBuilder; + +@SpringBootApplication +public class IStudentApplication { + + public static void main(String[] args) { + MockBuilder.sharedInstace(); + SpringApplication.run(IStudentApplication.class, args); + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/ServletInitializer.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/ServletInitializer.java new file mode 100644 index 0000000..dc4f3de --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/ServletInitializer.java @@ -0,0 +1,13 @@ +package ro.ubb.istudent; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +public class ServletInitializer extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(IStudentApplication.class); + } + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/controller/StatisticsAssignmentController.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/controller/StatisticsAssignmentController.java new file mode 100644 index 0000000..7786490 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/controller/StatisticsAssignmentController.java @@ -0,0 +1,80 @@ +package ro.ubb.istudent.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import ro.ubb.istudent.designpatterns.strategy.*; +import ro.ubb.istudent.dto.CourseDTO; +import ro.ubb.istudent.util.MockBuilder; + +import java.util.List; +import java.util.Queue; + +@RestController +public class StatisticsAssignmentController { + + private Context context; + + @Autowired + @Qualifier("assignmentsFeedbackTeachersStatistics") + private AssignmentsFeedbackTeachersStatistics assignmentsFeedbackTeachersStatistics; + + @Autowired + @Qualifier("assignmentsFeedbackStudentsStatistics") + private AssignmentsFeedbackStudentsStatistics assignmentsFeedbackStudentsStatistics; + + @Autowired + @Qualifier("completedAssignmentsCourseStatistics") + private CompletedAssignmentsCourseStatistics completedAssignmentsCourseStatistics; + + @Autowired + @Qualifier("assignmentsFilesStatistics") + private AssignmentsFilesStatistics assignmentsFilesStatistics; + + @Autowired + @Qualifier("allAttachementsStatistics") + private AllAttachementsStatistics allAttachementsStatistics; + + @Autowired + @Qualifier("maxNrOfAttachementsPerAssignmentStatistics") + private MaxNrOfAttachementsPerAssignmentStatistics maxNrOfAttachementsPerAssignmentStatistics; + + + @RequestMapping(value = "/feedback_teachers", method = RequestMethod.GET) + public long getStatisticsFeedbackFromTeachers() { + context = new Context(assignmentsFeedbackTeachersStatistics); + return context.executeStrategy(); + } + + @RequestMapping(value = "/courses", method = RequestMethod.GET) + public List getStatisticsForNumberOfCompletedAssignments() { + return completedAssignmentsCourseStatistics.computeStatistics(); + } + + @RequestMapping(value = "/assignements_have_files", method = RequestMethod.GET) + public long getNumberOfAssignmentsWithAttachements() { + context = new Context(assignmentsFilesStatistics); + return context.executeStrategy(); + } + + @RequestMapping(value = "/assignments_file_all", method = RequestMethod.GET) + public long getAllAttachmentsNr() { + context = new Context(allAttachementsStatistics); + return context.executeStrategy(); + } + + @RequestMapping(value = "/assignments_file_max", method = RequestMethod.GET) + public long getMaxNrOfAttachements() { + context = new Context(maxNrOfAttachementsPerAssignmentStatistics); + return context.executeStrategy(); + } + + @RequestMapping(value = "/feedback_students", method = RequestMethod.GET) + public long getNrAssignWithFeedbackFromStudent(){ + context = new Context(assignmentsFeedbackStudentsStatistics); + return context.executeStrategy(); + } + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/DefaultClass.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/DefaultClass.java new file mode 100644 index 0000000..a506160 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/DefaultClass.java @@ -0,0 +1,7 @@ +package ro.ubb.istudent.designpatterns; + +/** + * Created by Cristina on 1/25/2018. + */ +public class DefaultClass { +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/AssignmentBuildDirector.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/AssignmentBuildDirector.java new file mode 100644 index 0000000..c0f3967 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/AssignmentBuildDirector.java @@ -0,0 +1,54 @@ +package ro.ubb.istudent.designpatterns.builder; + +import ro.ubb.istudent.domain.AssignmentEntity; +import ro.ubb.istudent.domain.FeedbackEntity; +import ro.ubb.istudent.domain.StudentEntity; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +/** + * Created by Cristina on 1/25/2018. + */ + +public class AssignmentBuildDirector { + private AssignmentBuilder builder; + private static Integer generator = 0; + private static Random r = new Random(); + + public AssignmentBuildDirector(final AssignmentBuilder builder) { + this.builder = builder; + } + + private List generateList(int size){ + List l = new ArrayList<>(); + for (int i = 0; i attachments) { + assignment.setAttachments(attachments); + return this; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/AssignmentBuilder.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/AssignmentBuilder.java new file mode 100644 index 0000000..90ecc6d --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/AssignmentBuilder.java @@ -0,0 +1,31 @@ +package ro.ubb.istudent.designpatterns.builder; + +import ro.ubb.istudent.domain.AssignmentEntity; +import ro.ubb.istudent.domain.FeedbackEntity; + +import java.util.Date; +import java.util.List; + +/** + * Created by Cristina on 1/25/2018. + */ + +public interface AssignmentBuilder { + + AssignmentEntity build(); + + AssignmentBuilder id(final long id); + + AssignmentBuilder feedback(final FeedbackEntity feedbackEntity); + + AssignmentBuilder date(final Date date); + + AssignmentBuilder deadline(final Date deadline); + + AssignmentBuilder description(final String description); + + AssignmentBuilder isCompleted(final Boolean isCompleted); + + AssignmentBuilder attachments(final List attachments); + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuildDirector.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuildDirector.java new file mode 100644 index 0000000..ea08332 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuildDirector.java @@ -0,0 +1,28 @@ +package ro.ubb.istudent.designpatterns.builder; + +import ro.ubb.istudent.domain.StudentEntity; + +/** + * Created by Cristina on 1/25/2018. + */ + +public class StudentBuildDirector { + private StudentBuilder builder; + + public StudentBuildDirector(final StudentBuilder builder) { + this.builder = builder; + } + + public StudentEntity construct() { + return builder + .firstName("John") + .lastName("Smith") + .gender("MALE") + .age(25) + .yearOfGraduation(2014) + .countryOfResidence("Bulgaria") + .gradeBookId(1) + .build(); + } + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuilder.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuilder.java new file mode 100644 index 0000000..973c43c --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuilder.java @@ -0,0 +1,26 @@ +package ro.ubb.istudent.designpatterns.builder; + +import ro.ubb.istudent.domain.StudentEntity; + +/** + * Created by Cristina on 1/25/2018. + */ + +public interface StudentBuilder{ + + StudentEntity build(); + + StudentBuilder firstName(final String firstName); + + StudentBuilder lastName(final String lastName); + + StudentBuilder gender(final String gender); + + StudentBuilder age(final int age); + + StudentBuilder yearOfGraduation(final int yearOfGraduation); + + StudentBuilder countryOfResidence(final String countryOfResidence); + + StudentBuilder gradeBookId(final int gradeBookId); +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuilderImpl.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuilderImpl.java new file mode 100644 index 0000000..68c187d --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/builder/StudentBuilderImpl.java @@ -0,0 +1,62 @@ +package ro.ubb.istudent.designpatterns.builder; + +import ro.ubb.istudent.domain.StudentEntity; + +/** + * Created by Cristina on 1/25/2018. + */ + +public class StudentBuilderImpl implements StudentBuilder{ + private StudentEntity student; + + public StudentBuilderImpl() { + student = new StudentEntity(); + } + + @Override + public StudentEntity build() { + return student; + } + + @Override + public StudentBuilder firstName(final String firstName) { + student.setFirstName(firstName); + return this; + } + + @Override + public StudentBuilder lastName(final String lastName) { + student.setLastName(lastName); + return this; + } + + @Override + public StudentBuilder gender(final String gender) { + student.setGender(gender); + return this; + } + + @Override + public StudentBuilder age(final int age) { + student.setAge(age); + return this; + } + + @Override + public StudentBuilder yearOfGraduation(final int yearOfGraduation) { + student.setYearOfGraduation(yearOfGraduation); + return this; + } + + @Override + public StudentBuilder countryOfResidence(final String countryOfResidence) { + student.setCountryOfResidence(countryOfResidence); + return this; + } + + @Override + public StudentBuilder gradeBookId(final int gradeBookId) { + student.setGradeBookId(gradeBookId); + return this; + } +} \ No newline at end of file diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AllAttachementsStatistics.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AllAttachementsStatistics.java new file mode 100644 index 0000000..68b91df --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AllAttachementsStatistics.java @@ -0,0 +1,31 @@ +package ro.ubb.istudent.designpatterns.strategy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; +import ro.ubb.istudent.repository.AssignmentRepository; +import ro.ubb.istudent.service.AssignmentService; + +/** + * Created by dariusi on 1/26/18. + */ +@Component("allAttachementsStatistics") +@Transactional +public class AllAttachementsStatistics implements Strategy { + @Autowired + private AssignmentRepository assignmentRepository; + + @Autowired + private AssignmentService assignmentService; + + @Override + public long computeStatistics() { + assignmentService.createMockData(); + return this.assignmentRepository.findAll(). + stream(). + map(a -> a.getAttachments().size()) + .mapToInt(Integer::intValue) + .sum(); + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFeedbackStudentsStatistics.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFeedbackStudentsStatistics.java new file mode 100644 index 0000000..0a0af92 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFeedbackStudentsStatistics.java @@ -0,0 +1,27 @@ +package ro.ubb.istudent.designpatterns.strategy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; +import ro.ubb.istudent.repository.AssignmentRepository; +import ro.ubb.istudent.service.AssignmentService; + +@Component("assignmentsFeedbackStudentsStatistics") +@Transactional +public class AssignmentsFeedbackStudentsStatistics implements Strategy { + + @Autowired + private AssignmentRepository assignmentRepository; + + @Autowired + private AssignmentService assignmentService; + + @Override + public long computeStatistics() { + assignmentService.createMockData(); + return this.assignmentRepository.findAll().stream().filter( + assignmentEntity -> !ObjectUtils.isEmpty(assignmentEntity.getFeedback().getStudentEntity())) + .count(); + } +} \ No newline at end of file diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFeedbackTeachersStatistics.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFeedbackTeachersStatistics.java new file mode 100644 index 0000000..d6c5775 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFeedbackTeachersStatistics.java @@ -0,0 +1,23 @@ +package ro.ubb.istudent.designpatterns.strategy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; +import ro.ubb.istudent.repository.AssignmentRepository; + +@Component("assignmentsFeedbackTeachersStatistics") +@Transactional +public class AssignmentsFeedbackTeachersStatistics implements Strategy { + + @Autowired + private AssignmentRepository assignmentRepository; + + @Override + public long computeStatistics() { + return assignmentRepository.findAll() + .stream() + .filter(assignmentEntity -> !ObjectUtils.isEmpty(assignmentEntity.getFeedback().getTeacher())) + .count(); + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFilesStatistics.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFilesStatistics.java new file mode 100644 index 0000000..7f355ab --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/AssignmentsFilesStatistics.java @@ -0,0 +1,23 @@ +package ro.ubb.istudent.designpatterns.strategy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; +import ro.ubb.istudent.repository.AssignmentRepository; + +@Component("assignmentsFilesStatistics") +@Transactional +public class AssignmentsFilesStatistics implements Strategy { + + @Autowired + private AssignmentRepository assignmentRepository; + + @Override + public long computeStatistics() { + return assignmentRepository.findAll() + .stream() + .filter(assignmentEntity -> !ObjectUtils.isEmpty(!assignmentEntity.getAttachments().isEmpty())) + .count(); + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/CompletedAssignmentsCourseStatistics.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/CompletedAssignmentsCourseStatistics.java new file mode 100644 index 0000000..d1c750a --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/CompletedAssignmentsCourseStatistics.java @@ -0,0 +1,39 @@ +package ro.ubb.istudent.designpatterns.strategy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import ro.ubb.istudent.domain.AssignmentEntity; +import ro.ubb.istudent.domain.CourseEntity; +import ro.ubb.istudent.dto.CourseDTO; +import ro.ubb.istudent.repository.AssignmentRepository; +import ro.ubb.istudent.repository.CourseRepository; +import ro.ubb.istudent.util.MockBuilder; + +import java.util.ArrayList; +import java.util.List; + +@Component("completedAssignmentsCourseStatistics") +@Transactional +public class CompletedAssignmentsCourseStatistics{ + + @Autowired + private CourseRepository courserRepo; + + public List computeStatistics() { + courserRepo.load(MockBuilder.sharedInstace().courses); + List result = new ArrayList<>(); + for(CourseEntity c: courserRepo.findAll()) + { + int cnt = 0; + for(AssignmentEntity a : c.getAssignments()) + { + if(a.isCompleted()) + cnt++; + } + result.add(new CourseDTO(c.getName(),cnt, c.getAssignments().size() - cnt)); + } + + return result; + } +} \ No newline at end of file diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/Context.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/Context.java new file mode 100644 index 0000000..b537c2a --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/Context.java @@ -0,0 +1,14 @@ +package ro.ubb.istudent.designpatterns.strategy; + +public class Context { + private Strategy strategy; + + public Context(Strategy strategy){ + this.strategy = strategy; + } + + public long executeStrategy(){ + return strategy.computeStatistics(); + } + +} \ No newline at end of file diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/MaxNrOfAttachementsPerAssignmentStatistics.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/MaxNrOfAttachementsPerAssignmentStatistics.java new file mode 100644 index 0000000..55c9691 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/MaxNrOfAttachementsPerAssignmentStatistics.java @@ -0,0 +1,32 @@ +package ro.ubb.istudent.designpatterns.strategy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import ro.ubb.istudent.domain.AssignmentEntity; +import ro.ubb.istudent.repository.AssignmentRepository; +import ro.ubb.istudent.service.AssignmentService; + +import java.util.Comparator; + +/** + * Created by dariusi on 1/26/18. + */ +@Component("maxNrOfAttachementsPerAssignmentStatistics") +@Transactional +public class MaxNrOfAttachementsPerAssignmentStatistics implements Strategy { + @Autowired + private AssignmentRepository assignmentRepository; + + @Autowired + private AssignmentService assignmentService; + + @Override + public long computeStatistics() { + assignmentService.createMockData(); + // Define comparator + Comparator comparator = (a1, a2) -> Integer.compare(a1.getAttachments().size(), a2.getAttachments().size()); + + return assignmentRepository.findAll().stream().max(comparator).get().getAttachments().size(); + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/Strategy.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/Strategy.java new file mode 100644 index 0000000..a0abe67 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/designpatterns/strategy/Strategy.java @@ -0,0 +1,7 @@ +package ro.ubb.istudent.designpatterns.strategy; + +public interface Strategy { + + long computeStatistics(); + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AssignmentEntity.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AssignmentEntity.java new file mode 100644 index 0000000..c6bb1e9 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AssignmentEntity.java @@ -0,0 +1,106 @@ +package ro.ubb.istudent.domain; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +public class AssignmentEntity implements Serializable { + + private Long id; + private Long studentId; + private Long courseId; + private List attachments; + + private FeedbackEntity feedback; + private Date date; + private Date deadline; + private String description; + private Boolean isCompleted; + + public AssignmentEntity(){} + + public AssignmentEntity(Long id, Long studentId, Long courseId, List attachments, FeedbackEntity feedback, Date date, Date deadline, String description) { + this.id = id; + this.studentId = studentId; + this.courseId = courseId; + this.attachments = attachments; + this.feedback = feedback; + this.date = date; + this.deadline = deadline; + this.description = description; + } + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getStudentId() { + return studentId; + } + + public void setStudentId(Long studentId) { + this.studentId = studentId; + } + + public Long getCourseId() { + return courseId; + } + + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + + public FeedbackEntity getFeedback() { + return feedback; + } + + public void setFeedback(FeedbackEntity feedback) { + this.feedback = feedback; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public void setAttachments(List attachments) { + this.attachments = attachments; + } + + public List getAttachments() { + return attachments; + } + + public Date getDeadline() { + return deadline; + } + + public void setDeadline(Date deadline) { + this.deadline = deadline; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean isCompleted() { + return isCompleted; + } + + public void setIsCompleted(Boolean completed) { + isCompleted = completed; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AssignmentTypeEnum.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AssignmentTypeEnum.java new file mode 100644 index 0000000..340949d --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AssignmentTypeEnum.java @@ -0,0 +1,4 @@ +package ro.ubb.istudent.domain; + +public enum AssignmentTypeEnum { +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AttachmentEntity.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AttachmentEntity.java new file mode 100644 index 0000000..2cde450 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/AttachmentEntity.java @@ -0,0 +1,46 @@ +//package ro.ubb.istudent.domain; +// +//import javax.persistence.*; +//import java.io.Serializable; +// +//@Entity +//public class AttachmentEntity implements Serializable { +// +// @Id +// private Long id; +// private String content; +// +// @ManyToOne(fetch= FetchType.LAZY) +// @JoinColumn(name="ASSIGNMENT_ID") +// private AssignmentEntity assignment; +// +// public AttachmentEntity(Long id, String content, AssignmentEntity assignment) { +// this.id = id; +// this.content = content; +// this.assignment = assignment; +// } +// +// public Long getId() { +// return id; +// } +// +// public void setId(Long id) { +// this.id = id; +// } +// +// public String getContent() { +// return content; +// } +// +// public void setContent(String content) { +// this.content = content; +// } +// +// public AssignmentEntity getAssignment() { +// return assignment; +// } +// +// public void setAssignment(AssignmentEntity assignment) { +// this.assignment = assignment; +// } +//} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/CourseEntity.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/CourseEntity.java new file mode 100644 index 0000000..49ec305 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/CourseEntity.java @@ -0,0 +1,148 @@ +package ro.ubb.istudent.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +public class CourseEntity implements Serializable { + + + private Long id; + private String name; + private Long teacherID; + private List materials; + private List students; + + private List assignments; + private List exams; + private Long yearOfStudy; + private Date startDate; + private Date endDate; + private Integer minimumCourseMaterials; + + public CourseEntity(Long id, + String name, + Long teacherID, + Long yearOfStudy, + Date startDate, + Date endDate, + List assign, + Integer minimumCourseMaterials) { + this.id = id; + this.name = name; + this.teacherID = teacherID; + this.yearOfStudy = yearOfStudy; + this.startDate = startDate; + this.endDate = endDate; + this.assignments = assign; + this.minimumCourseMaterials = minimumCourseMaterials; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getTeacherID() { + return teacherID; + } + + public void setTeacherID(Long teacherID) { + this.teacherID = teacherID; + } + + public List getMaterials() { + return materials; + } + + public void setMaterials(List materials) { + this.materials = materials; + } + + public List getStudents() { + return students; + } + + public void setStudents(List students) { + this.students = students; + } + + public List getAssignments() { + return assignments; + } + + public void setAssignments(List assignments) { + this.assignments = assignments; + } + + public List getExams() { + return exams; + } + + public void setExams(List exams) { + this.exams = exams; + } + + public Long getYearOfStudy() { + return yearOfStudy; + } + + public void setYearOfStudy(Long yearOfStudy) { + this.yearOfStudy = yearOfStudy; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public Integer getMinimumCourseMaterials() { + return minimumCourseMaterials; + } + + public void setMinimumCourseMaterials(Integer minimumCourseMaterials) { + this.minimumCourseMaterials = minimumCourseMaterials; + } + + @Override + public String toString() { + return "CourseEntity{" + + "id=" + id + + ", name='" + name + '\'' + + ", teacherID=" + teacherID + + ", materials=" + materials + + ", students=" + students + + ", assignements=" + assignments + + ", exams=" + exams + + ", yearOfStudy=" + yearOfStudy + + ", startDate=" + startDate + + ", endDate=" + endDate + + ", minimumCourseMaterials=" + minimumCourseMaterials + + '}'; + } + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/FeedbackEntity.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/FeedbackEntity.java new file mode 100644 index 0000000..e70d1d1 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/FeedbackEntity.java @@ -0,0 +1,61 @@ +package ro.ubb.istudent.domain; + +import java.io.Serializable; + + +public class FeedbackEntity implements Serializable { + + private Integer id; + private TeacherEntity teacher; + private String description; + private StudentEntity studentEntity; + + private AssignmentEntity assignment; + + public FeedbackEntity(Integer id, TeacherEntity teacher, String description, StudentEntity studentEntity, + AssignmentEntity assignment) { + this.id = id; + this.teacher = teacher; + this.description = description; + this.studentEntity = studentEntity; + this.assignment = assignment; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) {this.id = id;} + + public TeacherEntity getTeacher() { + return teacher; + } + + public void setTeacher(TeacherEntity teacher) { + this.teacher = teacher; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public StudentEntity getStudentEntity() { + return studentEntity; + } + + public void setStudentEntity(StudentEntity studentEntity) { + this.studentEntity = studentEntity; + } + + public AssignmentEntity getAssignment() { + return assignment; + } + + public void setAssignment(AssignmentEntity assignment) { + this.assignment = assignment; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/GenderEnum.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/GenderEnum.java new file mode 100644 index 0000000..15650f5 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/GenderEnum.java @@ -0,0 +1,6 @@ +package ro.ubb.istudent.domain; + +public enum GenderEnum { + MALE, + FEMALE +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/StudentEntity.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/StudentEntity.java new file mode 100644 index 0000000..ab919f4 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/StudentEntity.java @@ -0,0 +1,125 @@ +package ro.ubb.istudent.domain; + +/** + * Created by Cristina on 12/12/2017. + */ + +import javax.persistence.Entity; +import javax.persistence.Id; +import java.io.Serializable; + +/** + * Created by Cristina on 12/12/2017. + */ +public class StudentEntity implements Serializable { + private long id; + private String firstName; + private String lastName; + private String gender; + private int age; + private long groupId; + private int yearOfGraduation; + private String countryOfResidence; + private long gradeBookId; + + public StudentEntity(){} + + public StudentEntity(long id, String firstName, String lastName, String gender, int age, long groupId, int yearOfGraduation, String countryOfResidence, long gradeBookId) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.gender = gender; + this.age = age; + this.groupId = groupId; + this.yearOfGraduation = yearOfGraduation; + this.countryOfResidence = countryOfResidence; + this.gradeBookId = gradeBookId; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public long getGroupId() { + return groupId; + } + + public void setGroupId(int groupId) { + this.groupId = groupId; + } + + public int getYearOfGraduation() { + return yearOfGraduation; + } + + public void setYearOfGraduation(int yearOfGraduation) { + this.yearOfGraduation = yearOfGraduation; + } + + public String getCountryOfResidence() { + return countryOfResidence; + } + + public void setCountryOfResidence(String countryOfResidence) { + this.countryOfResidence = countryOfResidence; + } + + public long getGradeBookId() { + return gradeBookId; + } + + public void setGradeBookId(int gradeBookId) { + this.gradeBookId = gradeBookId; + } + + @Override + public String toString() { + return "StudentEntity{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", gender='" + gender + '\'' + + ", age=" + age + + ", groupId=" + groupId + + ", yearOfGraduation=" + yearOfGraduation + + ", countryOfResidence='" + countryOfResidence + '\'' + + ", gradeBookId=" + gradeBookId + + '}'; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/TeacherEntity.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/TeacherEntity.java new file mode 100644 index 0000000..0edfbf4 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/domain/TeacherEntity.java @@ -0,0 +1,68 @@ +package ro.ubb.istudent.domain; + + +import javax.persistence.Entity; +import javax.persistence.Id; +import java.io.Serializable; + +public class TeacherEntity implements Serializable { + + private Long id; + + private String firstName; + + private String lastName; + + private GenderEnum gender; + + public TeacherEntity(){} + + public TeacherEntity(Long id, String firstName, String lastName, GenderEnum gender) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.gender = gender; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public GenderEnum getGender() { + return gender; + } + + public void setGender(GenderEnum gender) { + this.gender = gender; + } + + @Override + public String toString() { + return "TeacherEntity{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", gender=" + gender + + '}'; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/AssignmentDto.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/AssignmentDto.java new file mode 100644 index 0000000..46aa615 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/AssignmentDto.java @@ -0,0 +1,90 @@ +package ro.ubb.istudent.dto; + +import java.util.Date; + +public class AssignmentDto implements Dto { + + private Long id; + private Long studentId; + private Long courseId; + private Long materialId; + private Long feedbackId; + private Date date; + private Date deadline; + private String description; + + public AssignmentDto(Long id, Long studentId, Long courseId, Long materialId, Long feedbackId, Date date, Date deadline, String description) { + this.id = id; + this.studentId = studentId; + this.courseId = courseId; + this.materialId = materialId; + this.feedbackId = feedbackId; + this.date = date; + this.deadline = deadline; + this.description = description; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getStudentId() { + return studentId; + } + + public void setStudentId(Long studentId) { + this.studentId = studentId; + } + + public Long getCourseId() { + return courseId; + } + + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + + public Long getMaterialId() { + return materialId; + } + + public void setMaterialId(Long materialId) { + this.materialId = materialId; + } + + public Long getFeedbackId() { + return feedbackId; + } + + public void setFeedbackId(Long feedbackId) { + this.feedbackId = feedbackId; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public Date getDeadline() { + return deadline; + } + + public void setDeadline(Date deadline) { + this.deadline = deadline; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/CourseDTO.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/CourseDTO.java new file mode 100644 index 0000000..ea5e85a --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/CourseDTO.java @@ -0,0 +1,84 @@ +package ro.ubb.istudent.dto; + +/** + * Created by dariusi on 1/26/18. + */ +public class CourseDTO implements Dto { + + private String name; + private Integer completedAssignments; + private Integer unfinishedAssignments; + private String teacher; + + public String getTeacher() { + return teacher; + } + + public void setTeacher(String teacher) { + this.teacher = teacher; + } + + public String getYearOfStudy() { + return yearOfStudy; + } + + public void setYearOfStudy(String yearOfStudy) { + this.yearOfStudy = yearOfStudy; + } + + public String getStarDate() { + return starDate; + } + + public void setStarDate(String starDate) { + this.starDate = starDate; + } + + public String getEndDate() { + return endDate; + } + + public void setEndDate(String endDate) { + this.endDate = endDate; + } + + private String yearOfStudy; + private String starDate; + private String endDate; + + public CourseDTO(String name, Integer completedAssignments, Integer unfinishedAssignments) + { + this.name = name; + this.completedAssignments = completedAssignments; + this.unfinishedAssignments = unfinishedAssignments; + teacher = "Igna Darius"; + yearOfStudy= "Year: 3 Semester: 2"; + starDate = "20.08.2017"; + endDate = "20.01.2018"; + } + + public Integer getUnfinishedAssignments() { + return unfinishedAssignments; + } + + public void setUnfinishedAssignments(Integer unfinishedAssignments) { + this.unfinishedAssignments = unfinishedAssignments; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + public Integer getCompletedAssignments() { + return completedAssignments; + } + + public void setCompletedAssignments(Integer completedAssignments) { + this.completedAssignments = completedAssignments; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/Dto.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/Dto.java new file mode 100644 index 0000000..4ce6bc1 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/dto/Dto.java @@ -0,0 +1,6 @@ +package ro.ubb.istudent.dto; + +import java.io.Serializable; + +public interface Dto extends Serializable { +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/exception/GlobalExceptionHandler.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..cb175d8 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/exception/GlobalExceptionHandler.java @@ -0,0 +1,28 @@ +package ro.ubb.istudent.exception; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; + +import javax.persistence.EntityNotFoundException; + +@ControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(EntityNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public void processEntityNotFoundException(EntityNotFoundException ex) { + LOG.error("Entity not found {}", ex); + } + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public void processAllOtherExceptions(Exception ex) { + LOG.error("Unexpected exception. Please add a custom exception handler for ex: {}", ex); + } +} \ No newline at end of file diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/AssignmentRepository.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/AssignmentRepository.java new file mode 100644 index 0000000..79c1752 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/AssignmentRepository.java @@ -0,0 +1,14 @@ +package ro.ubb.istudent.repository; + +import ro.ubb.istudent.domain.AssignmentEntity; + +import java.util.List; + +public interface AssignmentRepository { + + void save(AssignmentEntity assignmentEntity); + void deleteAll(); + void load(List l); + List findAll(); + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/AssignmentRepositoryImpl.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/AssignmentRepositoryImpl.java new file mode 100644 index 0000000..429a905 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/AssignmentRepositoryImpl.java @@ -0,0 +1,37 @@ +package ro.ubb.istudent.repository; + +import org.springframework.stereotype.Repository; +import ro.ubb.istudent.domain.AssignmentEntity; + +import java.util.ArrayList; +import java.util.List; + +@Repository +public class AssignmentRepositoryImpl implements AssignmentRepository { + + private List assignmentEntities; + + public AssignmentRepositoryImpl() { + assignmentEntities = new ArrayList<>(); + } + + @Override + public void save(AssignmentEntity assignmentEntity) { + assignmentEntities.add(assignmentEntity); + } + + @Override + public void deleteAll() { + assignmentEntities.clear(); + } + + @Override + public void load(List l) { + assignmentEntities = l; + } + + @Override + public List findAll() { + return assignmentEntities; + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/CourseRepository.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/CourseRepository.java new file mode 100644 index 0000000..a545eb2 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/repository/CourseRepository.java @@ -0,0 +1,28 @@ +package ro.ubb.istudent.repository; + +import org.springframework.stereotype.Repository; +import ro.ubb.istudent.domain.CourseEntity; + +import java.util.List; + +/** + * Created by dariusi on 1/26/18. + */ +@Repository +public class CourseRepository { + private List courses; + + public List findAll(){ + return courses; + } + + public void load(List l) + { + courses = l; + } + + public void addCourse(CourseEntity c) + { + courses.add(c); + } +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/service/AssignmentService.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/service/AssignmentService.java new file mode 100644 index 0000000..ea2a5f0 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/service/AssignmentService.java @@ -0,0 +1,30 @@ +package ro.ubb.istudent.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; +import ro.ubb.istudent.designpatterns.builder.AssignmentBuildDirector; +import ro.ubb.istudent.designpatterns.builder.AssignmentBuildImpl; +import ro.ubb.istudent.designpatterns.builder.AssignmentBuilder; +import ro.ubb.istudent.domain.AssignmentEntity; +import ro.ubb.istudent.repository.AssignmentRepository; +import ro.ubb.istudent.util.MockBuilder; + +@Service +@Transactional +public class AssignmentService { + + private static final Logger LOG = LoggerFactory.getLogger(AssignmentService.class); + + @Autowired + private AssignmentRepository assignmentRepository; + + public void createMockData() { + assignmentRepository.load(MockBuilder.sharedInstace().assigns); + } + + +} diff --git a/assignment_related_analytics/src/main/java/ro/ubb/istudent/util/MockBuilder.java b/assignment_related_analytics/src/main/java/ro/ubb/istudent/util/MockBuilder.java new file mode 100644 index 0000000..9878cc7 --- /dev/null +++ b/assignment_related_analytics/src/main/java/ro/ubb/istudent/util/MockBuilder.java @@ -0,0 +1,93 @@ +package ro.ubb.istudent.util; + +import ro.ubb.istudent.designpatterns.builder.*; +import ro.ubb.istudent.domain.*; + +import java.util.*; + +public class MockBuilder { + static final MockBuilder shared = new MockBuilder(); + + public List assigns = new ArrayList<>(); + public List courses = new ArrayList<>(); + + static public MockBuilder sharedInstace() { + return shared; + } + + private MockBuilder() { + generateAssignments(10); + generateCourses(10); + } + + public void mockData() { + System.out.println("Data mocked"); + } + + private void generateAssignments(int size){ + for (int i = 0; i < size; i++) { + assigns.add(getAssignment()); + } + } + + private void generateCourses(int size){ + for (int i = 0; i < size; i++) { + courses.add(getCourse()); + } + } + + private List genAssignments(int size){ + List a = new ArrayList<>(); + for (int i = 0; i < size; i++) { + a.add(getAssignment()); + } + return a; + } + + public CourseEntity getCourse(){ + Random r = new Random(); + return new CourseEntity(1l,"Design Patterns" + ,0l + ,0l,new Date(),new Date(),genAssignments(r.nextInt()%8),0); + } + + public AssignmentEntity getAssignment(){ + Random r = new Random(); + final StudentBuilder studentBuilder = new StudentBuilderImpl(); + final StudentBuildDirector studentBuildDirector = new StudentBuildDirector(studentBuilder); + StudentEntity studentEntity; + TeacherEntity teacherEntity; + AssignmentBuilder builder = new AssignmentBuildImpl(); + Integer generator = r.nextInt() % 100; + if(r.nextBoolean()){ + studentEntity = studentBuildDirector.construct(); + teacherEntity = null; + } + else + { + studentEntity = null; + teacherEntity = new TeacherEntity(1l,"asd","asd",GenderEnum.MALE); + } + AssignmentEntity a = builder + .id(generator) + .feedback(new FeedbackEntity(generator, teacherEntity,"Description" ,studentEntity, + new AssignmentEntity())) + .date(Calendar.getInstance().getTime()) + .deadline(Calendar.getInstance().getTime()) + .description("Math Assign") + .isCompleted(r.nextBoolean()) + .attachments(generateList(r.nextInt() % 10 + 1)) + .build(); + return a; + } + + + private List generateList(int size){ + List l = new ArrayList<>(); + for (int i = 0; i dtoOptional) { + return dtoOptional.map(ResponseEntity::ok) + .orElseThrow(() -> new EntityNotFoundException("Cannot find entity by id.")); + } +} diff --git a/build.gradle b/build.gradle index a518043..fabe3a0 100644 --- a/build.gradle +++ b/build.gradle @@ -17,6 +17,8 @@ buildscript { } } +//plugins { id "io.spring.dependency-management" version "1.0.0.RELEASE" } + apply plugin: 'java' apply plugin: 'org.springframework.boot' apply plugin: 'war' @@ -39,17 +41,13 @@ repositories { maven { url 'https://jitpack.io' } } -configurations { - providedRuntime -} - dependencies { compile('org.springframework.boot:spring-boot-starter-thymeleaf') compile('org.springframework.boot:spring-boot-starter-web') + compileOnly 'org.projectlombok:lombok:1.16.18' compile('org.springframework.boot:spring-boot-starter-data-mongodb') compile("de.flapdoodle.embed:de.flapdoodle.embed.mongo") compile group: 'com.rabbitmq', name: 'amqp-client', version: '5.0.0' - runtime('com.h2database:h2') runtime('mysql:mysql-connector-java') providedRuntime('org.springframework.boot:spring-boot-starter-tomcat') @@ -62,6 +60,10 @@ dependencies { testCompile("com.github.sbrannen:spring-test-junit5:1.0.0") } +configurations { + providedRuntime +} + junitPlatform { // platformVersion '1.0.0' filters { @@ -77,4 +79,4 @@ junitPlatform { } enableStandardTestTask false reportsDir = file("$buildDir/test-results/test") -} +} \ No newline at end of file diff --git a/classes/production/project/application.yml b/classes/production/project/application.yml new file mode 100644 index 0000000..f5d4db0 --- /dev/null +++ b/classes/production/project/application.yml @@ -0,0 +1,2 @@ +application: + base-url: "http://localhost:8080/api" \ No newline at end of file diff --git a/classes/production/project/banner.txt b/classes/production/project/banner.txt new file mode 100644 index 0000000..30b48f6 --- /dev/null +++ b/classes/production/project/banner.txt @@ -0,0 +1,31 @@ + +██╗███████╗████████╗██╗ ██╗██████╗ ███████╗███╗ ██╗████████╗ +██║██╔════╝╚══██╔══╝██║ ██║██╔══██╗██╔════╝████╗ ██║╚══██╔══╝ +██║███████╗ ██║ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║ ██║ +██║╚════██║ ██║ ██║ ██║██║ ██║██╔══╝ ██║╚██╗██║ ██║ +██║███████║ ██║ ╚██████╔╝██████╔╝███████╗██║ ╚████║ ██║ +╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ + + + ${AnsiColor.BRIGHT_BLUE}████████████████████████████████████████████████████████████████████████████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████████████████████████████████████████████████████████████ + ${AnsiColor.RED}██████████████████${AnsiColor.BRIGHT_BLUE}████████████████${AnsiColor.BLACK}██████████████████████████████${AnsiColor.BRIGHT_BLUE}████████████████ + ${AnsiColor.RED}████████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██████████████ + ${AnsiColor.BRIGHT_RED}████${AnsiColor.RED}██████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.MAGENTA}██████████████████████${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████████████ + ${AnsiColor.BRIGHT_RED}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}████${AnsiColor.MAGENTA}██████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██${AnsiColor.BLACK}████${AnsiColor.BRIGHT_BLUE}██████ + ${AnsiColor.BRIGHT_RED}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.MAGENTA}██████${AnsiColor.WHITE}██${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_YELLOW}██████████████████${AnsiColor.BRIGHT_RED}████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.MAGENTA}██████${AnsiColor.WHITE}██${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_YELLOW}██████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_YELLOW}██████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}████████${AnsiColor.WHITE}████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_YELLOW}████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}██${AnsiColor.BRIGHT_YELLOW}████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_GREEN}██████████████████${AnsiColor.BRIGHT_YELLOW}██${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}████████${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BRIGHT_GREEN}██████████████████████${AnsiColor.WHITE}████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BRIGHT_YELLOW}██${AnsiColor.WHITE}██████████${AnsiColor.BRIGHT_YELLOW}██${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BRIGHT_GREEN}██████████████████████${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BLUE}██████████████████${AnsiColor.BRIGHT_GREEN}████████${AnsiColor.BLACK}██████${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████${AnsiColor.WHITE}████████████████${AnsiColor.MAGENTA}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BLUE}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}████████████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_BLUE}██████████████████${AnsiColor.BLUE}████${AnsiColor.BLUE}██████${AnsiColor.BLACK}████${AnsiColor.WHITE}██████${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██████ + ${AnsiColor.BRIGHT_BLUE}██████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}████${AnsiColor.WHITE}████████████████████${AnsiColor.BLACK}██████████████████${AnsiColor.BRIGHT_BLUE}████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}████████████████████████████████${AnsiColor.WHITE}██${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BRIGHT_BLUE}████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████████████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████████████ + ████████████████████████████████████████████████████████████████████████████████ + ${AnsiColor.BRIGHT_BLUE}:: Meow :: Running Spring Boot ${spring-boot.version} :: \ö/${AnsiColor.BLACK} diff --git a/classes/production/project/static/index.html b/classes/production/project/static/index.html new file mode 100644 index 0000000..ebdd16f --- /dev/null +++ b/classes/production/project/static/index.html @@ -0,0 +1,50 @@ + + + + + Spring Boot - POST-GET AJAX Example + + + + + + +
+ +
+
+ + +
+ +
+ + + + + + +
+ + + + + + \ No newline at end of file diff --git a/classes/production/project/static/js/greeting.js b/classes/production/project/static/js/greeting.js new file mode 100644 index 0000000..7718018 --- /dev/null +++ b/classes/production/project/static/js/greeting.js @@ -0,0 +1,72 @@ +$(document).ready(function () { + + var url = window.location; + var latestGreetingUrl; + + $("#btnId").click(function (event) { + event.preventDefault(); + + // Open Bootstrap Modal + if (latestGreetingUrl) { + openModel(); + // Get data from Server + ajaxGet(); + } + }); + + $("#greetingForm").submit(function (event) { + event.preventDefault(); + ajaxPost(); + }); + + // Open Bootstrap Modal + function openModel() { + $("#modalId").modal(); + } + + // DO GET + function ajaxGet() { + $.ajax({ + type: "GET", + url: latestGreetingUrl, + success: function (data) { + // fill data to Modal Body + fillData(data); + }, + error: function (e) { + fillData(null); + } + }); + } + + // DO POST + function ajaxPost() { + var result = {}; + $.each($("#greetingForm").serializeArray(), function () { + result[this.name] = this.value; + }); + + $.ajax({ + type: "POST", + url: "/api/greeting", + data: JSON.stringify(result), + dataType: "text", + contentType: "application/json; charset=utf-8", + success: function (data, status, xhr) { + latestGreetingUrl = xhr.getResponseHeader('Location'); + }, + error: function (data, status, xhr) { + var err = eval("(" + xhr.getResponseHeader('Location') + ")"); + alert(err); + } + }); + } + + function fillData(data) { + if (data != null) { + $(".modal-body #greetingId").text(JSON.stringify(data)); + } else { + $(".modal-body #greetingId").text("Can Not Get Data from Server!"); + } + } +}); \ No newline at end of file diff --git a/out/production/resources/application.yml b/out/production/resources/application.yml new file mode 100644 index 0000000..f5d4db0 --- /dev/null +++ b/out/production/resources/application.yml @@ -0,0 +1,2 @@ +application: + base-url: "http://localhost:8080/api" \ No newline at end of file diff --git a/out/production/resources/banner.txt b/out/production/resources/banner.txt new file mode 100644 index 0000000..30b48f6 --- /dev/null +++ b/out/production/resources/banner.txt @@ -0,0 +1,31 @@ + +██╗███████╗████████╗██╗ ██╗██████╗ ███████╗███╗ ██╗████████╗ +██║██╔════╝╚══██╔══╝██║ ██║██╔══██╗██╔════╝████╗ ██║╚══██╔══╝ +██║███████╗ ██║ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║ ██║ +██║╚════██║ ██║ ██║ ██║██║ ██║██╔══╝ ██║╚██╗██║ ██║ +██║███████║ ██║ ╚██████╔╝██████╔╝███████╗██║ ╚████║ ██║ +╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ + + + ${AnsiColor.BRIGHT_BLUE}████████████████████████████████████████████████████████████████████████████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████████████████████████████████████████████████████████████ + ${AnsiColor.RED}██████████████████${AnsiColor.BRIGHT_BLUE}████████████████${AnsiColor.BLACK}██████████████████████████████${AnsiColor.BRIGHT_BLUE}████████████████ + ${AnsiColor.RED}████████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██████████████ + ${AnsiColor.BRIGHT_RED}████${AnsiColor.RED}██████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.MAGENTA}██████████████████████${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████████████ + ${AnsiColor.BRIGHT_RED}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}████${AnsiColor.MAGENTA}██████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██${AnsiColor.BLACK}████${AnsiColor.BRIGHT_BLUE}██████ + ${AnsiColor.BRIGHT_RED}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.MAGENTA}██████${AnsiColor.WHITE}██${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_YELLOW}██████████████████${AnsiColor.BRIGHT_RED}████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.MAGENTA}██████${AnsiColor.WHITE}██${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_YELLOW}██████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_YELLOW}██████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}████████${AnsiColor.WHITE}████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_YELLOW}████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}██${AnsiColor.BRIGHT_YELLOW}████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_GREEN}██████████████████${AnsiColor.BRIGHT_YELLOW}██${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}████████${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BRIGHT_GREEN}██████████████████████${AnsiColor.WHITE}████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BRIGHT_YELLOW}██${AnsiColor.WHITE}██████████${AnsiColor.BRIGHT_YELLOW}██${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BRIGHT_GREEN}██████████████████████${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BLUE}██████████████████${AnsiColor.BRIGHT_GREEN}████████${AnsiColor.BLACK}██████${AnsiColor.WHITE}██${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.MAGENTA}████${AnsiColor.WHITE}████████████████${AnsiColor.MAGENTA}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██ + ${AnsiColor.BLUE}██████████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}████████████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████ + ${AnsiColor.BRIGHT_BLUE}██████████████████${AnsiColor.BLUE}████${AnsiColor.BLUE}██████${AnsiColor.BLACK}████${AnsiColor.WHITE}██████${AnsiColor.MAGENTA}██████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████████████████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██████ + ${AnsiColor.BRIGHT_BLUE}██████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██${AnsiColor.BLACK}████${AnsiColor.WHITE}████████████████████${AnsiColor.BLACK}██████████████████${AnsiColor.BRIGHT_BLUE}████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}██████${AnsiColor.BLACK}████████████████████████████████${AnsiColor.WHITE}██${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}██${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BRIGHT_BLUE}████████████${AnsiColor.BLACK}██${AnsiColor.WHITE}████${AnsiColor.BLACK}████${AnsiColor.WHITE}████${AnsiColor.BLACK}██${AnsiColor.BRIGHT_BLUE}████████████ + ${AnsiColor.BRIGHT_BLUE}████████████████████████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████████████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████${AnsiColor.BLACK}██████${AnsiColor.BRIGHT_BLUE}████████████ + ████████████████████████████████████████████████████████████████████████████████ + ${AnsiColor.BRIGHT_BLUE}:: Meow :: Running Spring Boot ${spring-boot.version} :: \ö/${AnsiColor.BLACK} diff --git a/out/production/resources/static/index.html b/out/production/resources/static/index.html new file mode 100644 index 0000000..ebdd16f --- /dev/null +++ b/out/production/resources/static/index.html @@ -0,0 +1,50 @@ + + + + + Spring Boot - POST-GET AJAX Example + + + + + + +
+ +
+
+ + +
+ +
+ + + + + + +
+ + + + + + \ No newline at end of file diff --git a/out/production/resources/static/js/greeting.js b/out/production/resources/static/js/greeting.js new file mode 100644 index 0000000..7718018 --- /dev/null +++ b/out/production/resources/static/js/greeting.js @@ -0,0 +1,72 @@ +$(document).ready(function () { + + var url = window.location; + var latestGreetingUrl; + + $("#btnId").click(function (event) { + event.preventDefault(); + + // Open Bootstrap Modal + if (latestGreetingUrl) { + openModel(); + // Get data from Server + ajaxGet(); + } + }); + + $("#greetingForm").submit(function (event) { + event.preventDefault(); + ajaxPost(); + }); + + // Open Bootstrap Modal + function openModel() { + $("#modalId").modal(); + } + + // DO GET + function ajaxGet() { + $.ajax({ + type: "GET", + url: latestGreetingUrl, + success: function (data) { + // fill data to Modal Body + fillData(data); + }, + error: function (e) { + fillData(null); + } + }); + } + + // DO POST + function ajaxPost() { + var result = {}; + $.each($("#greetingForm").serializeArray(), function () { + result[this.name] = this.value; + }); + + $.ajax({ + type: "POST", + url: "/api/greeting", + data: JSON.stringify(result), + dataType: "text", + contentType: "application/json; charset=utf-8", + success: function (data, status, xhr) { + latestGreetingUrl = xhr.getResponseHeader('Location'); + }, + error: function (data, status, xhr) { + var err = eval("(" + xhr.getResponseHeader('Location') + ")"); + alert(err); + } + }); + } + + function fillData(data) { + if (data != null) { + $(".modal-body #greetingId").text(JSON.stringify(data)); + } else { + $(".modal-body #greetingId").text("Can Not Get Data from Server!"); + } + } +}); \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..8498346 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +include 'assignment_related_analytics' + diff --git a/src/main/java/ro/ubb/istudent/IStudentApplication.java b/src/main/java/ro/ubb/istudent/IStudentApplication.java index 62cea69..e72868e 100644 --- a/src/main/java/ro/ubb/istudent/IStudentApplication.java +++ b/src/main/java/ro/ubb/istudent/IStudentApplication.java @@ -1,12 +1,14 @@ -package ro.ubb.istudent; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class IStudentApplication { - - public static void main(String[] args) { - SpringApplication.run(IStudentApplication.class, args); - } -} +//package ro.ubb.istudent; +// +//import org.springframework.boot.SpringApplication; +//import org.springframework.boot.autoconfigure.SpringBootApplication; +//import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +// +//@SpringBootApplication +//@EnableJpaRepositories +//public class IStudentApplication { +// +// public static void main(String[] args) { +// SpringApplication.run(IStudentApplication.class, args); +// } +//} diff --git a/src/main/resources/static/statistics.html b/src/main/resources/static/statistics.html new file mode 100644 index 0000000..566549b --- /dev/null +++ b/src/main/resources/static/statistics.html @@ -0,0 +1,10 @@ + + + + + Title + + + + + \ No newline at end of file diff --git a/src/test/java/ro/ubb/istudent/service/GreetingServiceTest.java b/src/test/java/ro/ubb/istudent/service/GreetingServiceTest.java index 57d244a..531e8fe 100644 --- a/src/test/java/ro/ubb/istudent/service/GreetingServiceTest.java +++ b/src/test/java/ro/ubb/istudent/service/GreetingServiceTest.java @@ -11,7 +11,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; import ro.ubb.istudent.IStudentApplication; -import ro.ubb.istudent.dto.GreetingDto; import java.util.Optional;