From 2f8021a2c04bc0586e6777448ae559f800175f13 Mon Sep 17 00:00:00 2001
From: Aaron Lee
Date: Tue, 15 Nov 2016 20:11:05 -0800
Subject: [PATCH 1/2] Update and version control pods to compile properly
---
iOSSwiftStarter/Podfile | 19 +-
iOSSwiftStarter/Podfile.lock | 32 +-
iOSSwiftStarter/Pods/Alamofire/LICENSE | 2 +-
iOSSwiftStarter/Pods/Alamofire/README.md | 305 +-
.../Pods/Alamofire/Source/Alamofire.swift | 75 +-
.../Pods/Alamofire/Source/Download.swift | 54 +-
.../Pods/Alamofire/Source/Error.swift | 56 +-
.../Pods/Alamofire/Source/Manager.swift | 264 +-
.../Alamofire/Source/MultipartFormData.swift | 92 +-
.../Source/NetworkReachabilityManager.swift | 244 +
.../Pods/Alamofire/Source/Notifications.swift | 47 +
.../Alamofire/Source/ParameterEncoding.swift | 74 +-
.../Pods/Alamofire/Source/Request.swift | 160 +-
.../Pods/Alamofire/Source/Response.swift | 54 +-
.../Source/ResponseSerialization.swift | 123 +-
.../Pods/Alamofire/Source/Result.swift | 42 +-
.../Alamofire/Source/ServerTrustPolicy.swift | 98 +-
.../Pods/Alamofire/Source/Stream.swift | 42 +-
.../Pods/Alamofire/Source/Timeline.swift | 138 +
.../Pods/Alamofire/Source/Upload.swift | 68 +-
.../Pods/Alamofire/Source/Validation.swift | 69 +-
.../AlamofireObjectMapper.swift | 108 +-
.../Pods/AlamofireObjectMapper/README.md | 63 +-
.../Kingfisher/KingfisherOptions.swift | 60 -
.../Kingfisher/KingfisherOptionsInfo.swift | 70 -
.../Kingfisher/UIButton+Kingfisher.swift | 592 ---
.../Kingfisher/UIImage+Extension.swift | 195 -
.../Kingfisher/UIImageView+Kingfisher.swift | 391 --
iOSSwiftStarter/Pods/Kingfisher/README.md | 110 +-
.../Sources/AnimatedImageView.swift | 375 ++
.../Pods/Kingfisher/Sources/Box.swift | 16 +
.../Pods/Kingfisher/Sources/Image.swift | 415 ++
.../{Kingfisher => Sources}/ImageCache.swift | 332 +-
.../ImageDownloader.swift | 198 +-
.../Kingfisher/Sources/ImagePrefetcher.swift | 270 +
.../ImageTransition.swift | 24 +-
.../Sources/ImageView+Kingfisher.swift | 291 ++
.../Pods/Kingfisher/Sources/Indicator.swift | 176 +
.../{Kingfisher => Sources}/Kingfisher.h | 4 +-
.../KingfisherManager.swift | 127 +-
.../Sources/KingfisherOptionsInfo.swift | 184 +
.../{Kingfisher => Sources}/Resource.swift | 23 +-
.../{Kingfisher => Sources}/String+MD5.swift | 153 +-
.../ThreadHelper.swift | 15 +-
.../Sources/UIButton+Kingfisher.swift | 317 ++
iOSSwiftStarter/Pods/Manifest.lock | 32 +-
.../ObjectMapper/Core/FromJSON.swift | 36 +-
.../ObjectMapper/ObjectMapper/Core/Map.swift | 24 +-
.../ObjectMapper/Core/Mappable.swift | 37 +-
.../ObjectMapper/Core/Mapper.swift | 145 +-
.../ObjectMapper/Core/Operators.swift | 160 +-
.../ObjectMapper/Core/ToJSON.swift | 24 +-
.../Transforms/DictionaryTransform.swift | 58 +
.../Transforms/NSDataTransform.swift | 50 +
.../Transforms/URLTransform.swift | 5 +-
iOSSwiftStarter/Pods/ObjectMapper/README.md | 36 +-
.../Pods/Pods.xcodeproj/project.pbxproj | 4512 +++++++++--------
.../xcschemes/Alamofire.xcscheme | 60 +
.../xcschemes/AlamofireObjectMapper.xcscheme | 60 +
.../xcschemes/AsyncSwift.xcscheme | 60 +
.../xcschemes/CoreStore.xcscheme | 60 +
.../xcschemes/GCDKit.xcscheme | 60 +
.../xcschemes/Hakuba.xcscheme | 60 +
.../xcschemes/Kingfisher.xcscheme | 60 +
.../alee.xcuserdatad/xcschemes/Kugel.xcscheme | 60 +
.../xcschemes/Nimble.xcscheme | 60 +
.../xcschemes/ObjectMapper.xcscheme | 60 +
.../xcschemes/Pods-iOSSwiftStarter.xcscheme | 60 +
.../Pods-iOSSwiftStarterTests.xcscheme | 60 +
.../Pods-iOSSwiftStarterUITests.xcscheme | 60 +
.../alee.xcuserdatad/xcschemes/Quick.xcscheme | 60 +
.../xcschemes/ReactKit.xcscheme | 60 +
.../xcschemes/StatefulViewController.xcscheme | 60 +
.../xcschemes/SwiftTask.xcscheme | 60 +
.../xcschemes/xcschememanagement.plist | 96 +
.../Alamofire/Alamofire-umbrella.h | 2 +
.../Target Support Files/Alamofire/Info.plist | 2 +-
.../AlamofireObjectMapper-umbrella.h | 2 +
.../AlamofireObjectMapper/Info.plist | 2 +-
.../AsyncSwift/AsyncSwift-umbrella.h | 2 +
.../CoreStore/CoreStore-umbrella.h | 2 +
.../GCDKit/GCDKit-umbrella.h | 2 +
.../Hakuba/Hakuba-umbrella.h | 2 +
.../Kingfisher/Info.plist | 2 +-
.../Kingfisher/Kingfisher-umbrella.h | 2 +
.../Kingfisher/Kingfisher.xcconfig | 1 +
.../Kugel/Kugel-umbrella.h | 2 +
.../Nimble/Nimble-umbrella.h | 2 +
.../ObjectMapper/Info.plist | 2 +-
.../ObjectMapper/ObjectMapper-umbrella.h | 2 +
...-iOSSwiftStarter-acknowledgements.markdown | 2 +-
...ods-iOSSwiftStarter-acknowledgements.plist | 30 +-
.../Pods-iOSSwiftStarter-resources.sh | 14 +-
.../Pods-iOSSwiftStarter-umbrella.h | 2 +
.../Pods-iOSSwiftStarter.debug.xcconfig | 1 +
.../Pods-iOSSwiftStarter.release.xcconfig | 1 +
...OSSwiftStarterTests-acknowledgements.plist | 6 +
.../Pods-iOSSwiftStarterTests-resources.sh | 14 +-
.../Pods-iOSSwiftStarterTests-umbrella.h | 2 +
.../Pods-iOSSwiftStarterTests.debug.xcconfig | 1 +
...Pods-iOSSwiftStarterTests.release.xcconfig | 1 +
.../Pods-iOSSwiftStarterUITests-resources.sh | 14 +-
.../Pods-iOSSwiftStarterUITests-umbrella.h | 2 +
...Pods-iOSSwiftStarterUITests.debug.xcconfig | 1 +
...ds-iOSSwiftStarterUITests.release.xcconfig | 1 +
.../Quick/Quick-umbrella.h | 2 +
.../ReactKit/ReactKit-umbrella.h | 2 +
.../StatefulViewController-umbrella.h | 2 +
.../SwiftTask/SwiftTask-umbrella.h | 2 +
.../iOSSwiftStarter.xcodeproj/project.pbxproj | 70 +-
110 files changed, 8132 insertions(+), 4869 deletions(-)
create mode 100644 iOSSwiftStarter/Pods/Alamofire/Source/NetworkReachabilityManager.swift
create mode 100644 iOSSwiftStarter/Pods/Alamofire/Source/Notifications.swift
create mode 100644 iOSSwiftStarter/Pods/Alamofire/Source/Timeline.swift
delete mode 100644 iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptions.swift
delete mode 100644 iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptionsInfo.swift
delete mode 100644 iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift
delete mode 100644 iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImage+Extension.swift
delete mode 100644 iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImageView+Kingfisher.swift
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/AnimatedImageView.swift
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/Box.swift
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/Image.swift
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/ImageCache.swift (70%)
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/ImageDownloader.swift (61%)
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/ImagePrefetcher.swift
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/ImageTransition.swift (90%)
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/Indicator.swift
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/Kingfisher.h (94%)
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/KingfisherManager.swift (65%)
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/Resource.swift (66%)
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/String+MD5.swift (64%)
rename iOSSwiftStarter/Pods/Kingfisher/{Kingfisher => Sources}/ThreadHelper.swift (68%)
create mode 100644 iOSSwiftStarter/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift
create mode 100644 iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Transforms/DictionaryTransform.swift
create mode 100644 iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Transforms/NSDataTransform.swift
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Alamofire.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/AlamofireObjectMapper.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/AsyncSwift.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/CoreStore.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/GCDKit.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Hakuba.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Kingfisher.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Kugel.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Nimble.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/ObjectMapper.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Pods-iOSSwiftStarter.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Pods-iOSSwiftStarterTests.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Pods-iOSSwiftStarterUITests.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/Quick.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/ReactKit.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/StatefulViewController.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/SwiftTask.xcscheme
create mode 100644 iOSSwiftStarter/Pods/Pods.xcodeproj/xcuserdata/alee.xcuserdatad/xcschemes/xcschememanagement.plist
diff --git a/iOSSwiftStarter/Podfile b/iOSSwiftStarter/Podfile
index ecc1560..2811b84 100644
--- a/iOSSwiftStarter/Podfile
+++ b/iOSSwiftStarter/Podfile
@@ -9,14 +9,14 @@ end
target 'iOSSwiftStarter' do
abstract_pods
- pod 'Alamofire', '~> 3.0'
- pod 'AlamofireObjectMapper', '~> 2.1'
+ pod 'Alamofire', '~> 3.5.0'
+ pod 'AlamofireObjectMapper', '~> 3.0.2'
pod 'ReactKit'
- pod 'Kugel'
+ pod 'Kugel', '~> 0.1.0'
pod 'CoreStore'
pod 'Hakuba'
- pod 'Kingfisher', '~> 1.8'
- pod 'AsyncSwift'
+ pod 'Kingfisher', '~> 2.6.1'
+ pod 'AsyncSwift', '~> 1.6.4'
pod 'StatefulViewController', '~> 1.0'
end
@@ -32,3 +32,12 @@ end
target 'iOSSwiftStarterUITests' do
end
+
+# Use Legacy Swift Language Version
+post_install do |installer|
+ installer.pods_project.targets.each do |target|
+ target.build_configurations.each do |configuration|
+ configuration.build_settings['SWIFT_VERSION'] = "2.3"
+ end
+ end
+end
\ No newline at end of file
diff --git a/iOSSwiftStarter/Podfile.lock b/iOSSwiftStarter/Podfile.lock
index 1b7f2d4..1841449 100644
--- a/iOSSwiftStarter/Podfile.lock
+++ b/iOSSwiftStarter/Podfile.lock
@@ -1,17 +1,17 @@
PODS:
- - Alamofire (3.1.4)
- - AlamofireObjectMapper (2.1.0):
- - Alamofire (~> 3.1.0)
+ - Alamofire (3.5.1)
+ - AlamofireObjectMapper (3.0.2):
+ - Alamofire (~> 3.2)
- ObjectMapper (~> 1.0)
- AsyncSwift (1.6.4)
- CoreStore (1.6.10):
- GCDKit (= 1.2.5)
- GCDKit (1.2.5)
- Hakuba (2.1.1)
- - Kingfisher (1.9.2)
+ - Kingfisher (2.6.1)
- Kugel (0.1.0)
- Nimble (4.0.1)
- - ObjectMapper (1.3.0)
+ - ObjectMapper (1.5.0)
- Quick (0.9.2)
- ReactKit (0.12.0):
- SwiftTask (~> 4.0.0)
@@ -19,13 +19,13 @@ PODS:
- SwiftTask (4.0.0)
DEPENDENCIES:
- - Alamofire (~> 3.0)
- - AlamofireObjectMapper (~> 2.1)
- - AsyncSwift
+ - Alamofire (~> 3.5.0)
+ - AlamofireObjectMapper (~> 3.0.2)
+ - AsyncSwift (~> 1.6.4)
- CoreStore
- Hakuba
- - Kingfisher (~> 1.8)
- - Kugel
+ - Kingfisher (~> 2.6.1)
+ - Kugel (~> 0.1.0)
- Nimble
- ObjectMapper (~> 1.0)
- Quick
@@ -33,21 +33,21 @@ DEPENDENCIES:
- StatefulViewController (~> 1.0)
SPEC CHECKSUMS:
- Alamofire: fbc829692f351fa1d8a31dd75fd7f7f56fea31fb
- AlamofireObjectMapper: 24097576202064f8b0a583452dd934064f78dc0e
+ Alamofire: 0dfba1184a543e2aa160f4e39cac4e8aba48d223
+ AlamofireObjectMapper: 70f97cbf45c01c48d26aa07a1a7059a60ed7411d
AsyncSwift: 3c90beed237324f1b57e1f1c414dc5501985d208
CoreStore: 17dd4d1673e9dd165262c55abe37d37b8132f643
GCDKit: ed6646fcf761ff139162aaac518b9ec1fb7aa720
Hakuba: bc5a0422290d086c33a6424a26dd58c1a1136e94
- Kingfisher: 7b6df0fa9d211807152c32c46494f9bc08f0e07b
+ Kingfisher: 7e5515bf6c4f2acad91f6400955d2257549cab7b
Kugel: 2efb1b1e3abe0911aca6f41d9c7560630e88f566
Nimble: 0f3c8b8b084cda391209c3c5efbb48bedeeb920a
- ObjectMapper: 4eb08a726e9791a93b2632049951b56a7c17e471
+ ObjectMapper: 386645adca9d9d23b95eda43090b09d66444cf14
Quick: 18d057bc66451eedd5d1c8dc99ba2a5db6e60226
ReactKit: a2b705e8a8674b9cb38b8112c07891df87e8e62b
StatefulViewController: 2a0e5ab30d9ade8e366253fb759baa9fbf458f3e
SwiftTask: 724ff63fc8bd9b366d242696d4aff098f6de3c3a
-PODFILE CHECKSUM: f3d7954ea384e9f7f62712fd425e07113253d445
+PODFILE CHECKSUM: 6e64c3853e61b3e9e20893fe4fc4bcfcdf9f1db8
-COCOAPODS: 1.0.0
+COCOAPODS: 1.1.1
diff --git a/iOSSwiftStarter/Pods/Alamofire/LICENSE b/iOSSwiftStarter/Pods/Alamofire/LICENSE
index 5b7934d..4cfbf72 100644
--- a/iOSSwiftStarter/Pods/Alamofire/LICENSE
+++ b/iOSSwiftStarter/Pods/Alamofire/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/iOSSwiftStarter/Pods/Alamofire/README.md b/iOSSwiftStarter/Pods/Alamofire/README.md
index bcc0ff4..e72f038 100644
--- a/iOSSwiftStarter/Pods/Alamofire/README.md
+++ b/iOSSwiftStarter/Pods/Alamofire/README.md
@@ -1,7 +1,7 @@

-[](https://travis-ci.org/Alamofire/Alamofire)
-[](https://img.shields.io/cocoapods/v/Alamofire.svg)
+[](https://travis-ci.org/Alamofire/Alamofire)
+[](https://img.shields.io/cocoapods/v/Alamofire.svg)
[](https://github.com/Carthage/Carthage)
[](http://cocoadocs.org/docsets/Alamofire)
[](http://twitter.com/AlamofireSF)
@@ -22,10 +22,18 @@ Alamofire is an HTTP networking library written in Swift.
- [x] Comprehensive Unit Test Coverage
- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire)
+## Component Libraries
+
+In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem.
+
+* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system.
+* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire.
+
## Requirements
- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
-- Xcode 7.2+
+- Xcode 8.0+
+- Swift 2.2 or 2.3
## Migration Guides
@@ -60,10 +68,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo
```ruby
source 'https://github.com/CocoaPods/Specs.git'
-platform :ios, '8.0'
+platform :ios, '10.0'
use_frameworks!
-pod 'Alamofire', '~> 3.0'
+target '' do
+ pod 'Alamofire', '~> 3.5'
+end
```
Then, run the following command:
@@ -86,7 +96,7 @@ $ brew install carthage
To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl
-github "Alamofire/Alamofire" ~> 3.0
+github "Alamofire/Alamofire" ~> 3.5
```
Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project.
@@ -161,6 +171,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
> Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler.
+### Validation
+
+By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.
+
+#### Manual Validation
+
+```swift
+Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
+ .validate(statusCode: 200..<300)
+ .validate(contentType: ["application/json"])
+ .response { response in
+ print(response)
+ }
+```
+
+#### Automatic Validation
+
+Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided.
+
+```swift
+Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
+ .validate()
+ .responseJSON { response in
+ switch response.result {
+ case .Success:
+ print("Validation Successful")
+ case .Failure(let error):
+ print(error)
+ }
+ }
+```
+
### Response Serialization
**Built-in Response Methods**
@@ -175,6 +217,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
+ .validate()
.response { request, response, data, error in
print(request)
print(response)
@@ -183,12 +226,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
}
```
-> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types.
+> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types.
#### Response Data Handler
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
+ .validate()
.responseData { response in
print(response.request)
print(response.response)
@@ -200,6 +244,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift
Alamofire.request(.GET, "https://httpbin.org/get")
+ .validate()
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
@@ -210,6 +255,7 @@ Alamofire.request(.GET, "https://httpbin.org/get")
```swift
Alamofire.request(.GET, "https://httpbin.org/get")
+ .validate()
.responseJSON { response in
debugPrint(response)
}
@@ -221,6 +267,7 @@ Response handlers can even be chained:
```swift
Alamofire.request(.GET, "https://httpbin.org/get")
+ .validate()
.responseString { response in
print("Response String: \(response.result.value)")
}
@@ -332,7 +379,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global `
```swift
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
- "Content-Type": "application/x-www-form-urlencoded"
+ "Accept": "application/json"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
@@ -341,6 +388,14 @@ Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
}
```
+The default Alamofire `Manager` provides a common set of headers for every request. These include:
+
+* `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC7230](https://tools.ietf.org/html/rfc7230#section-4.2.3).
+* `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.3.5).
+* `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 9.3.0) Alamofire/3.4.2`, per [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.5.3).
+
+Customizing these headers, since they need to be added to every request, should be done by creating a customized `Manager` instance and modifying the `defaultHTTPHeaders` dictionary, as shown in the [Modifying Session Configuration](#modifying-session-configuration) section.
+
### Caching
Caching is handled on the system framework level by [`NSURLCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache).
@@ -374,6 +429,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
+ .validate()
.responseJSON { response in
debugPrint(response)
}
@@ -540,38 +596,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
}
```
-### Validation
+### Timeline
-By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.
-
-#### Manual Validation
-
-```swift
-Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
- .validate(statusCode: 200..<300)
- .validate(contentType: ["application/json"])
- .response { response in
- print(response)
- }
-```
-
-#### Automatic Validation
-
-Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided.
+Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`.
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseJSON { response in
- switch response.result {
- case .Success:
- print("Validation Successful")
- case .Failure(let error):
- print(error)
- }
+ print(response.timeline)
}
```
+The above reports the following `Timeline` info:
+
+- `Latency`: 0.428 seconds
+- `Request Duration`: 0.428 seconds
+- `Serialization Duration`: 0.001 seconds
+- `Total Duration`: 0.429 seconds
+
### Printable
```swift
@@ -679,6 +722,20 @@ Requests can be suspended, resumed, and cancelled:
### Response Serialization
+#### Handling Errors
+
+Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples:
+
+```swift
+public enum BackendError: ErrorType {
+ case Network(error: NSError)
+ case DataSerialization(reason: String)
+ case JSONSerialization(error: NSError)
+ case ObjectSerialization(reason: String)
+ case XMLSerialization(error: NSError)
+}
+```
+
#### Creating a Custom Response Serializer
Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`.
@@ -687,26 +744,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/
```swift
extension Request {
- public static func XMLResponseSerializer() -> ResponseSerializer {
+ public static func XMLResponseSerializer() -> ResponseSerializer {
return ResponseSerializer { request, response, data, error in
- guard error == nil else { return .Failure(error!) }
+ guard error == nil else { return .Failure(.Network(error: error!)) }
guard let validData = data else {
- let failureReason = "Data could not be serialized. Input data was nil."
- let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
- return .Failure(error)
+ return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil."))
}
do {
let XML = try ONOXMLDocument(data: validData)
return .Success(XML)
} catch {
- return .Failure(error as NSError)
+ return .Failure(.XMLSerialization(error: error as NSError))
}
}
}
- public func responseXMLDocument(completionHandler: Response -> Void) -> Self {
+ public func responseXMLDocument(completionHandler: Response -> Void) -> Self {
return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler)
}
}
@@ -722,9 +777,9 @@ public protocol ResponseObjectSerializable {
}
extension Request {
- public func responseObject(completionHandler: Response -> Void) -> Self {
- let responseSerializer = ResponseSerializer { request, response, data, error in
- guard error == nil else { return .Failure(error!) }
+ public func responseObject(completionHandler: Response -> Void) -> Self {
+ let responseSerializer = ResponseSerializer { request, response, data, error in
+ guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
@@ -737,12 +792,10 @@ extension Request {
{
return .Success(responseObject)
} else {
- let failureReason = "JSON could not be serialized into response object: \(value)"
- let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
- return .Failure(error)
+ return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)"))
}
case .Failure(let error):
- return .Failure(error)
+ return .Failure(.JSONSerialization(error: error))
}
}
@@ -765,7 +818,7 @@ final class User: ResponseObjectSerializable {
```swift
Alamofire.request(.GET, "https://example.com/users/mattt")
- .responseObject { (response: Response) in
+ .responseObject { (response: Response) in
debugPrint(response)
}
```
@@ -777,10 +830,26 @@ public protocol ResponseCollectionSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}
+extension ResponseCollectionSerializable where Self: ResponseObjectSerializable {
+ static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] {
+ var collection = [Self]()
+
+ if let representation = representation as? [[String: AnyObject]] {
+ for itemRepresentation in representation {
+ if let item = Self(response: response, representation: itemRepresentation) {
+ collection.append(item)
+ }
+ }
+ }
+
+ return collection
+ }
+}
+
extension Alamofire.Request {
- public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self {
- let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in
- guard error == nil else { return .Failure(error!) }
+ public func responseCollection(completionHandler: Response<[T], BackendError> -> Void) -> Self {
+ let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in
+ guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error)
@@ -790,12 +859,10 @@ extension Alamofire.Request {
if let response = response {
return .Success(T.collection(response: response, representation: value))
} else {
- let failureReason = "Response collection could not be serialized due to nil response"
- let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
- return .Failure(error)
+ return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response"))
}
case .Failure(let error):
- return .Failure(error)
+ return .Failure(.JSONSerialization(error: error))
}
}
@@ -813,26 +880,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable {
self.username = response.URL!.lastPathComponent!
self.name = representation.valueForKeyPath("name") as! String
}
-
- static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
- var users: [User] = []
-
- if let representation = representation as? [[String: AnyObject]] {
- for userRepresentation in representation {
- if let user = User(response: response, representation: userRepresentation) {
- users.append(user)
- }
- }
- }
-
- return users
- }
}
```
```swift
Alamofire.request(.GET, "http://example.com/users")
- .responseCollection { (response: Response<[User], NSError>) in
+ .responseCollection { (response: Response<[User], BackendError>) in
debugPrint(response)
}
```
@@ -912,7 +965,7 @@ enum Router: URLRequestConvertible {
var URLRequest: NSMutableURLRequest {
let result: (path: String, parameters: [String: AnyObject]) = {
switch self {
- case .Search(let query, let page) where page > 1:
+ case .Search(let query, let page) where page > 0:
return ("/search", ["q": query, "offset": Router.perPage * page])
case .Search(let query, _):
return ("/search", ["q": query])
@@ -997,6 +1050,74 @@ enum Router: URLRequestConvertible {
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
```
+### SessionDelegate
+
+By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons.
+
+#### Override Closures
+
+The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available:
+
+```swift
+/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
+public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
+
+/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
+public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
+
+/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
+public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
+
+/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
+public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
+```
+
+The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains.
+
+```swift
+let delegate: Alamofire.Manager.SessionDelegate = manager.delegate
+
+delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
+ var finalRequest = request
+
+ if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") {
+ finalRequest = originalRequest
+ }
+
+ return finalRequest
+}
+```
+
+#### Subclassing
+
+Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs.
+
+```swift
+class LoggingSessionDelegate: Manager.SessionDelegate {
+ override func URLSession(
+ session: NSURLSession,
+ task: NSURLSessionTask,
+ willPerformHTTPRedirection response: NSHTTPURLResponse,
+ newRequest request: NSURLRequest,
+ completionHandler: NSURLRequest? -> Void)
+ {
+ print("URLSession will perform HTTP redirection to request: \(request)")
+
+ super.URLSession(
+ session,
+ task: task,
+ willPerformHTTPRedirection: response,
+ newRequest: request,
+ completionHandler: completionHandler
+ )
+ }
+}
+```
+
+Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort.
+
+> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks.
+
### Security
Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`.
@@ -1075,7 +1196,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server
#### Validating the Certificate Chain
-Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check.
+Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check.
There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server.
@@ -1114,19 +1235,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends
> It is recommended to always use valid certificates in production environments.
----
+### Network Reachability
-## Component Libraries
+The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces.
-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.
+```swift
+let manager = NetworkReachabilityManager(host: "www.apple.com")
-* [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.
+manager?.listener = { status in
+ print("Network Status Changed: \(status)")
+}
+
+manager?.startListening()
+```
+
+> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported.
+
+There are some important things to remember when using network reachability to determine what to do next.
+
+* **Do NOT** use Reachability to determine if a network request should be sent.
+ * You should **ALWAYS** send it.
+* When Reachability is restored, use the event to retry failed network requests.
+ * Even though the network requests may still fail, this is a good moment to retry them.
+* The network reachability status can be useful for determining why a network request may have failed.
+ * If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out."
+
+> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info.
+
+---
## Open Rdars
The following rdars have some affect on the current implementation of Alamofire.
* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case
+* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage
## FAQ
@@ -1144,6 +1287,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http://
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 enthusiam 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.
+
+
+
## License
Alamofire is released under the MIT license. See LICENSE for details.
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Alamofire.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Alamofire.swift
index 3b52d0f..743e3b9 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Alamofire.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Alamofire.swift
@@ -1,31 +1,33 @@
-// Alamofire.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Alamofire.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
import Foundation
// MARK: - URLStringConvertible
/**
- Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
+ Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
construct URL requests.
*/
public protocol URLStringConvertible {
@@ -42,27 +44,25 @@ public protocol URLStringConvertible {
}
extension String: URLStringConvertible {
- public var URLString: String {
- return self
- }
+ public var URLString: String { return self }
}
extension NSURL: URLStringConvertible {
public var URLString: String {
- return absoluteString
+ #if swift(>=2.3)
+ return absoluteString!
+ #else
+ return absoluteString
+ #endif
}
}
extension NSURLComponents: URLStringConvertible {
- public var URLString: String {
- return URL!.URLString
- }
+ public var URLString: String { return URL!.URLString }
}
extension NSURLRequest: URLStringConvertible {
- public var URLString: String {
- return URL!.URLString
- }
+ public var URLString: String { return URL!.URLString }
}
// MARK: - URLRequestConvertible
@@ -76,9 +76,7 @@ public protocol URLRequestConvertible {
}
extension NSURLRequest: URLRequestConvertible {
- public var URLRequest: NSMutableURLRequest {
- return self.mutableCopy() as! NSMutableURLRequest
- }
+ public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest }
}
// MARK: - Convenience
@@ -89,7 +87,16 @@ func URLRequest(
headers: [String: String]? = nil)
-> NSMutableURLRequest
{
- let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
+ let mutableURLRequest: NSMutableURLRequest
+
+ if URLString.dynamicType == NSMutableURLRequest.self {
+ mutableURLRequest = URLString as! NSMutableURLRequest
+ } else if URLString.dynamicType == NSURLRequest.self {
+ mutableURLRequest = (URLString as! NSURLRequest).URLRequest
+ } else {
+ mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
+ }
+
mutableURLRequest.HTTPMethod = method.rawValue
if let headers = headers {
@@ -353,11 +360,11 @@ public func download(URLRequest: URLRequestConvertible, destination: Request.Dow
// MARK: Resume Data
/**
- Creates a request using the shared manager instance for downloading from the resume data produced from a
+ Creates a request using the shared manager instance for downloading from the resume data produced from a
previous request cancellation.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
- when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
+ when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
information.
- parameter destination: The closure used to determine the destination of the downloaded file.
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Download.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Download.swift
index 1df90cc..ed39e33 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Download.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Download.swift
@@ -1,24 +1,26 @@
-// Download.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Download.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -112,8 +114,8 @@ extension Manager {
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
- when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
+ - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
+ when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
additional information.
- parameter destination: The closure used to determine the destination of the downloaded file.
@@ -128,14 +130,14 @@ extension Manager {
extension Request {
/**
- A closure executed once a 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
+ A closure executed once a 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 single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
/**
- Creates a download file destination closure which uses the default file manager to move the temporary file to a
+ 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.
@@ -152,7 +154,11 @@ extension Request {
let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)
if !directoryURLs.isEmpty {
+ #if swift(>=2.3)
+ return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!)!
+ #else
return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!)
+ #endif
}
return temporaryURL
@@ -211,12 +217,14 @@ extension Request {
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
+ if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
+
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
- totalBytesWritten,
+ totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Error.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Error.swift
index b776a3e..467d99c 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Error.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Error.swift
@@ -1,24 +1,26 @@
-// Error.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Error.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -39,6 +41,15 @@ public struct Error {
case PropertyListSerializationFailed = -6007
}
+ /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire.
+ public struct UserInfoKeys {
+ /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value.
+ public static let ContentType = "ContentType"
+
+ /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value.
+ public static let StatusCode = "StatusCode"
+ }
+
/**
Creates an `NSError` with the given error code and failure reason.
@@ -47,6 +58,7 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason.
*/
+ @available(*, deprecated=3.4.0)
public static func errorWithCode(code: Code, failureReason: String) -> NSError {
return errorWithCode(code.rawValue, failureReason: failureReason)
}
@@ -59,8 +71,18 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason.
*/
+ @available(*, deprecated=3.4.0)
public static func errorWithCode(code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Domain, code: code, userInfo: userInfo)
}
+
+ static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError {
+ return error(domain: domain, code: code.rawValue, failureReason: failureReason)
+ }
+
+ static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError {
+ let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
+ return NSError(domain: domain, code: code, userInfo: userInfo)
+ }
}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Manager.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Manager.swift
index ea405a4..8d7b2f2 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Manager.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Manager.swift
@@ -1,24 +1,26 @@
-// Manager.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Manager.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -30,7 +32,7 @@ public class Manager {
// MARK: - Properties
/**
- A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
+ A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
@@ -45,36 +47,62 @@ public class Manager {
*/
public static let defaultHTTPHeaders: [String: String] = {
// 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"
+ 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: String = {
- var components: [String] = []
- for (index, languageCode) in (NSLocale.preferredLanguages() as [String]).enumerate() {
- let q = 1.0 - (Double(index) * 0.1)
- components.append("\(languageCode);q=\(q)")
- if q <= 0.5 {
- break
- }
- }
-
- return components.joinWithSeparator(",")
- }()
+ let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
+ let quality = 1.0 - (Double(index) * 0.1)
+ return "\(languageCode);q=\(quality)"
+ }.joinWithSeparator(", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
+ // Example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 9.3.0) Alamofire/3.4.2`
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
- let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown"
- let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown"
- let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown"
- let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
+ 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"
- var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
- let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
+ let osNameVersion: String = {
+ let versionString: String
- if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) {
- return mutableUserAgent as String
- }
+ if #available(OSX 10.10, *) {
+ let version = NSProcessInfo.processInfo().operatingSystemVersion
+ versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
+ } else {
+ versionString = "10.9"
+ }
+
+ let osName: String = {
+ #if os(iOS)
+ return "iOS"
+ #elseif os(watchOS)
+ return "watchOS"
+ #elseif os(tvOS)
+ return "tvOS"
+ #elseif os(OSX)
+ return "OS X"
+ #elseif os(Linux)
+ return "Linux"
+ #else
+ return "Unknown"
+ #endif
+ }()
+
+ return "\(osName) \(versionString)"
+ }()
+
+ let alamofireVersion: String = {
+ guard
+ let afInfo = NSBundle(forClass: Manager.self).infoDictionary,
+ build = afInfo["CFBundleShortVersionString"]
+ else { return "Unknown" }
+
+ return "Alamofire/\(build)"
+ }()
+
+ return executable + "/" + appVersion + " (" + bundle + "; build:" + appBuild + "; " + osNameVersion + ") " + alamofireVersion
}
return "Alamofire"
@@ -99,14 +127,14 @@ public class Manager {
public var startRequestsImmediately: Bool = true
/**
- The background completion handler closure provided by the UIApplicationDelegate
- `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
- completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
+ 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
+
+ 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.
*/
public var backgroundCompletionHandler: (() -> Void)?
@@ -116,11 +144,11 @@ public class Manager {
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- - parameter configuration: The configuration used to construct the managed session.
+ - parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` 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
+ - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
@@ -151,11 +179,11 @@ public class Manager {
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
+ guard delegate === session.delegate else { return nil }
+
self.delegate = delegate
self.session = session
- guard delegate === session.delegate else { return nil }
-
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
@@ -226,18 +254,18 @@ public class Manager {
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
- public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
+ public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
- subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
+ /// Access the task delegate for the specified task in a thread-safe manner.
+ public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate
}
-
set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
}
@@ -262,6 +290,9 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
+ /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
+ public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
+
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
@@ -289,6 +320,11 @@ public class Manager {
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
+ guard sessionDidReceiveChallengeWithCompletion == nil else {
+ sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
+ return
+ }
+
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
@@ -329,11 +365,23 @@ public class Manager {
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
+ /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
+ /// requires the caller to call the `completionHandler`.
+ public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
+
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
+ /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
+ /// requires the caller to call the `completionHandler`.
+ public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
+
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
- public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
+ public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
+
+ /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
+ /// requires the caller to call the `completionHandler`.
+ public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
@@ -350,8 +398,8 @@ public class Manager {
- 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
+ - 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.
*/
public func URLSession(
@@ -359,8 +407,13 @@ public class Manager {
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
- completionHandler: ((NSURLRequest?) -> Void))
+ completionHandler: NSURLRequest? -> Void)
{
+ guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
+ taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
+ return
+ }
+
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
@@ -382,10 +435,16 @@ public class Manager {
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
- completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
+ completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{
+ guard taskDidReceiveChallengeWithCompletion == nil else {
+ taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
+ return
+ }
+
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
- completionHandler(taskDidReceiveChallenge(session, task, challenge))
+ let result = taskDidReceiveChallenge(session, task, challenge)
+ completionHandler(result.0, result.1)
} else if let delegate = self[task] {
delegate.URLSession(
session,
@@ -408,8 +467,13 @@ public class Manager {
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
- needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
+ needNewBodyStream completionHandler: NSInputStream? -> Void)
{
+ guard taskNeedNewBodyStreamWithCompletion == nil else {
+ taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
+ return
+ }
+
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
@@ -460,6 +524,8 @@ public class Manager {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
+ NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
+
self[task] = nil
}
@@ -470,6 +536,10 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
+ /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
+ /// requires caller to call the `completionHandler`.
+ public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
+
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
@@ -477,7 +547,11 @@ public class Manager {
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
- public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
+ public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
+
+ /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
+ /// requires caller to call the `completionHandler`.
+ public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
// MARK: Delegate Methods
@@ -487,16 +561,21 @@ public class Manager {
- 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
+ - 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.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
- completionHandler: ((NSURLSessionResponseDisposition) -> Void))
+ completionHandler: NSURLSessionResponseDisposition -> Void)
{
+ guard dataTaskDidReceiveResponseWithCompletion == nil else {
+ dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
+ return
+ }
+
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
@@ -546,20 +625,25 @@ public class Manager {
- 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
+ - 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
+ - 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.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
- completionHandler: ((NSCachedURLResponse?) -> Void))
+ completionHandler: NSCachedURLResponse? -> 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] as? Request.DataTaskDelegate {
@@ -594,8 +678,8 @@ public class Manager {
- 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
+ - 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.
*/
public func URLSession(
@@ -615,11 +699,11 @@ public class Manager {
- 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
+ - 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
+ - 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`.
*/
public func URLSession(
@@ -647,11 +731,11 @@ public class Manager {
- 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
+ - 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.
+ - 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.
*/
public func URLSession(
@@ -682,17 +766,21 @@ public class Manager {
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
+ #if !os(OSX)
+ if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
+ return sessionDidFinishEventsForBackgroundURLSession != nil
+ }
+ #endif
+
switch selector {
- case "URLSession:didBecomeInvalidWithError:":
+ case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
- case "URLSession:didReceiveChallenge:completionHandler:":
- return sessionDidReceiveChallenge != nil
- case "URLSessionDidFinishEventsForBackgroundURLSession:":
- return sessionDidFinishEventsForBackgroundURLSession != nil
- case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
- return taskWillPerformHTTPRedirection != nil
- case "URLSession:dataTask:didReceiveResponse:completionHandler:":
- return dataTaskDidReceiveResponse != nil
+ case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
+ return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
+ case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
+ return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
+ case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
+ return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/MultipartFormData.swift b/iOSSwiftStarter/Pods/Alamofire/Source/MultipartFormData.swift
index d798f9c..5a7ef09 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/MultipartFormData.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/MultipartFormData.swift
@@ -1,24 +1,26 @@
-// MultipartFormData.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// MultipartFormData.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -29,10 +31,10 @@ 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
+ 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
@@ -116,7 +118,7 @@ public class MultipartFormData {
self.bodyParts = []
/**
- * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
+ * 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
*/
@@ -217,7 +219,7 @@ public class MultipartFormData {
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
- setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason))
+ setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
}
}
@@ -245,8 +247,7 @@ public class MultipartFormData {
guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
- let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
- setBodyPartError(error)
+ setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
@@ -261,8 +262,7 @@ public class MultipartFormData {
}
guard isReachable else {
- let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
- setBodyPartError(error)
+ setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
return
}
@@ -277,8 +277,7 @@ public class MultipartFormData {
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
- let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
- setBodyPartError(error)
+ setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
@@ -301,8 +300,7 @@ public class MultipartFormData {
guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
- let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
- setBodyPartError(error)
+ setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
@@ -312,8 +310,7 @@ public class MultipartFormData {
guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
- let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
- setBodyPartError(error)
+ setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
return
}
@@ -370,8 +367,8 @@ public class MultipartFormData {
/**
Encodes all the appended body parts into a single `NSData` object.
- 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
+ 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 `NSError` if encoding encounters an error.
@@ -413,10 +410,10 @@ public class MultipartFormData {
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)"
- throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
+ throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)"
- throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
+ throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
}
let outputStream: NSOutputStream
@@ -425,10 +422,9 @@ public class MultipartFormData {
outputStream = possibleOutputStream
} else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
- throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
+ throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
}
- outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true
@@ -439,7 +435,6 @@ public class MultipartFormData {
}
outputStream.close()
- outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
// MARK: - Private - Body Part Encoding
@@ -476,7 +471,6 @@ public class MultipartFormData {
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream
- inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
var error: NSError?
@@ -495,7 +489,7 @@ public class MultipartFormData {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
- error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
+ error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
break
} else {
break
@@ -503,7 +497,6 @@ public class MultipartFormData {
}
inputStream.close()
- inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error {
throw error
@@ -537,7 +530,6 @@ public class MultipartFormData {
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream
- inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
while inputStream.hasBytesAvailable {
@@ -556,14 +548,13 @@ public class MultipartFormData {
try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
- throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
+ throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
} else {
break
}
}
inputStream.close()
- inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
private func writeFinalBoundaryDataForBodyPart(
@@ -598,7 +589,7 @@ public class MultipartFormData {
if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)"
- throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason)
+ throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason)
}
bytesToWrite -= bytesWritten
@@ -661,9 +652,8 @@ public class MultipartFormData {
// MARK: - Private - Errors
- private func setBodyPartError(error: NSError) {
- if bodyPartError == nil {
- bodyPartError = error
- }
+ private func setBodyPartError(code code: Int, failureReason: String) {
+ guard bodyPartError == nil else { return }
+ bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/iOSSwiftStarter/Pods/Alamofire/Source/NetworkReachabilityManager.swift
new file mode 100644
index 0000000..d5e00ae
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/NetworkReachabilityManager.swift
@@ -0,0 +1,244 @@
+//
+// NetworkReachabilityManager.swift
+//
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#if !os(watchOS)
+
+import Foundation
+import SystemConfiguration
+
+/**
+ The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
+ WiFi network interfaces.
+
+ Reachability can be used to determine background information about why a network operation failed, or to retry
+ network requests when a connection is established. It should not be used to prevent a user from initiating a network
+ request, as it's possible that an initial request may be required to establish reachability.
+*/
+public class NetworkReachabilityManager {
+ /**
+ Defines the various states of network reachability.
+
+ - Unknown: It is unknown whether the network is reachable.
+ - NotReachable: The network is not reachable.
+ - ReachableOnWWAN: The network is reachable over the WWAN connection.
+ - ReachableOnWiFi: The network is reachable over the WiFi connection.
+ */
+ 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: dispatch_queue_t = dispatch_get_main_queue()
+
+ /// 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(sizeofValue(address))
+ address.sin_family = sa_family_t(AF_INET)
+
+ guard let reachability = withUnsafePointer(&address, {
+ SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($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.
+ */
+ public func startListening() -> Bool {
+ var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
+ context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
+
+ let callbackEnabled = SCNetworkReachabilitySetCallback(
+ reachability,
+ { (_, flags, info) in
+ let reachability = Unmanaged.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
+ reachability.notifyListener(flags)
+ },
+ &context
+ )
+
+ let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
+
+ dispatch_async(listenerQueue) {
+ self.previousFlags = SCNetworkReachabilityFlags()
+ self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
+ }
+
+ return callbackEnabled && queueEnabled
+ }
+
+ /**
+ Stops listening for changes in network reachability status.
+ */
+ public func stopListening() {
+ SCNetworkReachabilitySetCallback(reachability, nil, nil)
+ SCNetworkReachabilitySetDispatchQueue(reachability, nil)
+ }
+
+ // MARK: - Internal - Listener Notification
+
+ func notifyListener(flags: SCNetworkReachabilityFlags) {
+ guard previousFlags != flags else { return }
+ previousFlags = flags
+
+ listener?(networkReachabilityStatusForFlags(flags))
+ }
+
+ // MARK: - Internal - Network Reachability Status
+
+ func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
+ guard flags.contains(.Reachable) else { return .NotReachable }
+
+ var networkStatus: NetworkReachabilityStatus = .NotReachable
+
+ if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
+
+ if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
+ if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
+ }
+
+ #if os(iOS)
+ if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) }
+ #endif
+
+ return networkStatus
+ }
+}
+
+// MARK: -
+
+extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
+
+/**
+ Returns whether the two network reachability status values are equal.
+
+ - parameter lhs: The left-hand side value to compare.
+ - parameter rhs: The right-hand side value to compare.
+
+ - returns: `true` if the two values are equal, `false` otherwise.
+*/
+public func ==(
+ lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
+ rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
+ -> Bool
+{
+ switch (lhs, rhs) {
+ case (.Unknown, .Unknown):
+ return true
+ case (.NotReachable, .NotReachable):
+ return true
+ case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)):
+ return lhsConnectionType == rhsConnectionType
+ default:
+ return false
+ }
+}
+
+#endif
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Notifications.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Notifications.swift
new file mode 100644
index 0000000..a7dbcfe
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Notifications.swift
@@ -0,0 +1,47 @@
+//
+// Notifications.swift
+//
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+import Foundation
+
+/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload.
+public struct Notifications {
+ /// Used as a namespace for all `NSURLSessionTask` related notifications.
+ public struct Task {
+ /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed
+ /// `NSURLSessionTask`.
+ public static let DidResume = "com.alamofire.notifications.task.didResume"
+
+ /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the
+ /// suspended `NSURLSessionTask`.
+ public static let DidSuspend = "com.alamofire.notifications.task.didSuspend"
+
+ /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the
+ /// cancelled `NSURLSessionTask`.
+ public static let DidCancel = "com.alamofire.notifications.task.didCancel"
+
+ /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the
+ /// completed `NSURLSessionTask`.
+ public static let DidComplete = "com.alamofire.notifications.task.didComplete"
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/ParameterEncoding.swift b/iOSSwiftStarter/Pods/Alamofire/Source/ParameterEncoding.swift
index c417503..c54e58b 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/ParameterEncoding.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/ParameterEncoding.swift
@@ -1,24 +1,26 @@
-// ParameterEncoding.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// ParameterEncoding.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -36,8 +38,8 @@ public enum Method: String {
/**
Used to specify the way in which a set of parameters are applied to a URL request.
- - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
- and `DELETE` requests, or set as the body for requests with any other HTTP method. The
+ - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
+ and `DELETE` requests, or set as the body for requests with any other HTTP method. 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
@@ -47,8 +49,8 @@ public enum Method: String {
- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same
implementation as the `.URL` case, but always applies the encoded result to the URL.
- - `JSON`: Uses `NSJSONSerialization` 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
+ - `JSON`: Uses `NSJSONSerialization` 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`.
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
@@ -69,10 +71,10 @@ public enum 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
+ - parameter URLRequest: The request to have parameters applied.
+ - parameter parameters: The parameters to apply.
- - returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
+ - returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any.
*/
public func encode(
@@ -82,9 +84,7 @@ public enum ParameterEncoding {
{
var mutableURLRequest = URLRequest.URLRequest
- guard let parameters = parameters where !parameters.isEmpty else {
- return (mutableURLRequest, nil)
- }
+ guard let parameters = parameters else { return (mutableURLRequest, nil) }
var encodingError: NSError? = nil
@@ -118,7 +118,10 @@ public enum ParameterEncoding {
}
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
- if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
+ if let
+ URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false)
+ where !parameters.isEmpty
+ {
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL
@@ -141,7 +144,10 @@ public enum ParameterEncoding {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
- mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
+ mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ }
+
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
@@ -153,7 +159,11 @@ public enum ParameterEncoding {
format: format,
options: options
)
- mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
+
+ if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
+ mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
+ }
+
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
@@ -219,7 +229,7 @@ public enum ParameterEncoding {
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
- // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
+ // 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:
//
@@ -236,7 +246,7 @@ public enum ParameterEncoding {
while index != string.endIndex {
let startIndex = index
let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
- let range = Range(start: startIndex, end: endIndex)
+ let range = startIndex.. [String: String] {
+ guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] }
+
+ let credential = data.base64EncodedStringWithOptions([])
+
+ return ["Authorization": "Basic \(credential)"]
+ }
+
// MARK: - Progress
/**
- Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
+ Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
from the server.
- - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
+ - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
to write.
- - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
+ - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
expected to read.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
@@ -130,8 +153,8 @@ public class Request {
/**
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
+ 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 `response` closure will be called with nil `responseData`.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
@@ -149,17 +172,21 @@ public class Request {
// MARK: - State
/**
- Suspends the request.
+ Resumes the request.
*/
- public func suspend() {
- task.suspend()
+ public func resume() {
+ if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
+
+ task.resume()
+ NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task)
}
/**
- Resumes the request.
+ Suspends the request.
*/
- public func resume() {
- task.resume()
+ public func suspend() {
+ task.suspend()
+ NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task)
}
/**
@@ -176,12 +203,14 @@ public class Request {
} else {
task.cancel()
}
+
+ NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task)
}
// MARK: - TaskDelegate
/**
- The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
+ 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.
*/
public class TaskDelegate: NSObject {
@@ -195,6 +224,7 @@ public class Request {
var data: NSData? { return nil }
var error: NSError?
+ var initialResponseTime: CFAbsoluteTime?
var credential: NSURLCredential?
init(task: NSURLSessionTask) {
@@ -272,7 +302,7 @@ public class Request {
}
} else {
if challenge.previousFailureCount > 0 {
- disposition = .CancelAuthenticationChallenge
+ disposition = .RejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
@@ -381,6 +411,8 @@ public class Request {
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
+ if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
+
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
@@ -426,7 +458,7 @@ public class Request {
extension Request: CustomStringConvertible {
/**
- The textual representation used when written to an output stream, which includes the HTTP method and URL, as
+ 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.
*/
public var description: String {
@@ -454,22 +486,24 @@ extension Request: CustomDebugStringConvertible {
func cURLRepresentation() -> String {
var components = ["$ curl -i"]
- guard let request = self.request else {
+ guard let
+ request = self.request,
+ URL = request.URL,
+ host = URL.host
+ else {
return "$ curl command could not be created"
}
- let URL = request.URL
-
if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" {
components.append("-X \(HTTPMethod)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(
- host: URL!.host!,
- port: URL!.port?.integerValue ?? 0,
- `protocol`: URL!.scheme,
- realm: URL!.host!,
+ host: host,
+ port: URL.port?.integerValue ?? 0,
+ protocol: URL.scheme,
+ realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
@@ -487,44 +521,46 @@ extension Request: CustomDebugStringConvertible {
if session.configuration.HTTPShouldSetCookies {
if let
cookieStorage = session.configuration.HTTPCookieStorage,
- cookies = cookieStorage.cookiesForURL(URL!) where !cookies.isEmpty
+ cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
- if let headerFields = request.allHTTPHeaderFields {
- for (field, value) in headerFields {
- switch field {
- case "Cookie":
- continue
- default:
- components.append("-H \"\(field): \(value)\"")
- }
+ var headers: [NSObject: AnyObject] = [:]
+
+ if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
+ for (field, value) in additionalHeaders where field != "Cookie" {
+ headers[field] = value
}
}
- if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
- for (field, value) in additionalHeaders {
- switch field {
- case "Cookie":
- continue
- default:
- components.append("-H \"\(field): \(value)\"")
- }
+ if let headerFields = request.allHTTPHeaderFields {
+ for (field, value) in headerFields where field != "Cookie" {
+ headers[field] = value
}
}
+ for (field, value) in headers {
+ components.append("-H \"\(field): \(value)\"")
+ }
+
if let
HTTPBodyData = request.HTTPBody,
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
{
- let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
+ var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"")
+ escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
+
components.append("-d \"\(escapedBody)\"")
}
- components.append("\"\(URL!.absoluteString)\"")
+ #if swift(>=2.3)
+ components.append("\"\(URL.absoluteString!)\"")
+ #else
+ components.append("\"\(URL.absoluteString)\"")
+ #endif
return components.joinWithSeparator(" \\\n\t")
}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Response.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Response.swift
index 834f8ea..9c437ff 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Response.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Response.swift
@@ -1,24 +1,26 @@
-// Response.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Response.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -36,22 +38,33 @@ public struct Response {
/// The result of response serialization.
public let result: Result
+ /// The timeline of the complete lifecycle of the `Request`.
+ public let timeline: Timeline
+
/**
Initializes the `Response` instance with the specified URL request, URL response, server data and response
serialization result.
-
+
- 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 `Response` instance.
*/
- public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result) {
+ public init(
+ request: NSURLRequest?,
+ response: NSHTTPURLResponse?,
+ data: NSData?,
+ result: Result,
+ timeline: Timeline = Timeline())
+ {
self.request = request
self.response = response
self.data = data
self.result = result
+ self.timeline = timeline
}
}
@@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible {
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.length ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)")
+ output.append("[Timeline]: \(timeline.debugDescription)")
return output.joinWithSeparator("\n")
}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/ResponseSerialization.swift b/iOSSwiftStarter/Pods/Alamofire/Source/ResponseSerialization.swift
index e621ece..89e3954 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/ResponseSerialization.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/ResponseSerialization.swift
@@ -1,24 +1,26 @@
-// ResponseSerialization.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// ResponseSerialization.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -29,10 +31,10 @@ import Foundation
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
- typealias SerializedObject
+ associatedtype SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
- typealias ErrorObject: ErrorType
+ associatedtype ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
@@ -99,7 +101,7 @@ extension Request {
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,
+ - 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.
@@ -119,16 +121,25 @@ extension Request {
self.delegate.error
)
- dispatch_async(queue ?? dispatch_get_main_queue()) {
- let response = Response(
- request: self.request,
- response: self.response,
- data: self.delegate.data,
- result: result
- )
+ let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
+ let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
- completionHandler(response)
- }
+ let timeline = Timeline(
+ requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
+ initialResponseTime: initialResponseTime,
+ requestCompletedTime: requestCompletedTime,
+ serializationCompletedTime: CFAbsoluteTimeGetCurrent()
+ )
+
+ let response = Response(
+ request: self.request,
+ response: self.response,
+ data: self.delegate.data,
+ result: result,
+ timeline: timeline
+ )
+
+ dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) }
}
return self
@@ -152,7 +163,7 @@ extension Request {
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
- let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
+ let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
@@ -167,8 +178,12 @@ extension Request {
- returns: The request.
*/
- public func responseData(completionHandler: Response -> Void) -> Self {
- return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
+ public func responseData(
+ queue queue: dispatch_queue_t? = nil,
+ completionHandler: Response -> Void)
+ -> Self
+ {
+ return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
@@ -177,16 +192,16 @@ extension Request {
extension Request {
/**
- Creates a response serializer that returns a string initialized from the response data with the specified
+ Creates a response serializer that returns a string 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
+ - 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(
- var encoding encoding: NSStringEncoding? = nil)
+ encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer
{
return ResponseSerializer { _, response, data, error in
@@ -196,23 +211,25 @@ extension Request {
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
- let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
+ let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
- if let encodingName = response?.textEncodingName where encoding == nil {
- encoding = CFStringConvertEncodingToNSStringEncoding(
+ var convertedEncoding = encoding
+
+ if let encodingName = response?.textEncodingName where convertedEncoding == nil {
+ convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
- let actualEncoding = encoding ?? NSISOLatin1StringEncoding
+ let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
- let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
+ let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
@@ -221,19 +238,21 @@ extension Request {
/**
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,
+ - 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.
*/
public func responseString(
- encoding encoding: NSStringEncoding? = nil,
+ queue queue: dispatch_queue_t? = nil,
+ encoding: NSStringEncoding? = nil,
completionHandler: Response -> Void)
-> Self
{
return response(
+ queue: queue,
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
@@ -245,7 +264,7 @@ extension Request {
extension Request {
/**
- Creates a response serializer that returns a JSON object constructed from the response data using
+ Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
@@ -263,7 +282,7 @@ extension Request {
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
- let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
+ let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
@@ -285,11 +304,13 @@ extension Request {
- returns: The request.
*/
public func responseJSON(
- options options: NSJSONReadingOptions = .AllowFragments,
+ queue queue: dispatch_queue_t? = nil,
+ options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response -> Void)
-> Self
{
return response(
+ queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
@@ -301,7 +322,7 @@ extension Request {
extension Request {
/**
- Creates a response serializer that returns an object constructed from the response data using
+ Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
@@ -319,7 +340,7 @@ extension Request {
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
- let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
+ let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
@@ -337,17 +358,19 @@ extension Request {
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
- arguments: the URL request, the URL response, the server data and the result
+ arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
- options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
+ queue queue: dispatch_queue_t? = nil,
+ options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response -> Void)
-> Self
{
return response(
+ queue: queue,
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Result.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Result.swift
index 4aeeab6..4aabf08 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Result.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Result.swift
@@ -1,33 +1,35 @@
-// Result.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Result.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
+ - 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
+ - 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 {
@@ -73,7 +75,7 @@ public enum Result {
// MARK: - CustomStringConvertible
extension Result: CustomStringConvertible {
- /// The textual representation used when written to an output stream, which includes whether the result was a
+ /// 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 {
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/ServerTrustPolicy.swift b/iOSSwiftStarter/Pods/Alamofire/Source/ServerTrustPolicy.swift
index 5512a5a..c721144 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/ServerTrustPolicy.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/ServerTrustPolicy.swift
@@ -1,24 +1,26 @@
-// ServerTrustPolicy.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// ServerTrustPolicy.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -30,9 +32,9 @@ public class ServerTrustPolicyManager {
/**
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
+ 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.
@@ -78,31 +80,31 @@ extension NSURLSession {
// 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
+ 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
+ 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
+ - 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.
- 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
+ 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
+ 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.
@@ -179,13 +181,21 @@ public enum ServerTrustPolicy {
switch self {
case let .PerformDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
- SecTrustSetPolicies(serverTrust, [policy])
+ #if swift(>=2.3)
+ SecTrustSetPolicies(serverTrust, policy)
+ #else
+ SecTrustSetPolicies(serverTrust, [policy])
+ #endif
serverTrustIsValid = trustIsValid(serverTrust)
case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
+ #if swift(>=2.3)
+ SecTrustSetPolicies(serverTrust, policy)
+ #else
SecTrustSetPolicies(serverTrust, [policy])
+ #endif
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
@@ -209,7 +219,11 @@ public enum ServerTrustPolicy {
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
+ #if swift(>=2.3)
+ SecTrustSetPolicies(serverTrust, policy)
+ #else
SecTrustSetPolicies(serverTrust, [policy])
+ #endif
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
@@ -237,13 +251,23 @@ public enum ServerTrustPolicy {
private func trustIsValid(trust: SecTrust) -> Bool {
var isValid = false
-
+ #if swift(>=2.3)
+ var result = SecTrustResultType(rawValue: SecTrustResultType.Invalid.rawValue)
+ let status = SecTrustEvaluate(trust, &result!)
+ #else
var result = SecTrustResultType(kSecTrustResultInvalid)
let status = SecTrustEvaluate(trust, &result)
+ #endif
if status == errSecSuccess {
+ #if swift(>=2.3)
+ let unspecified = SecTrustResultType(rawValue: SecTrustResultType.Unspecified.rawValue)
+ let proceed = SecTrustResultType(rawValue: SecTrustResultType.Proceed.rawValue)
+ #else
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
let proceed = SecTrustResultType(kSecTrustResultProceed)
+ #endif
+
isValid = result == unspecified || result == proceed
}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Stream.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Stream.swift
index af89d5d..e463d9b 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Stream.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Stream.swift
@@ -1,30 +1,32 @@
-// Stream.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Stream.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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(watchOS)
-@available(iOS 9.0, OSX 10.11, *)
+@available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager {
private enum Streamable {
case Stream(String, Int)
@@ -62,7 +64,7 @@ extension Manager {
- parameter hostName: The hostname of the server to connect to.
- parameter port: The port of the server to connect to.
- :returns: The created stream request.
+ - returns: The created stream request.
*/
public func stream(hostName hostName: String, port: Int) -> Request {
return stream(.Stream(hostName, port))
@@ -82,7 +84,7 @@ extension Manager {
// MARK: -
-@available(iOS 9.0, OSX 10.11, *)
+@available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
// MARK: Override Closures
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Timeline.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Timeline.swift
new file mode 100644
index 0000000..f347705
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Timeline.swift
@@ -0,0 +1,138 @@
+//
+// Timeline.swift
+//
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+import Foundation
+
+/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`.
+public struct Timeline {
+ /// The time the request was initialized.
+ public let requestStartTime: CFAbsoluteTime
+
+ /// The time the first bytes were received from or sent to the server.
+ public let initialResponseTime: CFAbsoluteTime
+
+ /// The time when the request was completed.
+ public let requestCompletedTime: CFAbsoluteTime
+
+ /// The time when the response serialization was completed.
+ public let serializationCompletedTime: CFAbsoluteTime
+
+ /// The time interval in seconds from the time the request started to the initial response from the server.
+ public let latency: NSTimeInterval
+
+ /// The time interval in seconds from the time the request started to the time the request completed.
+ public let requestDuration: NSTimeInterval
+
+ /// The time interval in seconds from the time the request completed to the time response serialization completed.
+ public let serializationDuration: NSTimeInterval
+
+ /// The time interval in seconds from the time the request started to the time response serialization completed.
+ public let totalDuration: NSTimeInterval
+
+ /**
+ 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.joinWithSeparator(", ") + " }"
+ }
+}
+
+// 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.joinWithSeparator(", ") + " }"
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Upload.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Upload.swift
index f7cc8bc..33703f0 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Upload.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Upload.swift
@@ -1,24 +1,26 @@
-// Upload.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Upload.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -192,12 +194,12 @@ extension Manager {
public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024
/**
- Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
+ 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 `Request` along with
+ - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with
streaming information.
- - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
+ - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
error.
*/
public enum MultipartFormDataEncodingResult {
@@ -208,17 +210,17 @@ extension Manager {
/**
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
- 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
+ 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
+ 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
+ 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.
@@ -308,14 +310,20 @@ extension Manager {
} else {
let fileManager = NSFileManager.defaultManager()
let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
- let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data")
let fileName = NSUUID().UUIDString
+ #if swift(>=2.3)
+ let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data")!
+ let fileURL = directoryURL.URLByAppendingPathComponent(fileName)!
+ #else
+ let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data")
let fileURL = directoryURL.URLByAppendingPathComponent(fileName)
+ #endif
do {
try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil)
try formData.writeEncodedDataToDisk(fileURL)
+
dispatch_async(dispatch_get_main_queue()) {
let encodingResult = MultipartFormDataEncodingResult.Success(
request: self.upload(URLRequestWithContentType, file: fileURL),
@@ -359,6 +367,8 @@ extension Request {
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
+ if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
+
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
diff --git a/iOSSwiftStarter/Pods/Alamofire/Source/Validation.swift b/iOSSwiftStarter/Pods/Alamofire/Source/Validation.swift
index 6763917..b94e07d 100644
--- a/iOSSwiftStarter/Pods/Alamofire/Source/Validation.swift
+++ b/iOSSwiftStarter/Pods/Alamofire/Source/Validation.swift
@@ -1,24 +1,26 @@
-// Validation.swift
//
-// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+// Validation.swift
//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
+// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION 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
@@ -36,7 +38,7 @@ extension Request {
}
/**
- A closure used to validate a request that takes a URL request and URL response, and returns whether the
+ A closure used to validate a request that takes a URL request and URL response, and returns whether the
request was valid.
*/
public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
@@ -80,7 +82,17 @@ extension Request {
return .Success
} else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
- return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
+
+ let error = NSError(
+ domain: Error.Domain,
+ code: Error.Code.StatusCodeValidationFailed.rawValue,
+ userInfo: [
+ NSLocalizedFailureReasonErrorKey: failureReason,
+ Error.UserInfoKeys.StatusCode: response.statusCode
+ ]
+ )
+
+ return .Failure(error)
}
}
}
@@ -128,7 +140,7 @@ extension Request {
- returns: The request.
*/
- public func validate(contentType acceptableContentTypes: S) -> Self {
+ public func validate(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
@@ -149,25 +161,38 @@ extension Request {
}
}
+ let contentType: String
let failureReason: String
if let responseContentType = response.MIMEType {
+ contentType = responseContentType
+
failureReason = (
"Response content type \"\(responseContentType)\" does not match any acceptable " +
"content types: \(acceptableContentTypes)"
)
} else {
+ contentType = ""
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
}
- return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
+ let error = NSError(
+ domain: Error.Domain,
+ code: Error.Code.ContentTypeValidationFailed.rawValue,
+ userInfo: [
+ NSLocalizedFailureReasonErrorKey: failureReason,
+ Error.UserInfoKeys.ContentType: contentType
+ ]
+ )
+
+ return .Failure(error)
}
}
// MARK: - Automatic
/**
- Validates that the response has a status code in the default acceptable range of 200...299, and that the content
+ 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.
diff --git a/iOSSwiftStarter/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift b/iOSSwiftStarter/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift
index 84176c3..f37eb0f 100644
--- a/iOSSwiftStarter/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift
+++ b/iOSSwiftStarter/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift
@@ -32,7 +32,16 @@ import ObjectMapper
extension Request {
- public static func ObjectMapperSerializer(keyPath: String?) -> ResponseSerializer {
+ internal static func newError(code: Error.Code, failureReason: String) -> NSError {
+ let errorDomain = "com.alamofireobjectmapper.error"
+
+ let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
+ let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo)
+
+ return returnError
+ }
+
+ public static func ObjectMapperSerializer(keyPath: String?, mapToObject object: T? = nil, context: MapContext? = nil) -> ResponseSerializer {
return ResponseSerializer { request, response, data, error in
guard error == nil else {
return .Failure(error!)
@@ -40,7 +49,7 @@ extension Request {
guard let _ = data else {
let failureReason = "Data could not be serialized. Input data was nil."
- let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
+ let error = newError(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
@@ -54,65 +63,35 @@ extension Request {
JSONToMap = result.value
}
- if let parsedObject = Mapper().map(JSONToMap){
+ if let object = object {
+ Mapper().map(JSONToMap, toObject: object)
+ return .Success(object)
+ } else if let parsedObject = Mapper(context: context).map(JSONToMap){
return .Success(parsedObject)
}
let failureReason = "ObjectMapper failed to serialize response."
- let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
+ let error = newError(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
-
- /**
- Adds a handler to be called once the request has finished.
-
- - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
-
- - returns: The request.
- */
- public func responseObject(completionHandler: Response -> Void) -> Self {
- return responseObject(nil, keyPath: nil, completionHandler: completionHandler)
- }
-
- /**
- Adds a handler to be called once the request has finished.
-
- - parameter keyPath: The key path where object mapping should be performed
- - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
-
- - returns: The request.
- */
- public func responseObject(keyPath: String, completionHandler: Response -> Void) -> Self {
- return responseObject(nil, keyPath: keyPath, completionHandler: completionHandler)
- }
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
+ - parameter keyPath: The key path where object mapping should be performed
+ - parameter object: An object to perform the mapping on to
- parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
- returns: The request.
*/
- public func responseObject(queue: dispatch_queue_t?, completionHandler: Response -> Void) -> Self {
- return responseObject(queue, keyPath: nil, completionHandler: completionHandler)
- }
- /**
- Adds a handler to be called once the request has finished.
-
- - parameter queue: The queue on which the completion handler is dispatched.
- - parameter keyPath: The key path where object mapping should be performed
- - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
-
- - returns: The request.
- */
- public func responseObject(queue: dispatch_queue_t?, keyPath: String?, completionHandler: Response -> Void) -> Self {
- return response(queue: queue, responseSerializer: Request.ObjectMapperSerializer(keyPath), completionHandler: completionHandler)
+ public func responseObject(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, mapToObject object: T? = nil, context: MapContext? = nil, completionHandler: Response -> Void) -> Self {
+ return response(queue: queue, responseSerializer: Request.ObjectMapperSerializer(keyPath, mapToObject: object, context: context), completionHandler: completionHandler)
}
- public static func ObjectMapperArraySerializer(keyPath: String?) -> ResponseSerializer<[T], NSError> {
+ public static func ObjectMapperArraySerializer(keyPath: String?, context: MapContext? = nil) -> ResponseSerializer<[T], NSError> {
return ResponseSerializer { request, response, data, error in
guard error == nil else {
return .Failure(error!)
@@ -120,7 +99,7 @@ extension Request {
guard let _ = data else {
let failureReason = "Data could not be serialized. Input data was nil."
- let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
+ let error = newError(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
@@ -134,51 +113,16 @@ extension Request {
JSONToMap = result.value
}
- if let parsedObject = Mapper().mapArray(JSONToMap){
+ if let parsedObject = Mapper(context: context).mapArray(JSONToMap){
return .Success(parsedObject)
}
let failureReason = "ObjectMapper failed to serialize response."
- let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
+ let error = newError(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
- /**
- Adds a handler to be called once the request has finished.
-
- - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
-
- - returns: The request.
- */
- public func responseArray(completionHandler: Response<[T], NSError> -> Void) -> Self {
- return responseArray(nil, keyPath: nil, completionHandler: completionHandler)
- }
-
- /**
- Adds a handler to be called once the request has finished.
-
- - parameter keyPath: The key path where object mapping should be performed
- - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
-
- - returns: The request.
- */
- public func responseArray(keyPath: String, completionHandler: Response<[T], NSError> -> Void) -> Self {
- return responseArray(nil, keyPath: keyPath, completionHandler: completionHandler)
- }
-
- /**
- Adds a handler to be called once the request has finished.
-
- - parameter queue: The queue on which the completion handler is dispatched.
- - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
-
- - returns: The request.
- */
- public func responseArray(queue: dispatch_queue_t?, completionHandler: Response<[T], NSError> -> Void) -> Self {
- return responseArray(queue, keyPath: nil, completionHandler: completionHandler)
- }
-
/**
Adds a handler to be called once the request has finished.
@@ -188,7 +132,7 @@ extension Request {
- returns: The request.
*/
- public func responseArray(queue: dispatch_queue_t?, keyPath: String?, completionHandler: Response<[T], NSError> -> Void) -> Self {
- return response(queue: queue, responseSerializer: Request.ObjectMapperArraySerializer(keyPath), completionHandler: completionHandler)
+ public func responseArray(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: Response<[T], NSError> -> Void) -> Self {
+ return response(queue: queue, responseSerializer: Request.ObjectMapperArraySerializer(keyPath, context: context), completionHandler: completionHandler)
}
}
diff --git a/iOSSwiftStarter/Pods/AlamofireObjectMapper/README.md b/iOSSwiftStarter/Pods/AlamofireObjectMapper/README.md
index b3b051f..ecceb80 100644
--- a/iOSSwiftStarter/Pods/AlamofireObjectMapper/README.md
+++ b/iOSSwiftStarter/Pods/AlamofireObjectMapper/README.md
@@ -33,10 +33,10 @@ Given a URL which returns weather data in the following form:
}
```
-You can use this extension as the follows:
+You can use the extension as the follows:
```swift
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
-Alamofire.request(.GET, URL).responseObject("data") { (response: Response) in
+Alamofire.request(.GET, URL).responseObject { (response: Response) in
let weatherResponse = response.result.value
print(weatherResponse?.location)
@@ -84,43 +84,42 @@ class Forecast: Mappable {
}
```
-The extension uses Generics to allow you to create your own custom response objects. Below are four functions which you can use to have your responses mapped to objects. Just replace `T` with your custom response object and the extension handles the rest:
+The extension uses Generics to allow you to create your own custom response objects. Below is the `responseObject` function definition. Just replace `T` in the completionHandler with your custom response object and the extension handles the rest:
```swift
-public func responseObject(completionHandler: Response -> Void) -> Self
-```
-
-```swift
-public func responseObject(keyPath: String, completionHandler: Response -> Void) -> Self
-```
-
-```swift
-public func responseObject(queue: dispatch_queue_t?, completionHandler: Response -> Void) -> Self
-```
-
-```swift
-public func responseObject(queue: dispatch_queue_t?, keyPath: String?, completionHandler: Response -> Void) -> Self
+public func responseObject(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, mapToObject object: T? = nil, completionHandler: Response -> Void) -> Self
```
+The `responseObject` function has 3 optional parameters and a required completionHandler:
+- `queue`: The queue on which the completion handler is dispatched.
+- `keyPath`: The key path of the JSON where object mapping should be performed
+- `mapToObject`: An object to perform the mapping on to
+- `completionHandler`: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
###KeyPath
-The `keyPath` variable in the functions above is used to drill down in a JSON response and only map the data at that `keyPath`. It also supports nested values such as `data.weather` to drill down several levels in a JSON response.
-
-#Array Responses
-If you have an endpoint that returns data in `Array` form you can map it with the following functions:
-```swift
-public func responseArray(completionHandler: Response<[T], NSError> -> Void) -> Self
-```
-
-```swift
-public func responseArray(keyPath: String, completionHandler: Response<[T], NSError> -> Void) -> Self
+The `keyPath` variable is used to drill down into a JSON response and only map the data found at that `keyPath`. It supports nested values such as `data.weather` to drill down several levels in a JSON response.
```
+let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"
+let expectation = expectationWithDescription("\(URL)")
-```swift
-public func responseArray(queue: dispatch_queue_t?, completionHandler: Response<[T], NSError> -> Void) -> Self
+Alamofire.request(.GET, URL).responseObject(keyPath: "data") { (response: Response) in
+ expectation.fulfill()
+
+ let weatherResponse = response.result.value
+ print(weatherResponse?.location)
+
+ if let threeDayForecast = weatherResponse?.threeDayForecast {
+ for forecast in threeDayForecast {
+ print(forecast.day)
+ print(forecast.temperature)
+ }
+ }
+}
```
+#Array Responses
+If you have an endpoint that returns data in `Array` form you can map it with the following function:
```swift
-public func responseArray(queue: dispatch_queue_t?, keyPath: String?, completionHandler: Response<[T], NSError> -> Void) -> Self
+public func responseArray(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, completionHandler: Response<[T], NSError> -> Void) -> Self
```
For example, if your endpoint returns the following:
@@ -161,12 +160,12 @@ Alamofire.request(.GET, URL).responseArray { (response: Response<[Forecast], NSE
```
#Installation
-AlamofireObjectMapper can be added to your project using [Cocoapods](https://cocoapods.org/) by adding the following line to your Podfile:
+AlamofireObjectMapper can be added to your project using [CocoaPods](https://cocoapods.org/) by adding the following line to your Podfile:
```
-pod 'AlamofireObjectMapper', '~> 2.0'
+pod 'AlamofireObjectMapper', '~> 3.0'
```
If your using [Carthage](https://github.com/Carthage/Carthage) you can add a dependency on AlamofireObjectMapper by adding it to your Cartfile:
```
-github "tristanhimmelman/AlamofireObjectMapper" ~> 2.0
+github "tristanhimmelman/AlamofireObjectMapper" ~> 3.0
```
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptions.swift b/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptions.swift
deleted file mode 100644
index 23215b0..0000000
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptions.swift
+++ /dev/null
@@ -1,60 +0,0 @@
-//
-// KingfisherOptions.swift
-// Kingfisher
-//
-// Created by Wei Wang on 15/4/6.
-//
-// Copyright (c) 2015 Wei Wang
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-import Foundation
-
-/**
-* Options to control Kingfisher behaviors.
-*/
-public struct KingfisherOptions: OptionSetType {
-
- public let rawValue: UInt
-
- public init(rawValue: UInt) {
- self.rawValue = rawValue
- }
-
- /// None options. Kingfisher will keep its default behavior.
- public static let None = KingfisherOptions(rawValue: 0)
-
- /// Download in a low priority.
- public static let LowPriority = KingfisherOptions(rawValue: 1 << 0)
-
- /// Try to send request to server first. If response code is 304 (Not Modified), use the cached image. Otherwise, download the image and cache it again.
- public static var ForceRefresh = KingfisherOptions(rawValue: 1 << 1)
-
- /// Only cache downloaded image to memory, not cache in disk.
- public static var CacheMemoryOnly = KingfisherOptions(rawValue: 1 << 2)
-
- /// Decode the image in background thread before using.
- public static var BackgroundDecode = KingfisherOptions(rawValue: 1 << 3)
-
- /// If set it will dispatch callbacks asynchronously to the global queue DISPATCH_QUEUE_PRIORITY_DEFAULT. Otherwise it will use the queue defined at KingfisherManager.DefaultOptions.queue
- public static var BackgroundCallback = KingfisherOptions(rawValue: 1 << 4)
-
- /// Decode the image using the same scale as the main screen. Otherwise it will use the same scale as defined on the KingfisherManager.DefaultOptions.scale.
- public static var ScreenScale = KingfisherOptions(rawValue: 1 << 5)
-}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptionsInfo.swift b/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptionsInfo.swift
deleted file mode 100644
index ea6e0c1..0000000
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherOptionsInfo.swift
+++ /dev/null
@@ -1,70 +0,0 @@
-//
-// KingfisherOptionsInfo.swift
-// Kingfisher
-//
-// Created by Wei Wang on 15/4/23.
-//
-// Copyright (c) 2015 Wei Wang
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-import Foundation
-
-/**
-* KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher.
-*/
-public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
-
-/**
-Item could be added into KingfisherOptionsInfo
-
-- Options: Item for options. The value of this item should be a KingfisherOptions.
-- TargetCache: Item for target cache. The value of this item should be an ImageCache object. Kingfisher will use this cache when handling the related operation, including trying to retrieve the cached images and store the downloaded image to it.
-- Downloader: Item for downloader to use. The value of this item should be an ImageDownloader object. Kingfisher will use this downloader to download the images.
-- Transition: Item for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of this enum to animate the image in if it is downloaded from web. The transition will not happen when the image is retrieved from either memory or disk cache.
-*/
-public enum KingfisherOptionsInfoItem {
- case Options(KingfisherOptions)
- case TargetCache(ImageCache)
- case Downloader(ImageDownloader)
- case Transition(ImageTransition)
-}
-
-infix operator <== {
- associativity none
- precedence 160
-}
-
-// This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values.
-func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool {
- switch (lhs, rhs) {
- case (.Options(_), .Options(_)): return true
- case (.TargetCache(_), .TargetCache(_)): return true
- case (.Downloader(_), .Downloader(_)): return true
- case (.Transition(_), .Transition(_)): return true
- default: return false
- }
-}
-
-extension CollectionType where Generator.Element == KingfisherOptionsInfoItem {
-
- func kf_firstMatchIgnoringAssociatedValue(target: Generator.Element) -> Generator.Element? {
- return indexOf { $0 <== target }.flatMap { self[$0] }
- }
-}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift b/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift
deleted file mode 100644
index 219f1ba..0000000
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift
+++ /dev/null
@@ -1,592 +0,0 @@
-//
-// UIButton+Kingfisher.swift
-// Kingfisher
-//
-// Created by Wei Wang on 15/4/13.
-//
-// Copyright (c) 2015 Wei Wang
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-import UIKit
-
-/**
-* Set image to use from web for a specified state.
-*/
-public extension UIButton {
-
- /**
- Set an image to use for a specified state with a resource.
- It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
- The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- forState state: UIControlState) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image to use for a specified state with a URL.
- It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
- The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
-
- If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image to use for a specified state with a resource and a placeholder image.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image to use for a specified state with a URL and a placeholder image.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image to use for a specified state with a resource, a placeholder image and options.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image to use for a specified state with a URL, a placeholder image and options.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image to use for a specified state with a resource, a placeholder image, options and completion handler.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
- }
-
- /**
- Set an image to use for a specified state with a URL, a placeholder image, options and completion handler.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
- }
-
-
- /**
- Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter progressBlock: Called when the image downloading progress gets updated.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- setImage(placeholderImage, forState: state)
- kf_setWebURL(resource.downloadURL, forState: state)
- let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
- progressBlock: { receivedSize, totalSize in
- if let progressBlock = progressBlock {
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
- progressBlock(receivedSize: receivedSize, totalSize: totalSize)
- })
- }
- },
- completionHandler: {[weak self] image, error, cacheType, imageURL in
-
- dispatch_async_safely_main_queue {
- if let sSelf = self {
- if imageURL == sSelf.kf_webURLForState(state) && image != nil {
- sSelf.setImage(image, forState: state)
- }
- completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
- }
- }
- }
- )
- return task
- }
-
- /**
- Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter progressBlock: Called when the image downloading progress gets updated.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(Resource(downloadURL: URL),
- forState: state,
- placeholderImage: placeholderImage,
- optionsInfo: optionsInfo,
- progressBlock: progressBlock,
- completionHandler: completionHandler)
- }
-}
-
-private var lastURLKey: Void?
-public extension UIButton {
- /**
- Get the image URL binded to this button for a specified state.
-
- - parameter state: The state that uses the specified image.
-
- - returns: Current URL for image.
- */
- public func kf_webURLForState(state: UIControlState) -> NSURL? {
- return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
- }
-
- private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
- kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
- }
-
- private var kf_webURLs: NSMutableDictionary {
- var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
- if dictionary == nil {
- dictionary = NSMutableDictionary()
- kf_setWebURLs(dictionary!)
- }
- return dictionary!
- }
-
- private func kf_setWebURLs(URLs: NSMutableDictionary) {
- objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
- }
-}
-
-/**
-* Set background image to use from web for a specified state.
-*/
-public extension UIButton {
- /**
- Set the background image to use for a specified state with a resource.
- It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
- The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithResource(resource: Resource,
- forState state: UIControlState) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set the background image to use for a specified state with a URL.
- It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
- The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
-
- If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set the background image to use for a specified state with a resource and a placeholder image.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set the background image to use for a specified state with a URL and a placeholder image.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set the background image to use for a specified state with a resource, a placeholder image and options.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set the background image to use for a specified state with a URL, a placeholder image and options.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
- }
-
- /**
- Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
- }
-
- /**
- Set the background image to use for a specified state with a resource,
- a placeholder image, options progress handler and completion handler.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter progressBlock: Called when the image downloading progress gets updated.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithResource(resource: Resource,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- setBackgroundImage(placeholderImage, forState: state)
- kf_setBackgroundWebURL(resource.downloadURL, forState: state)
- let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
- progressBlock: { receivedSize, totalSize in
- if let progressBlock = progressBlock {
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
- progressBlock(receivedSize: receivedSize, totalSize: totalSize)
- })
- }
- },
- completionHandler: { [weak self] image, error, cacheType, imageURL in
- dispatch_async_safely_main_queue {
- if let sSelf = self {
- if imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil {
- sSelf.setBackgroundImage(image, forState: state)
- }
- completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
- }
- }
- }
- )
- return task
- }
-
- /**
- Set the background image to use for a specified state with a URL,
- a placeholder image, options progress handler and completion handler.
-
- - parameter URL: The URL of image for specified state.
- - parameter state: The state that uses the specified image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter progressBlock: Called when the image downloading progress gets updated.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithResource(Resource(downloadURL: URL),
- forState: state,
- placeholderImage: placeholderImage,
- optionsInfo: optionsInfo,
- progressBlock: progressBlock,
- completionHandler: completionHandler)
- }
-}
-
-private var lastBackgroundURLKey: Void?
-public extension UIButton {
- /**
- Get the background image URL binded to this button for a specified state.
-
- - parameter state: The state that uses the specified background image.
-
- - returns: Current URL for background image.
- */
- public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
- return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
- }
-
- private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
- kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
- }
-
- private var kf_backgroundWebURLs: NSMutableDictionary {
- var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
- if dictionary == nil {
- dictionary = NSMutableDictionary()
- kf_setBackgroundWebURLs(dictionary!)
- }
- return dictionary!
- }
-
- private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
- objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
- }
-}
-
-// MARK: - Deprecated
-public extension UIButton {
- @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo: instead.")
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- options: KingfisherOptions) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil)
- }
-
- @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- options: KingfisherOptions,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler)
- }
-
- @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
- public func kf_setImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- options: KingfisherOptions,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler)
- }
-
- @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo: instead.")
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- options: KingfisherOptions) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil)
- }
-
- @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- options: KingfisherOptions,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler)
- }
-
-
- @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
- public func kf_setBackgroundImageWithURL(URL: NSURL,
- forState state: UIControlState,
- placeholderImage: UIImage?,
- options: KingfisherOptions,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler)
- }
-}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImage+Extension.swift b/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImage+Extension.swift
deleted file mode 100644
index 096fa31..0000000
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImage+Extension.swift
+++ /dev/null
@@ -1,195 +0,0 @@
-//
-// UIImage+Decode.swift
-// Kingfisher
-//
-// Created by Wei Wang on 15/4/7.
-//
-// Copyright (c) 2015 Wei Wang
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-import UIKit
-import ImageIO
-import MobileCoreServices
-
-private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
-private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
-private let jpgHeaderIF: [UInt8] = [0xFF]
-private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
-
-// MARK: - Image format
-enum ImageFormat {
- case Unknown, PNG, JPEG, GIF
-}
-
-extension NSData {
- var kf_imageFormat: ImageFormat {
- var buffer = [UInt8](count: 8, repeatedValue: 0)
- self.getBytes(&buffer, length: 8)
- if buffer == pngHeader {
- return .PNG
- } else if buffer[0] == jpgHeaderSOI[0] &&
- buffer[1] == jpgHeaderSOI[1] &&
- buffer[2] == jpgHeaderIF[0]
- {
- return .JPEG
- } else if buffer[0] == gifHeader[0] &&
- buffer[1] == gifHeader[1] &&
- buffer[2] == gifHeader[2]
- {
- return .GIF
- }
-
- return .Unknown
- }
-}
-
-// MARK: - Decode
-extension UIImage {
- func kf_decodedImage() -> UIImage? {
- return self.kf_decodedImage(scale: self.scale)
- }
-
- func kf_decodedImage(scale scale: CGFloat) -> UIImage? {
- // prevent animated image (GIF) lose it's images
- if images != nil {
- return self
- }
-
- let imageRef = self.CGImage
- let colorSpace = CGColorSpaceCreateDeviceRGB()
- let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
- let contextHolder = UnsafeMutablePointer()
- let context = CGBitmapContextCreate(contextHolder, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
- if let context = context {
- let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
- CGContextDrawImage(context, rect, imageRef)
- let decompressedImageRef = CGBitmapContextCreateImage(context)
- return UIImage(CGImage: decompressedImageRef!, scale: scale, orientation: self.imageOrientation)
- } else {
- return nil
- }
- }
-}
-
-// MARK: - Normalization
-extension UIImage {
- public func kf_normalizedImage() -> UIImage {
- // prevent animated image (GIF) lose it's images
- if images != nil {
- return self
- }
-
- if imageOrientation == .Up {
- return self
- }
-
- UIGraphicsBeginImageContextWithOptions(size, false, scale)
- drawInRect(CGRect(origin: CGPointZero, size: size))
- let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
- UIGraphicsEndImageContext()
-
- return normalizedImage
- }
-}
-
-// MARK: - Create images from data
-extension UIImage {
- static func kf_imageWithData(data: NSData, scale: CGFloat) -> UIImage? {
- var image: UIImage?
- switch data.kf_imageFormat {
- case .JPEG: image = UIImage(data: data, scale: scale)
- case .PNG: image = UIImage(data: data, scale: scale)
- case .GIF: image = UIImage.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
- case .Unknown: image = nil
- }
- return image
- }
-}
-
-// MARK: - GIF
-func UIImageGIFRepresentation(image: UIImage) -> NSData? {
- return UIImageGIFRepresentation(image, duration: 0.0, repeatCount: 0)
-}
-
-func UIImageGIFRepresentation(image: UIImage, duration: NSTimeInterval, repeatCount: Int) -> NSData? {
- guard let images = image.images else {
- return nil
- }
-
- let frameCount = images.count
- let gifDuration = duration <= 0.0 ? image.duration / Double(frameCount) : duration / Double(frameCount)
-
- let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
- let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
-
- let data = NSMutableData()
-
- guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
- return nil
- }
- CGImageDestinationSetProperties(destination, imageProperties)
-
- for image in images {
- CGImageDestinationAddImage(destination, image.CGImage!, frameProperties)
- }
-
- return CGImageDestinationFinalize(destination) ? NSData(data: data) : nil
-}
-
-extension UIImage {
- static func kf_animatedImageWithGIFData(gifData data: NSData) -> UIImage? {
- return kf_animatedImageWithGIFData(gifData: data, scale: UIScreen.mainScreen().scale, duration: 0.0)
- }
-
- static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval) -> UIImage? {
-
- let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
- guard let imageSource = CGImageSourceCreateWithData(data, options) else {
- return nil
- }
-
- let frameCount = CGImageSourceGetCount(imageSource)
- var images = [UIImage]()
-
- var gifDuration = 0.0
-
- for i in 0 ..< frameCount {
- guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
- return nil
- }
-
- guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
- gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
- frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else
- {
- return nil
- }
-
- gifDuration += frameDuration.doubleValue
- images.append(UIImage(CGImage: imageRef, scale: scale, orientation: .Up))
- }
-
- if frameCount == 1 {
- return images.first
- } else {
- return UIImage.animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
- }
- }
-}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImageView+Kingfisher.swift b/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImageView+Kingfisher.swift
deleted file mode 100644
index eb84b24..0000000
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/UIImageView+Kingfisher.swift
+++ /dev/null
@@ -1,391 +0,0 @@
-//
-// UIImageView+Kingfisher.swift
-// Kingfisher
-//
-// Created by Wei Wang on 15/4/6.
-//
-// Copyright (c) 2015 Wei Wang
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-import UIKit
-
-// MARK: - Set Images
-/**
-* Set image to use from web.
-*/
-
-public extension UIImageView {
-
- /**
- Set an image with a resource.
- It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource`.
- The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image with a URL.
- It will ask for Kingfisher's manager to get the image for the URL.
- The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
-
- If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
-
- - parameter URL: The URL of image.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image with a resource and a placeholder image.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- placeholderImage: UIImage?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image with a URL and a placeholder image.
-
- - parameter URL: The URL of image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- placeholderImage: UIImage?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image with a resource, a placaholder image and options.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image with a URL, a placaholder image and options.
-
- - parameter URL: The URL of image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
- }
-
- /**
- Set an image with a resource, a placeholder image, options and completion handler.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
- }
-
- /**
- Set an image with a URL, a placeholder image, options and completion handler.
-
- - parameter URL: The URL of image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithURL(URL: NSURL,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
- }
-
- /**
- Set an image with a URL, a placeholder image, options, progress handler and completion handler.
-
- - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter progressBlock: Called when the image downloading progress gets updated.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
- public func kf_setImageWithResource(resource: Resource,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- let showIndicatorWhenLoading = kf_showIndicatorWhenLoading
- var indicator: UIActivityIndicatorView? = nil
- if showIndicatorWhenLoading {
- indicator = kf_indicator
- indicator?.hidden = false
- indicator?.startAnimating()
- }
-
- image = placeholderImage
-
- kf_setWebURL(resource.downloadURL)
-
- let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
- progressBlock: { receivedSize, totalSize in
- if let progressBlock = progressBlock {
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
- progressBlock(receivedSize: receivedSize, totalSize: totalSize)
-
- })
- }
- },
- completionHandler: {[weak self] image, error, cacheType, imageURL in
-
- dispatch_async_safely_main_queue {
-
- guard let sSelf = self where imageURL == sSelf.kf_webURL else {
- completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
- return
- }
-
- sSelf.kf_setImageTask(nil)
-
- guard let image = image else {
- completionHandler?(image: nil, error: error, cacheType: cacheType, imageURL: imageURL)
- return
- }
-
- if let transitionItem = optionsInfo?.kf_firstMatchIgnoringAssociatedValue(.Transition(.None)),
- case .Transition(let transition) = transitionItem where cacheType == .None {
-
- UIView.transitionWithView(sSelf, duration: 0.0, options: [],
- animations: {
- indicator?.stopAnimating()
- },
- completion: { finished in
- UIView.transitionWithView(sSelf, duration: transition.duration,
- options: transition.animationOptions,
- animations: {
- transition.animations?(sSelf, image)
- },
- completion: { finished in
- transition.completion?(finished)
- completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
- }
- )
- }
- )
- } else {
- indicator?.stopAnimating()
- sSelf.image = image
- completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
- }
- }
- }
- )
-
- kf_setImageTask(task)
-
- return task
- }
-
- /**
- Set an image with a URL, a placeholder image, options, progress handler and completion handler.
-
- - parameter URL: The URL of image.
- - parameter placeholderImage: A placeholder image when retrieving the image at URL.
- - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- - parameter progressBlock: Called when the image downloading progress gets updated.
- - parameter completionHandler: Called when the image retrieved and set.
-
- - returns: A task represents the retrieving process.
- */
-
- public func kf_setImageWithURL(URL: NSURL,
- placeholderImage: UIImage?,
- optionsInfo: KingfisherOptionsInfo?,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithResource(Resource(downloadURL: URL),
- placeholderImage: placeholderImage,
- optionsInfo: optionsInfo,
- progressBlock: progressBlock,
- completionHandler: completionHandler)
- }
-}
-
-extension UIImageView {
- /**
- Cancel the image download task bounded to the image view if it is running.
- Nothing will happen if the downloading has already finished.
- */
- public func kf_cancelDownloadTask() {
- kf_imageTask?.downloadTask?.cancel()
- }
-}
-
-// MARK: - Associated Object
-private var lastURLKey: Void?
-private var indicatorKey: Void?
-private var showIndicatorWhenLoadingKey: Void?
-private var imageTaskKey: Void?
-
-public extension UIImageView {
- /// Get the image URL binded to this image view.
- public var kf_webURL: NSURL? {
- return objc_getAssociatedObject(self, &lastURLKey) as? NSURL
- }
-
- private func kf_setWebURL(URL: NSURL) {
- objc_setAssociatedObject(self, &lastURLKey, URL, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
- }
-
- /// Whether show an animating indicator when the image view is loading an image or not.
- /// Default is false.
- public var kf_showIndicatorWhenLoading: Bool {
- get {
- if let result = objc_getAssociatedObject(self, &showIndicatorWhenLoadingKey) as? NSNumber {
- return result.boolValue
- } else {
- return false
- }
- }
-
- set {
- if kf_showIndicatorWhenLoading == newValue {
- return
- } else {
- if newValue {
- #if os(tvOS)
- let indicatorStyle = UIActivityIndicatorViewStyle.White
- #else
- let indicatorStyle = UIActivityIndicatorViewStyle.Gray
- #endif
- let indicator = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle)
- indicator.center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMidY(bounds))
-
- indicator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin, .FlexibleTopMargin]
- indicator.hidden = true
- indicator.hidesWhenStopped = true
-
- self.addSubview(indicator)
-
- kf_setIndicator(indicator)
- } else {
- kf_indicator?.removeFromSuperview()
- kf_setIndicator(nil)
- }
-
- objc_setAssociatedObject(self, &showIndicatorWhenLoadingKey, NSNumber(bool: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
- }
- }
- }
-
- /// The indicator view showing when loading. This will be `nil` if `kf_showIndicatorWhenLoading` is false.
- /// You may want to use this to set the indicator style or color when you set `kf_showIndicatorWhenLoading` to true.
- public var kf_indicator: UIActivityIndicatorView? {
- return objc_getAssociatedObject(self, &indicatorKey) as? UIActivityIndicatorView
- }
-
- private func kf_setIndicator(indicator: UIActivityIndicatorView?) {
- objc_setAssociatedObject(self, &indicatorKey, indicator, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
- }
-
- private var kf_imageTask: RetrieveImageTask? {
- return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask
- }
-
- private func kf_setImageTask(task: RetrieveImageTask?) {
- objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
- }
-}
-
-// MARK: - Deprecated
-public extension UIImageView {
- @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.")
- public func kf_setImageWithURL(URL: NSURL,
- placeholderImage: UIImage?,
- options: KingfisherOptions) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil)
- }
-
- @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.")
- public func kf_setImageWithURL(URL: NSURL,
- placeholderImage: UIImage?,
- options: KingfisherOptions,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler)
- }
-
- @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
- public func kf_setImageWithURL(URL: NSURL,
- placeholderImage: UIImage?,
- options: KingfisherOptions,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler)
- }
-
-}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/README.md b/iOSSwiftStarter/Pods/Kingfisher/README.md
index da31312..23c3a53 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/README.md
+++ b/iOSSwiftStarter/Pods/Kingfisher/README.md
@@ -10,14 +10,19 @@
+
+
+
+
+
Kingfisher is a lightweight and pure Swift implemented library for downloading and caching image from the web. This project is heavily inspired by the popular [SDWebImage](https://github.com/rs/SDWebImage). And it provides you a chance to use pure Swift alternative in your next app.
@@ -29,23 +34,31 @@ Kingfisher is a lightweight and pure Swift implemented library for downloading a
* Cache management. You can set the max duration or size the cache takes. From this, the cache will be cleaned automatically to prevent taking too many resources.
* Modern framework. Kingfisher uses `NSURLSession` and the latest technology of GCD, which makes it a strong and swift framework. It also provides you easy APIs to use.
* Cancelable processing task. You can cancel the downloading process if it is not needed anymore.
+* Prefetching. You can prefetch and cache the images which might soon appear in the page. It will bring your users great experience.
* Independent components. You can use the downloader or caching system separately. Or even create your own cache based on Kingfisher's code.
* Options to decompress the image in background before rendering it, which could improve the UI performance.
-* Categories over `UIImageView` and `UIButton` for setting image from an URL directly.
-* Support GIF seamlessly. You could just download and set your GIF images as the same as you do for PNG/JPEG format.
+* Categories over `UIImageView`, `NSImage` and `UIButton` for setting image from a URL directly. Use the same code across all Apple platforms.
+* Support GIF seamlessly. You could just download and set your GIF images as the same as you do for PNG/JPEG format using `AnimatedImageView`.
+* You could set `Activity Indicator` for your UIImageView or NSImageView to enable the indicator during loading image from web.
## Requirements
-* iOS 8.0+ or tvOS 9.0+
-* Xcode 7.0 or above
+* iOS 8.0+, tvOS 9.0+, watchOS 2.0+ or OS X 10.10+
+* Xcode 7.3 or above
+
+If you are upgrading to Kingfisher 2.x from 1.x, please read the [Kingfisher 2.0 Migration Guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-2.0-Migration-Guide) for more information.
+
+Kingfisher is now supporting Swift 2.2. If you need to use Kingfisher in Swift 2.1, you need to pin the version to 2.1.0.
+
+### Swift 3
+
+Kingfisher is now supporting Swift 3 in the [swift3](https://github.com/onevcat/Kingfisher/tree/swift3) branch. It is now under development and not be officially released yet. You could specify to that branch if you are working in a Swift 3 project. However, please reconsider if you want to use it in a releasing orientation product, since more breaking change would be applied later.
## Installation
### CocoaPods
-[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects.
-
-CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:
+[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:
``` bash
$ gem install cocoapods
@@ -58,9 +71,19 @@ source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
-pod 'Kingfisher', '~> 1.9'
+pod 'Kingfisher', '~> 2.4'
```
+If your CocoaPods Version > 1.0.0, you needs add Target name like this:
+```ruby
+source 'https://github.com/CocoaPods/Specs.git'
+platform :ios, '8.0'
+use_frameworks!
+
+target ‘’ do
+ pod 'Kingfisher', '~> 2.4'
+end
+```
Then, run the following command:
``` bash
@@ -83,7 +106,7 @@ $ brew install carthage
To integrate Kingfisher into your Xcode project using Carthage, specify it in your `Cartfile`:
``` ogdl
-github "onevcat/Kingfisher" ~> 1.9
+github "onevcat/Kingfisher" ~> 2.4
```
Then, run the following command to build the Kingfisher framework:
@@ -125,15 +148,15 @@ $ git submodule add https://github.com/onevcat/Kingfisher.git
- In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar.
- In the tab bar at the top of that window, open the "Build Phases" panel.
- Expand the "Target Dependencies" group, and add `Kingfisher.framework`.
-- Click on the `+` button at the top left of "Build Phases" panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Kingfisher.framework`.
+- Click on the `+` button at the top left of "Build Phases" panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Kingfisher.framework` of the platform you need.
## Usage
You can find the full API documentation at [CocoaDocs](http://cocoadocs.org/docsets/Kingfisher/).
-### UIImageView category
+### UIImageView and NSImageView category
-Use Kingfisher in your project is as easy as a pie. You can use the `UIImageView` category and trust Kingfisher to manage downloading and cache images.
+Use Kingfisher in your project is as easy as a pie. You can use the `UIImageView` or `NSImageView` category and trust Kingfisher to manage downloading and cache images.
#### Basic
@@ -164,12 +187,12 @@ It will ask Kingfisher's manager to get the image for the "your_customized_key"
#### Options
-Kingfisher will search in cache (both memory and disk) first with the URL, if no image found, it will try to download and store the image in the cache. You can change this behavior by passing an option dictionary, to let it ignore the cache.
+Kingfisher will search in cache (both memory and disk) first with the URL, if no image found, it will try to download and store the image in the cache. You can change this behavior by passing an option, to let it ignore the cache.
``` swift
imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
placeholderImage: nil,
- optionsInfo: [.Options(KingfisherOptions.ForceRefresh)])
+ optionsInfo: [.ForceRefresh])
```
There are also other options to control the cache level, downloading priority, etc. Take some other examples:
@@ -186,7 +209,7 @@ imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
This is useful if you want to use a specified cache for some reasons.
-And if you need to fade in the image to image view during 1 second:
+And if you need to fade in the image to image view during 1 second (image transition only works for iOS platform now):
```
imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
@@ -194,6 +217,18 @@ imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
optionsInfo: [.Transition(ImageTransition.Fade(1))])
```
+You are also free to combine these options to customize the behavior:
+
+```swift
+let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
+let optionInfo: KingfisherOptionsInfo = [
+ .ForceRefresh,
+ .DownloadPriority(0.5),
+ .CallbackDispatchQueue(queue),
+ .Transition(ImageTransition.Fade(1))
+]
+```
+
For more information about options, please see the `KingfisherOptionsInfo` in the [documentation](http://cocoadocs.org/docsets/Kingfisher/index.html).
#### Callbacks
@@ -207,7 +242,7 @@ imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
progressBlock: { (receivedSize, totalSize) -> () in
print("Download Progress: \(receivedSize)/\(totalSize)")
},
- completionHandler: { (image, error, imageURL) -> () in
+ completionHandler: { (image, error, cacheType, imageURL) -> () in
print("Downloaded and set!")
}
)
@@ -216,8 +251,7 @@ imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
#### Cancel Task
You can `cancel` the task if the images are not needed anymore.
-It could be useful when you use Kingfisher to set an image in a cell of table view or collection view,
-but users scroll the view and the cells disappeared before downloading finishing.
+It could be useful when you use Kingfisher to set an image in a cell of table view or collection view, but users scroll the view and the cells disappeared before downloading finishing.
``` swift
imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!)
@@ -226,7 +260,7 @@ imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!)
imageView.kf_cancelDownloadTask()
```
-All `kf_setImageWithURL` methods return a `RetrieveImageTask` object as well. You can also hold and manage it if you need to apply some check:
+If you need more control and want to do some check before cancelling, all `kf_setImageWithURL` methods return a `RetrieveImageTask` object as well. You can also hold and manage it, then call cancel on the task:
``` swift
let task = imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!)
@@ -288,6 +322,42 @@ cache.clearDiskCache()
cache.cleanExpiredDiskCache()
```
+### Prefetching
+
+You could prefetch some images and cache them before you display them on the screen. This is useful when you know a list of image resources you know they would probably be shown later. Since the prefetched images are already in the cache system, there is no need to request them again when you really need to display them in a image view. It will boost your UI and bring your users great experience.
+
+To prefetch some images, you could use the `ImagePrefetcher`:
+
+```swift
+let urls = ["http://example.com/image1.jpg", "http://example.com/image2.jpg"].map { NSURL(string: $0)! }
+let prefetcher = ImagePrefetcher(urls: urls, optionsInfo: nil, progressBlock: nil, completionHandler: {
+ (skippedResources, failedResources, completedResources) -> () in
+ print("These resources are prefetched: \(completedResources)")
+})
+prefetcher.start()
+```
+
+You can also stop a prefetch whenever you need:
+
+```swift
+prefetcher.stop()
+```
+
+After prefetching, you could retrieve image or set the image view with other Kingfisher's methods, with the same `ImageCache` object you used for the prefetching.
+
+### Animated GIF
+
+You can load animated GIF by replacing `UIImageView` with `AnimatedImageView`, and then using the same API for a regular image view like this:
+
+```swift
+let imageView = AnimatedImageView()
+imageView.kf_setImageWithURL(NSURL(string: "your_animated_gif_image_url")!)
+```
+
+`AnimatedImageView` will only decode some frames of your GIF image to get a smaller memory footprint. You can set the frame count you need to pre-load by setting the `framePreloadCount` property of an `AnimatedImageView` (default is 10).
+
+You can also load a GIF file by a regular `UIImageView`. However, all frames will be loaded and decoded into memory. It is probably not suitable if you are loading a large GIF image. For most cases, you may want to use `AnimatedImageView`. The GIF support in Kingfisher's `UIImageView` only fits the small files, and now is mostly serving for back compatibility.
+
## Future of Kingfisher
I want to keep Kingfisher slim. This framework will focus on providing a simple solution for image downloading and caching. But that does not mean the framework will not be improved. Kingfisher is far away from perfect, and necessary and useful features will be added later to make it better.
@@ -303,3 +373,5 @@ Follow and contact me on [Twitter](http://twitter.com/onevcat) or [Sina Weibo](h
## License
Kingfisher is released under the MIT license. See LICENSE for details.
+
+
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/AnimatedImageView.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/AnimatedImageView.swift
new file mode 100644
index 0000000..073c52f
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/AnimatedImageView.swift
@@ -0,0 +1,375 @@
+//
+// AnimatableImageView.swift
+// Kingfisher
+//
+// Created by bl4ckra1sond3tre on 4/22/16.
+//
+// The AnimatableImageView, AnimatedFrame and Animator is a modified version of
+// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
+//
+// The MIT License (MIT)
+//
+// Copyright (c) 2014-2016 Reda Lemeden.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy of
+// this software and associated documentation files (the "Software"), to deal in
+// the Software without restriction, including without limitation the rights to
+// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+// the Software, and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+// The name and characters used in the demo of this software are property of their
+// respective owners.
+
+import UIKit
+import ImageIO
+
+/// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image.
+public class AnimatedImageView: UIImageView {
+
+ /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView.
+ class TargetProxy {
+ private weak var target: AnimatedImageView?
+
+ init(target: AnimatedImageView) {
+ self.target = target
+ }
+
+ @objc func onScreenUpdate() {
+ target?.updateFrame()
+ }
+ }
+
+ // MARK: - Public property
+ /// Whether automatically play the animation when the view become visible. Default is true.
+ public var autoPlayAnimatedImage = true
+
+ /// The size of the frame cache.
+ public var framePreloadCount = 10
+
+ /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true.
+ public var needsPrescaling = true
+
+ /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling.
+ public var runLoopMode = NSRunLoopCommonModes {
+ willSet {
+ if runLoopMode == newValue {
+ return
+ } else {
+ stopAnimating()
+ displayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: runLoopMode)
+ displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: newValue)
+ startAnimating()
+ }
+ }
+ }
+
+ // MARK: - Private property
+ /// `Animator` instance that holds the frames of a specific image in memory.
+ private var animator: Animator?
+
+ /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D
+ private var displayLinkInitialized: Bool = false
+
+ /// A display link that keeps calling the `updateFrame` method on every screen refresh.
+ private lazy var displayLink: CADisplayLink = {
+ self.displayLinkInitialized = true
+ let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
+ displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: self.runLoopMode)
+ displayLink.paused = true
+ return displayLink
+ }()
+
+ // MARK: - Override
+ override public var image: Image? {
+ didSet {
+ if image != oldValue {
+ reset()
+ }
+ setNeedsDisplay()
+ layer.setNeedsDisplay()
+ }
+ }
+
+ deinit {
+ if displayLinkInitialized {
+ displayLink.invalidate()
+ }
+ }
+
+ override public func isAnimating() -> Bool {
+ if displayLinkInitialized {
+ return !displayLink.paused
+ } else {
+ return super.isAnimating()
+ }
+ }
+
+ /// Starts the animation.
+ override public func startAnimating() {
+ if self.isAnimating() {
+ return
+ } else {
+ displayLink.paused = false
+ }
+ }
+
+ /// Stops the animation.
+ override public func stopAnimating() {
+ super.stopAnimating()
+ if displayLinkInitialized {
+ displayLink.paused = true
+ }
+ }
+
+ override public func displayLayer(layer: CALayer) {
+ if let currentFrame = animator?.currentFrame {
+ layer.contents = currentFrame.CGImage
+ } else {
+ layer.contents = image?.CGImage
+ }
+ }
+
+ override public func didMoveToWindow() {
+ super.didMoveToWindow()
+ didMove()
+ }
+
+ override public func didMoveToSuperview() {
+ super.didMoveToSuperview()
+ didMove()
+ }
+
+ // This is for back compatibility that using regular UIImageView to show GIF.
+ override func shouldPreloadAllGIF() -> Bool {
+ return false
+ }
+
+ // MARK: - Private method
+ /// Reset the animator.
+ private func reset() {
+ animator = nil
+ if let imageSource = image?.kf_imageSource?.imageRef {
+ animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount)
+ animator?.needsPrescaling = needsPrescaling
+ animator?.prepareFrames()
+ }
+ didMove()
+ }
+
+ private func didMove() {
+ if autoPlayAnimatedImage && animator != nil {
+ if let _ = superview, _ = window {
+ startAnimating()
+ } else {
+ stopAnimating()
+ }
+ }
+ }
+
+ /// Update the current frame with the displayLink duration.
+ private func updateFrame() {
+ if animator?.updateCurrentFrame(displayLink.duration) ?? false {
+ layer.setNeedsDisplay()
+ }
+ }
+}
+
+/// Keeps a reference to an `Image` instance and its duration as a GIF frame.
+struct AnimatedFrame {
+ var image: Image?
+ let duration: NSTimeInterval
+
+ static func null() -> AnimatedFrame {
+ return AnimatedFrame(image: .None, duration: 0.0)
+ }
+}
+
+// MARK: - Animator
+///
+class Animator {
+ // MARK: Private property
+ private let size: CGSize
+ private let maxFrameCount: Int
+ private let imageSource: CGImageSourceRef
+
+ private var animatedFrames = [AnimatedFrame]()
+ private let maxTimeStep: NSTimeInterval = 1.0
+ private var frameCount = 0
+ private var currentFrameIndex = 0
+ private var currentPreloadIndex = 0
+ private var timeSinceLastFrameChange: NSTimeInterval = 0.0
+ private var needsPrescaling = true
+
+ /// Loop count of animatd image.
+ private var loopCount = 0
+
+ var currentFrame: UIImage? {
+ return frameAtIndex(currentFrameIndex)
+ }
+
+ var contentMode: UIViewContentMode = .ScaleToFill
+
+ /**
+ Init an animator with image source reference.
+
+ - parameter imageSource: The reference of animated image.
+
+ - parameter contentMode: Content mode of AnimatedImageView.
+
+ - parameter size: Size of AnimatedImageView.
+
+ - framePreloadCount: Frame cache size.
+
+ - returns: The animator object.
+ */
+ init(imageSource src: CGImageSourceRef, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount: Int) {
+ self.imageSource = src
+ self.contentMode = mode
+ self.size = size
+ self.maxFrameCount = framePreloadCount
+ }
+
+ func frameAtIndex(index: Int) -> Image? {
+ return animatedFrames[index].image
+ }
+
+ func prepareFrames() {
+ frameCount = CGImageSourceGetCount(imageSource)
+
+ if let properties = CGImageSourceCopyProperties(imageSource, nil),
+ gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
+ loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int {
+ self.loopCount = loopCount
+ }
+
+ let frameToProcess = min(frameCount, maxFrameCount)
+ animatedFrames.reserveCapacity(frameToProcess)
+ animatedFrames = (0.. AnimatedFrame {
+ guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
+ return AnimatedFrame.null()
+ }
+
+ let frameDuration = imageSource.kf_GIFPropertiesAtIndex(index).flatMap { (gifInfo) -> Double? in
+ let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
+ let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
+ let duration = unclampedDelayTime ?? delayTime
+ /**
+ http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
+ Many annoying ads specify a 0 duration to make an image flash as quickly as
+ possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
+ for any frames that specify a duration of <= 10 ms.
+ See and for more information.
+
+ See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
+ */
+ return duration > 0.011 ? duration : 0.100
+ }
+
+ let image = Image(CGImage: imageRef)
+ let scaledImage: Image?
+
+ if needsPrescaling {
+ scaledImage = image.kf_resizeToSize(size, contentMode: contentMode)
+ } else {
+ scaledImage = image
+ }
+
+ return AnimatedFrame(image: scaledImage, duration: frameDuration ?? 0.0)
+ }
+
+ /**
+ Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
+ */
+ func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
+ timeSinceLastFrameChange += min(maxTimeStep, duration)
+ guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration where frameDuration <= timeSinceLastFrameChange else {
+ return false
+ }
+
+ timeSinceLastFrameChange -= frameDuration
+ let lastFrameIndex = currentFrameIndex
+ currentFrameIndex += 1
+ currentFrameIndex = currentFrameIndex % animatedFrames.count
+
+ if animatedFrames.count < frameCount {
+ animatedFrames[lastFrameIndex] = prepareFrame(currentPreloadIndex)
+ currentPreloadIndex += 1
+ currentPreloadIndex = currentPreloadIndex % frameCount
+ }
+ return true
+ }
+}
+
+// MARK: - Resize
+extension Image {
+ func kf_resizeToSize(size: CGSize, contentMode: UIViewContentMode) -> Image {
+ switch contentMode {
+ case .ScaleAspectFit:
+ let newSize = self.size.kf_sizeConstrainedSize(size)
+ return kf_resizeToSize(newSize)
+ case .ScaleAspectFill:
+ let newSize = self.size.kf_sizeFillingSize(size)
+ return kf_resizeToSize(newSize)
+ default:
+ return kf_resizeToSize(size)
+ }
+ }
+
+ private func kf_resizeToSize(size: CGSize) -> Image {
+ UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
+ drawInRect(CGRect(origin: CGPoint.zero, size: size))
+ let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
+ UIGraphicsEndImageContext()
+ return resizedImage ?? self
+ }
+}
+
+extension CGSize {
+ func kf_sizeConstrainedSize(size: CGSize) -> CGSize {
+ let aspectWidth = round(kf_aspectRatio * size.height)
+ let aspectHeight = round(size.width / kf_aspectRatio)
+
+ return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
+ }
+
+ func kf_sizeFillingSize(size: CGSize) -> CGSize {
+ let aspectWidth = round(kf_aspectRatio * size.height)
+ let aspectHeight = round(size.width / kf_aspectRatio)
+
+ return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
+ }
+ private var kf_aspectRatio: CGFloat {
+ return height == 0.0 ? 1.0 : width / height
+ }
+}
+
+extension CGImageSourceRef {
+ func kf_GIFPropertiesAtIndex(index: Int) -> [String: Double]? {
+ let properties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as Dictionary?
+ return properties?[kCGImagePropertyGIFDictionary as String] as? [String: Double]
+ }
+}
+
+extension Array {
+ subscript(safe index: Int) -> Element? {
+ return indices ~= index ? self[index] : .None
+ }
+}
+
+private func pure(value: T) -> [T] {
+ return [value]
+}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/Box.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/Box.swift
new file mode 100644
index 0000000..7076add
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/Box.swift
@@ -0,0 +1,16 @@
+//
+// Box.swift
+// Kingfisher
+//
+// Created by WANG WEI on 2016/09/12.
+// Copyright © 2016年 Wei Wang. All rights reserved.
+//
+
+import Foundation
+
+class Box {
+ let value: T
+ init(value: T) {
+ self.value = value
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/Image.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/Image.swift
new file mode 100644
index 0000000..470f12f
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/Image.swift
@@ -0,0 +1,415 @@
+//
+// Image.swift
+// Kingfisher
+//
+// Created by Wei Wang on 16/1/6.
+//
+// Copyright (c) 2016 Wei Wang
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+
+#if os(OSX)
+import AppKit.NSImage
+public typealias Image = NSImage
+
+private var imagesKey: Void?
+private var durationKey: Void?
+#else
+import UIKit.UIImage
+import MobileCoreServices
+public typealias Image = UIImage
+
+private var imageSourceKey: Void?
+private var animatedImageDataKey: Void?
+#endif
+
+import ImageIO
+
+// MARK: - Image Properties
+extension Image {
+#if os(OSX)
+
+ var CGImage: CGImageRef! {
+ return CGImageForProposedRect(nil, context: nil, hints: nil)
+ }
+
+ var kf_scale: CGFloat {
+ return 1.0
+ }
+
+ private(set) var kf_images: [Image]? {
+ get {
+ return objc_getAssociatedObject(self, &imagesKey) as? [Image]
+ }
+ set {
+ objc_setAssociatedObject(self, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+ }
+
+ private(set) var kf_duration: NSTimeInterval {
+ get {
+ return objc_getAssociatedObject(self, &durationKey) as? NSTimeInterval ?? 0.0
+ }
+ set {
+ objc_setAssociatedObject(self, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+ }
+
+#else
+ var kf_scale: CGFloat {
+ return scale
+ }
+
+ var kf_images: [Image]? {
+ return images
+ }
+
+ var kf_duration: NSTimeInterval {
+ return duration
+ }
+
+ private(set) var kf_imageSource: ImageSource? {
+ get {
+ return objc_getAssociatedObject(self, &imageSourceKey) as? ImageSource
+ }
+ set {
+ objc_setAssociatedObject(self, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+ }
+
+ private(set) var kf_animatedImageData: NSData? {
+ get {
+ return objc_getAssociatedObject(self, &animatedImageDataKey) as? NSData
+ }
+ set {
+ objc_setAssociatedObject(self, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+ }
+#endif
+}
+
+// MARK: - Image Conversion
+extension Image {
+#if os(OSX)
+ static func kf_imageWithCGImage(cgImage: CGImageRef, scale: CGFloat, refImage: Image?) -> Image {
+ return Image(CGImage: cgImage, size: CGSize.zero)
+ }
+
+ /**
+ Normalize the image. This method does nothing in OS X.
+
+ - returns: The image itself.
+ */
+ public func kf_normalizedImage() -> Image {
+ return self
+ }
+
+ static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
+ return nil
+ }
+#else
+ static func kf_imageWithCGImage(cgImage: CGImageRef, scale: CGFloat, refImage: Image?) -> Image {
+ if let refImage = refImage {
+ return Image(CGImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
+ } else {
+ return Image(CGImage: cgImage, scale: scale, orientation: .Up)
+ }
+ }
+
+ /**
+ Normalize the image. This method will try to redraw an image with orientation and scale considered.
+
+ - returns: The normalized image with orientation set to up and correct scale.
+ */
+ public func kf_normalizedImage() -> Image {
+ // prevent animated image (GIF) lose it's images
+ if images != nil {
+ return self
+ }
+
+ if imageOrientation == .Up {
+ return self
+ }
+
+ UIGraphicsBeginImageContextWithOptions(size, false, scale)
+ drawInRect(CGRect(origin: CGPoint.zero, size: size))
+ let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
+ UIGraphicsEndImageContext()
+
+ return normalizedImage ?? self
+ }
+
+ static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
+ return Image.animatedImageWithImages(images, duration: duration)
+ }
+#endif
+}
+
+
+// MARK: - PNG
+func ImagePNGRepresentation(image: Image) -> NSData? {
+#if os(OSX)
+ if let cgimage = image.CGImage {
+ let rep = NSBitmapImageRep(CGImage: cgimage)
+ #if swift(>=2.3)
+ return rep.representationUsingType(.PNG, properties:[:])
+ #else
+ return rep.representationUsingType(.NSPNGFileType, properties:[:])
+ #endif
+ }
+ return nil
+#else
+ return UIImagePNGRepresentation(image)
+#endif
+}
+
+// MARK: - JPEG
+func ImageJPEGRepresentation(image: Image, _ compressionQuality: CGFloat) -> NSData? {
+#if os(OSX)
+ let rep = NSBitmapImageRep(CGImage: image.CGImage)
+ #if swift(>=2.3)
+ return rep.representationUsingType(.JPEG, properties: [NSImageCompressionFactor: compressionQuality])
+ #else
+ return rep.representationUsingType(.NSJPEGFileType, properties: [NSImageCompressionFactor: compressionQuality])
+ #endif
+#else
+ return UIImageJPEGRepresentation(image, compressionQuality)
+#endif
+}
+
+// MARK: - GIF
+func ImageGIFRepresentation(image: Image) -> NSData? {
+#if os(OSX)
+ return ImageGIFRepresentation(image, duration: 0.0, repeatCount: 0)
+#else
+ return image.kf_animatedImageData
+#endif
+}
+
+func ImageGIFRepresentation(image: Image, duration: NSTimeInterval, repeatCount: Int) -> NSData? {
+ guard let images = image.kf_images else {
+ return nil
+ }
+
+ let frameCount = images.count
+ let gifDuration = duration <= 0.0 ? image.kf_duration / Double(frameCount) : duration / Double(frameCount)
+
+ let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
+ let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
+
+ let data = NSMutableData()
+
+ guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
+ return nil
+ }
+ CGImageDestinationSetProperties(destination, imageProperties)
+
+ for image in images {
+ CGImageDestinationAddImage(destination, image.CGImage!, frameProperties)
+ }
+
+ return CGImageDestinationFinalize(destination) ? NSData(data: data) : nil
+}
+
+func ImagesCountWithImageSource(ref: CGImageSourceRef) -> Int {
+ return CGImageSourceGetCount(ref)
+}
+
+extension Image {
+ static func kf_animatedImageWithGIFData(gifData data: NSData, preloadAll: Bool) -> Image? {
+ return kf_animatedImageWithGIFData(gifData: data, scale: 1.0, duration: 0.0, preloadAll: preloadAll)
+ }
+
+ static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval, preloadAll: Bool) -> Image? {
+
+ func decodeFromSource(imageSource: CGImageSource, options: NSDictionary) -> ([Image], NSTimeInterval)? {
+
+ //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
+ func frameDuration(fromGifInfo gifInfo: NSDictionary) -> Double {
+ let gifDefaultFrameDuration = 0.100
+
+ let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
+ let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
+ let duration = unclampedDelayTime ?? delayTime
+
+ guard let frameDuration = duration else { return gifDefaultFrameDuration }
+
+ return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
+ }
+
+ let frameCount = CGImageSourceGetCount(imageSource)
+ var images = [Image]()
+ var gifDuration = 0.0
+ for i in 0 ..< frameCount {
+
+ guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
+ return nil
+ }
+
+ if frameCount == 1 {
+ // Single frame
+ gifDuration = Double.infinity
+ } else {
+ // Animated GIF
+ guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
+ gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else
+ {
+ return nil
+ }
+ gifDuration += frameDuration(fromGifInfo: gifInfo)
+ }
+
+ images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))
+ }
+
+ return (images, gifDuration)
+ }
+
+ // Start of kf_animatedImageWithGIFData
+ let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
+ guard let imageSource = CGImageSourceCreateWithData(data, options) else {
+ return nil
+ }
+
+#if os(OSX)
+ guard let (images, gifDuration) = decodeFromSource(imageSource, options: options) else {
+ return nil
+ }
+ let image = Image(data: data)
+ image?.kf_images = images
+ image?.kf_duration = gifDuration
+
+ return image
+#else
+
+ if preloadAll {
+ guard let (images, gifDuration) = decodeFromSource(imageSource, options: options) else {
+ return nil
+ }
+ let image = Image.kf_animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
+ image?.kf_animatedImageData = data
+ return image
+ } else {
+ let image = Image(data: data)
+ image?.kf_animatedImageData = data
+ image?.kf_imageSource = ImageSource(ref: imageSource)
+ return image
+ }
+#endif
+
+ }
+}
+
+// MARK: - Create images from data
+extension Image {
+ static func kf_imageWithData(data: NSData, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
+ var image: Image?
+ #if os(OSX)
+ switch data.kf_imageFormat {
+ case .JPEG: image = Image(data: data)
+ case .PNG: image = Image(data: data)
+ case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
+ case .Unknown: image = Image(data: data)
+ }
+ #else
+ switch data.kf_imageFormat {
+ case .JPEG: image = Image(data: data, scale: scale)
+ case .PNG: image = Image(data: data, scale: scale)
+ case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
+ case .Unknown: image = Image(data: data, scale: scale)
+ }
+ #endif
+
+ return image
+ }
+}
+
+// MARK: - Decode
+extension Image {
+ func kf_decodedImage() -> Image? {
+ return self.kf_decodedImage(scale: kf_scale)
+ }
+
+ func kf_decodedImage(scale scale: CGFloat) -> Image? {
+ // prevent animated image (GIF) lose it's images
+#if os(iOS)
+ if kf_imageSource != nil {
+ return self
+ }
+#else
+ if kf_images != nil {
+ return self
+ }
+#endif
+
+ let imageRef = self.CGImage
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
+ let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
+
+ if let imageRef = imageRef, context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo) {
+ let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
+ CGContextDrawImage(context, rect, imageRef)
+ let decompressedImageRef = CGBitmapContextCreateImage(context)
+ return Image.kf_imageWithCGImage(decompressedImageRef!, scale: scale, refImage: self)
+ } else {
+ return nil
+ }
+ }
+}
+
+/// Reference the source image reference
+class ImageSource {
+ var imageRef: CGImageSourceRef?
+ init(ref: CGImageSourceRef) {
+ self.imageRef = ref
+ }
+}
+
+// MARK: - Image format
+private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
+private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
+private let jpgHeaderIF: [UInt8] = [0xFF]
+private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
+
+enum ImageFormat {
+ case Unknown, PNG, JPEG, GIF
+}
+
+extension NSData {
+ var kf_imageFormat: ImageFormat {
+ var buffer = [UInt8](count: 8, repeatedValue: 0)
+ self.getBytes(&buffer, length: 8)
+ if buffer == pngHeader {
+ return .PNG
+ } else if buffer[0] == jpgHeaderSOI[0] &&
+ buffer[1] == jpgHeaderSOI[1] &&
+ buffer[2] == jpgHeaderIF[0]
+ {
+ return .JPEG
+ } else if buffer[0] == gifHeader[0] &&
+ buffer[1] == gifHeader[1] &&
+ buffer[2] == gifHeader[2]
+ {
+ return .GIF
+ }
+
+ return .Unknown
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageCache.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageCache.swift
similarity index 70%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageCache.swift
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/ImageCache.swift
index d4e1b26..233e92b 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageCache.swift
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageCache.swift
@@ -4,7 +4,7 @@
//
// Created by Wei Wang on 15/4/6.
//
-// Copyright (c) 2015 Wei Wang
+// Copyright (c) 2016 Wei Wang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -24,7 +24,11 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+#if os(OSX)
+import AppKit
+#else
import UIKit
+#endif
/**
This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification.
@@ -125,9 +129,11 @@ public class ImageCache {
self.fileManager = NSFileManager()
})
- NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
- NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil)
- NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil)
+#if !os(OSX) && !os(watchOS)
+ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageCache.clearMemoryCache), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
+ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageCache.cleanExpiredDiskCache), name: UIApplicationWillTerminateNotification, object: nil)
+ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageCache.backgroundCleanExpiredDiskCache), name: UIApplicationDidEnterBackgroundNotification, object: nil)
+#endif
}
deinit {
@@ -136,36 +142,20 @@ public class ImageCache {
}
// MARK: - Store & Remove
-public extension ImageCache {
- /**
- Store an image to cache. It will be saved to both memory and disk.
- It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:`
- instead.
-
- - parameter image: The image will be stored.
- - parameter originalData: The original data of the image.
- Kingfisher will use it to check the format of the image and optimize cache size on disk.
- If `nil` is supplied, the image data will be saved as a normalized PNG file.
- It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
- - parameter key: Key for the image.
- */
- public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String) {
- storeImage(image, originalData: originalData, forKey: key, toDisk: true, completionHandler: nil)
- }
-
+extension ImageCache {
/**
- Store an image to cache. It is an async operation.
+ Store an image to cache. It will be saved to both memory and disk. It is an async operation.
- - parameter image: The image will be stored.
+ - parameter image: The image to be stored.
- parameter originalData: The original data of the image.
Kingfisher will use it to check the format of the image and optimize cache size on disk.
If `nil` is supplied, the image data will be saved as a normalized PNG file.
It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
- parameter key: Key for the image.
- parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
- - parameter completionHandler: Called when stroe operation completes.
+ - parameter completionHandler: Called when store operation completes.
*/
- public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) {
+ public func storeImage(image: Image, originalData: NSData? = nil, forKey key: String, toDisk: Bool = true, completionHandler: (() -> Void)? = nil) {
memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost)
func callHandlerInMainQueue() {
@@ -177,7 +167,7 @@ public extension ImageCache {
}
if toDisk {
- dispatch_async(ioQueue, { () -> Void in
+ dispatch_async(ioQueue, {
let imageFormat: ImageFormat
if let originalData = originalData {
imageFormat = originalData.kf_imageFormat
@@ -187,10 +177,10 @@ public extension ImageCache {
let data: NSData?
switch imageFormat {
- case .PNG: data = originalData ?? UIImagePNGRepresentation(image)
- case .JPEG: data = originalData ?? UIImageJPEGRepresentation(image, 1.0)
- case .GIF: data = originalData ?? UIImageGIFRepresentation(image)
- case .Unknown: data = originalData ?? UIImagePNGRepresentation(image.kf_normalizedImage())
+ case .PNG: data = originalData ?? ImagePNGRepresentation(image)
+ case .JPEG: data = originalData ?? ImageJPEGRepresentation(image, 1.0)
+ case .GIF: data = originalData ?? ImageGIFRepresentation(image)
+ case .Unknown: data = originalData ?? ImagePNGRepresentation(image.kf_normalizedImage())
}
if let data = data {
@@ -210,24 +200,14 @@ public extension ImageCache {
}
/**
- Remove the image for key for the cache. It will be opted out from both memory and disk.
- It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:`
- instead.
-
- - parameter key: Key for the image.
- */
- public func removeImageForKey(key: String) {
- removeImageForKey(key, fromDisk: true, completionHandler: nil)
- }
-
- /**
- Remove the image for key for the cache. It is an async operation.
+ Remove the image for key for the cache. It will be opted out from both memory and disk.
+ It is an async operation.
- parameter key: Key for the image.
- parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
- parameter completionHandler: Called when removal operation completes.
*/
- public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) {
+ public func removeImageForKey(key: String, fromDisk: Bool = true, completionHandler: (() -> Void)? = nil) {
memoryCache.removeObjectForKey(key)
func callHandlerInMainQueue() {
@@ -263,61 +243,51 @@ extension ImageCache {
- returns: The retrieving task.
*/
- public func retrieveImageForKey(key: String, options: KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? {
+ public func retrieveImageForKey(key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask? {
// No completion handler. Not start working and early return.
guard let completionHandler = completionHandler else {
return nil
}
var block: RetrieveImageDiskTask?
+ let options = options ?? KingfisherEmptyOptionsInfo
+
if let image = self.retrieveImageInMemoryCacheForKey(key) {
-
- //Found image in memory cache.
- if options.shouldDecode {
- dispatch_async(self.processQueue, { () -> Void in
- let result = image.kf_decodedImage(scale: options.scale)
- dispatch_async(options.queue, { () -> Void in
- completionHandler(result, .Memory)
- })
- })
- } else {
+ dispatch_async_safely_to_queue(options.callbackDispatchQueue) { () -> Void in
completionHandler(image, .Memory)
}
} else {
var sSelf: ImageCache! = self
block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
-
// Begin to load image from disk
- dispatch_async(sSelf.ioQueue, { () -> Void in
- if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scale) {
- if options.shouldDecode {
- dispatch_async(sSelf.processQueue, { () -> Void in
- let result = image.kf_decodedImage(scale: options.scale)
- sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil)
+ if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) {
+ if options.backgroundDecode {
+ dispatch_async(sSelf.processQueue, { () -> Void in
+ let result = image.kf_decodedImage(scale: options.scaleFactor)
+ sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil)
- dispatch_async(options.queue, { () -> Void in
- completionHandler(result, .Memory)
- sSelf = nil
- })
- })
- } else {
- sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil)
- dispatch_async(options.queue, { () -> Void in
- completionHandler(image, .Disk)
+ dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
+ completionHandler(result, .Memory)
sSelf = nil
})
- }
+ })
} else {
- // No image found from either memory or disk
- dispatch_async(options.queue, { () -> Void in
- completionHandler(nil, nil)
+ sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil)
+ dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
+ completionHandler(image, .Disk)
sSelf = nil
})
}
- })
+ } else {
+ // No image found from either memory or disk
+ dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
+ completionHandler(nil, .None)
+ sSelf = nil
+ })
+ }
}
- dispatch_async(dispatch_get_main_queue(), block!)
+ dispatch_async(sSelf.ioQueue, block!)
}
return block
@@ -330,20 +300,22 @@ extension ImageCache {
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
- public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? {
- return memoryCache.objectForKey(key) as? UIImage
+ public func retrieveImageInMemoryCacheForKey(key: String) -> Image? {
+ return memoryCache.objectForKey(key) as? Image
}
/**
Get an image for a key from disk.
- parameter key: Key for the image.
- - param scale: The scale factor to assume when interpreting the image data.
+ - parameter scale: The scale factor to assume when interpreting the image data.
+ - parameter preloadAllGIFData: Whether all GIF data should be loaded. If true, you can set the loaded image to a regular UIImageView to play
+ the GIF animation. Otherwise, you should use `AnimatedImageView` to play it. Default is `false`
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
- public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = KingfisherManager.DefaultOptions.scale) -> UIImage? {
- return diskImageForKey(key, scale: scale)
+ public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = 1.0, preloadAllGIFData: Bool = false) -> Image? {
+ return diskImageForKey(key, scale: scale, preloadAllGIFData: preloadAllGIFData)
}
}
@@ -357,8 +329,7 @@ extension ImageCache {
}
/**
- Clear disk cache. This is could be an async or sync operation.
- Specify the way you want it by passing the `sync` parameter.
+ Clear disk cache.
*/
public func clearDiskCache() {
clearDiskCacheWithCompletionHandler(nil)
@@ -398,47 +369,12 @@ extension ImageCache {
- parameter completionHandler: Called after the operation completes.
*/
public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) {
+
// Do things in cocurrent io queue
dispatch_async(ioQueue, { () -> Void in
- let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath)
- let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]
- let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond)
- var cachedFiles = [NSURL: [NSObject: AnyObject]]()
- var URLsToDelete = [NSURL]()
- var diskCacheSize: UInt = 0
+ var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
- if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil),
- urls = fileEnumerator.allObjects as? [NSURL] {
- for fileURL in urls {
-
- do {
- let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
- // If it is a Directory. Continue to next file URL.
- if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber {
- if isDirectory.boolValue {
- continue
- }
- }
-
- // If this file is expired, add it to URLsToDelete
- if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate {
- if modificationDate.laterDate(expiredDate) == expiredDate {
- URLsToDelete.append(fileURL)
- continue
- }
- }
-
- if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
- diskCacheSize += fileSize.unsignedLongValue
- cachedFiles[fileURL] = resourceValues
- }
- } catch _ {
- }
-
- }
- }
-
for fileURL in URLsToDelete {
do {
try self.fileManager.removeItemAtURL(fileURL)
@@ -453,8 +389,8 @@ extension ImageCache {
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
- if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate,
- date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate {
+ if let date1 = resourceValue1[NSURLContentAccessDateKey] as? NSDate,
+ date2 = resourceValue2[NSURLContentAccessDateKey] as? NSDate {
return date1.compare(date2) == .OrderedAscending
}
// Not valid date information. This should not happen. Just in case.
@@ -484,8 +420,10 @@ extension ImageCache {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if URLsToDelete.count != 0 {
- let cleanedHashes = URLsToDelete.map( {$0.lastPathComponent!} )
-
+ let cleanedHashes = URLsToDelete.map({ (url) -> String in
+ return url.lastPathComponent!
+ })
+
NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
}
@@ -494,21 +432,71 @@ extension ImageCache {
})
}
+ private func travelCachedFiles(onlyForCacheSize onlyForCacheSize: Bool) -> (URLsToDelete: [NSURL], diskCacheSize: UInt, cachedFiles: [NSURL: [NSObject: AnyObject]]) {
+
+ let diskCacheURL = NSURL(fileURLWithPath: diskCachePath)
+ let resourceKeys = [NSURLIsDirectoryKey, NSURLContentAccessDateKey, NSURLTotalFileAllocatedSizeKey]
+ let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond)
+
+ var cachedFiles = [NSURL: [NSObject: AnyObject]]()
+ var URLsToDelete = [NSURL]()
+ var diskCacheSize: UInt = 0
+
+ if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil),
+ urls = fileEnumerator.allObjects as? [NSURL] {
+ for fileURL in urls {
+
+ do {
+ let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
+ // If it is a Directory. Continue to next file URL.
+ if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber {
+ if isDirectory.boolValue {
+ continue
+ }
+ }
+
+ if !onlyForCacheSize {
+ // If this file is expired, add it to URLsToDelete
+ if let lastAccessDate = resourceValues[NSURLContentAccessDateKey] as? NSDate {
+ if lastAccessDate.laterDate(expiredDate) == expiredDate {
+ URLsToDelete.append(fileURL)
+ continue
+ }
+ }
+ }
+
+ if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
+ diskCacheSize += fileSize.unsignedLongValue
+ if !onlyForCacheSize {
+ cachedFiles[fileURL] = resourceValues
+ }
+ }
+ } catch _ {
+ }
+ }
+ }
+
+ return (URLsToDelete, diskCacheSize, cachedFiles)
+ }
+
+#if !os(OSX) && !os(watchOS)
/**
Clean expired disk cache when app in background. This is an async operation.
In most cases, you should not call this method explicitly.
It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
*/
@objc public func backgroundCleanExpiredDiskCache() {
-
+ // if 'sharedApplication()' is unavailable, then return
+ guard let sharedApplication = UIApplication.kf_sharedApplication() else { return }
+
func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) {
- UIApplication.sharedApplication().endBackgroundTask(task)
+ sharedApplication.endBackgroundTask(task)
task = UIBackgroundTaskInvalid
}
var backgroundTask: UIBackgroundTaskIdentifier!
- backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
+ backgroundTask = sharedApplication.beginBackgroundTaskWithExpirationHandler { () -> Void in
endBackgroundTask(&backgroundTask!)
}
@@ -516,11 +504,12 @@ extension ImageCache {
endBackgroundTask(&backgroundTask!)
}
}
+#endif
}
// MARK: - Check cache status
-public extension ImageCache {
+extension ImageCache {
/**
* Cache result for checking whether an image is cached for a key.
@@ -530,6 +519,21 @@ public extension ImageCache {
public let cacheType: CacheType?
}
+ /**
+ Determine if a cached image exists for the given image, as keyed by the URL. It will return true if the
+ image is found either in memory or on disk. Essentially as long as there is a cache of the image somewhere
+ true is returned. A convenience method that decodes `isImageCachedForKey`.
+
+ - parameter url: The image URL.
+
+ - returns: True if the image is cached, false otherwise.
+ */
+ public func cachedImageExistsforURL(url: NSURL) -> Bool {
+ let resource = Resource(downloadURL: url)
+ let result = isImageCachedForKey(resource.cacheKey)
+ return result.cached
+ }
+
/**
Check whether an image is cached for a key.
@@ -576,45 +580,35 @@ public extension ImageCache {
*/
public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())) {
dispatch_async(ioQueue, { () -> Void in
- let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath)
-
- let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey]
- var diskCacheSize: UInt = 0
-
- if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil),
- urls = fileEnumerator.allObjects as? [NSURL] {
- for fileURL in urls {
- do {
- let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
- // If it is a Directory. Continue to next file URL.
- if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
- if isDirectory {
- continue
- }
- }
-
- if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
- diskCacheSize += fileSize.unsignedLongValue
- }
- } catch _ {
- }
-
- }
- }
-
+ let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(size: diskCacheSize)
})
})
}
+
+ /**
+ Get the cache path for the key.
+ It is useful for projects with UIWebView or anyone that needs access to the local file path.
+
+ i.e. `
`
+
+ - Note: This method does not guarantee there is an image already cached in the path.
+ You could use `isImageCachedForKey` method to check whether the image is cached under that key.
+ */
+ public func cachePathForKey(key: String) -> String {
+ let fileName = cacheFileNameForKey(key)
+ return (diskCachePath as NSString).stringByAppendingPathComponent(fileName)
+ }
+
}
// MARK: - Internal Helper
extension ImageCache {
- func diskImageForKey(key: String, scale: CGFloat) -> UIImage? {
+ func diskImageForKey(key: String, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
if let data = diskImageDataForKey(key) {
- return UIImage.kf_imageWithData(data, scale: scale)
+ return Image.kf_imageWithData(data, scale: scale, preloadAllGIFData: preloadAllGIFData)
} else {
return nil
}
@@ -625,21 +619,16 @@ extension ImageCache {
return NSData(contentsOfFile: filePath)
}
- func cachePathForKey(key: String) -> String {
- let fileName = cacheFileNameForKey(key)
- return (diskCachePath as NSString).stringByAppendingPathComponent(fileName)
- }
-
func cacheFileNameForKey(key: String) -> String {
- return key.kf_MD5()
+ return key.kf_MD5
}
}
-extension UIImage {
+extension Image {
var kf_imageCost: Int {
- return images == nil ?
- Int(size.height * size.width * scale * scale) :
- Int(size.height * size.width * scale * scale) * images!.count
+ return kf_images == nil ?
+ Int(size.height * size.width * kf_scale * kf_scale) :
+ Int(size.height * size.width * kf_scale * kf_scale) * kf_images!.count
}
}
@@ -648,3 +637,14 @@ extension Dictionary {
return Array(self).sort{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
}
}
+
+#if !os(OSX) && !os(watchOS)
+// MARK: - For App Extensions
+extension UIApplication {
+ public static func kf_sharedApplication() -> UIApplication? {
+ let selector = NSSelectorFromString("sharedApplication")
+ guard respondsToSelector(selector) else { return nil }
+ return performSelector(selector).takeUnretainedValue() as? UIApplication
+ }
+}
+#endif
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageDownloader.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageDownloader.swift
similarity index 61%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageDownloader.swift
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/ImageDownloader.swift
index b5f90f7..906bfb2 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageDownloader.swift
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageDownloader.swift
@@ -4,7 +4,7 @@
//
// Created by Wei Wang on 15/4/6.
//
-// Copyright (c) 2015 Wei Wang
+// Copyright (c) 2016 Wei Wang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -24,13 +24,17 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+#if os(OSX)
+import AppKit
+#else
import UIKit
+#endif
/// Progress update block of downloader.
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
/// Completion block of downloader.
-public typealias ImageDownloaderCompletionHandler = ((image: UIImage?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ())
+public typealias ImageDownloaderCompletionHandler = ((image: Image?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ())
/// Download task.
public struct RetrieveImageDownloadTask {
@@ -50,6 +54,19 @@ public struct RetrieveImageDownloadTask {
public var URL: NSURL? {
return internalTask.originalRequest?.URL
}
+
+ /// The relative priority of this download task.
+ /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
+ /// The value for it is between 0.0~1.0. Default priority is value of 0.5.
+ /// See documentation on `priority` of `NSURLSessionTask` for more about it.
+ public var priority: Float {
+ get {
+ return internalTask.priority
+ }
+ set {
+ internalTask.priority = newValue
+ }
+ }
}
private let defaultDownloaderName = "default"
@@ -63,11 +80,14 @@ The error code.
- BadData: The downloaded data is not an image or the data is corrupted.
- NotModified: The remote server responsed a 304 code. No image data downloaded.
+- NotCached: The image rquested is not in cache but OnlyFromCache is activated.
- InvalidURL: The URL is invalid.
*/
public enum KingfisherError: Int {
case BadData = 10000
case NotModified = 10001
+ case InvalidStatusCode = 10002
+ case NotCached = 10003
case InvalidURL = 20000
}
@@ -81,7 +101,38 @@ public enum KingfisherError: Int {
- parameter URL: URL of the original request URL.
- parameter response: The response object of the downloading process.
*/
- optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: UIImage, forURL URL: NSURL, withResponse response: NSURLResponse)
+ optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: Image, forURL URL: NSURL, withResponse response: NSURLResponse)
+}
+
+/// Protocol indicates that an authentication challenge could be handled.
+public protocol AuthenticationChallengeResponable: class {
+ /**
+ Called when an session level authentication challenge is received.
+ This method provide a chance to handle and response to the authentication challenge before downloading could start.
+
+ - parameter downloader: The downloader which receives this challenge.
+ - parameter challenge: An object that contains the request for authentication.
+ - parameter completionHandler: A handler that your delegate method must call.
+
+ - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`.
+ */
+ func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
+}
+
+extension AuthenticationChallengeResponable {
+
+ func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
+
+ if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
+ if let trustedHosts = downloader.trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) {
+ let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
+ completionHandler(.UseCredential, credential)
+ return
+ }
+ }
+
+ completionHandler(.PerformDefaultHandling, nil)
+ }
}
/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
@@ -90,8 +141,9 @@ public class ImageDownloader: NSObject {
class ImageFetchLoad {
var callbacks = [CallbackPair]()
var responseData = NSMutableData()
- var shouldDecode = false
- var scale = KingfisherManager.DefaultOptions.scale
+
+ var options: KingfisherOptionsInfo?
+
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
}
@@ -103,21 +155,29 @@ public class ImageDownloader: NSObject {
/// The duration before the download is timeout. Default is 15 seconds.
public var downloadTimeout: NSTimeInterval = 15.0
- /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site.
+ /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead.
public var trustedHosts: Set?
/// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly.
public var sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() {
didSet {
- session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
+ session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue())
}
}
+ /// Whether the download requests should use pipeling or not. Default is false.
+ public var requestsUsePipeling = false
+
+ private let sessionHandler: ImageDownloaderSessionHandler
private var session: NSURLSession?
/// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
public weak var delegate: ImageDownloaderDelegate?
+ /// A responder for authentication challenge.
+ /// Downloader will forward the received authentication challenge for the downloading session to this responder.
+ public weak var authenticationChallengeResponder: AuthenticationChallengeResponable?
+
// MARK: - Internal property
let barrierQueue: dispatch_queue_t
let processQueue: dispatch_queue_t
@@ -147,9 +207,14 @@ public class ImageDownloader: NSObject {
barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT)
processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_CONCURRENT)
+ sessionHandler = ImageDownloaderSessionHandler()
+
super.init()
- session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
+ // Provide a default implement for challenge responder.
+ authenticationChallengeResponder = sessionHandler
+
+ session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue())
}
func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? {
@@ -162,7 +227,7 @@ public class ImageDownloader: NSObject {
}
// MARK: - Download method
-public extension ImageDownloader {
+extension ImageDownloader {
/**
Download an image with a URL.
@@ -176,21 +241,21 @@ public extension ImageDownloader {
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
- return downloadImageWithURL(URL, options: KingfisherManager.DefaultOptions, progressBlock: progressBlock, completionHandler: completionHandler)
+ return downloadImageWithURL(URL, options: nil, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Download an image with a URL and option.
- parameter URL: Target URL.
- - parameter options: The options could control download behavior. See `KingfisherManager.Options`
+ - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
public func downloadImageWithURL(URL: NSURL,
- options: KingfisherManager.Options,
+ options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
@@ -203,11 +268,11 @@ public extension ImageDownloader {
internal func downloadImageWithURL(URL: NSURL,
retrieveImageTask: RetrieveImageTask?,
- options: KingfisherManager.Options,
+ options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
- if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelledBeforeDownlodStarting {
+ if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelledBeforeDownloadStarting {
return nil
}
@@ -215,12 +280,17 @@ public extension ImageDownloader {
// We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout)
- request.HTTPShouldUsePipelining = true
+ request.HTTPShouldUsePipelining = requestsUsePipeling
self.requestModifier?(request)
// There is a possiblility that request modifier changed the url to `nil` or empty.
- if request.URL == nil || request.URL!.absoluteString.isEmpty {
+ #if swift(>=2.3)
+ let isEmptyUrl = (request.URL == nil || request.URL!.absoluteString == nil || (request.URL!.absoluteString!.isEmpty))
+ #else
+ let isEmptyUrl = (request.URL == nil || request.URL!.absoluteString.isEmpty)
+ #endif
+ if isEmptyUrl {
completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidURL.rawValue, userInfo: nil), imageURL: nil, originalData: nil)
return nil
}
@@ -231,11 +301,13 @@ public extension ImageDownloader {
let dataTask = session.dataTaskWithRequest(request)
fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
- fetchLoad.shouldDecode = options.shouldDecode
- fetchLoad.scale = options.scale
+ fetchLoad.options = options
- dataTask.priority = options.lowPriority ? NSURLSessionTaskPriorityLow : NSURLSessionTaskPriorityDefault
+ dataTask.priority = options?.downloadPriority ?? NSURLSessionTaskPriorityDefault
dataTask.resume()
+
+ // Hold self while the task is executing.
+ self.sessionHandler.downloadHolder = self
}
fetchLoad.downloadTaskCount += 1
@@ -282,12 +354,30 @@ public extension ImageDownloader {
}
}
-// MARK: - NSURLSessionTaskDelegate
-extension ImageDownloader: NSURLSessionDataDelegate {
+// MARK: - NSURLSessionDataDelegate
+
+// See https://github.com/onevcat/Kingfisher/issues/235
+
+/// Delegate class for `NSURLSessionTaskDelegate`.
+/// The session object will hold its delegate until it gets invalidated.
+/// If we use `ImageDownloader` as the session delegate, it will not be released.
+/// So we need an additional handler to break the retain cycle.
+class ImageDownloaderSessionHandler: NSObject, NSURLSessionDataDelegate, AuthenticationChallengeResponable {
+
+ // The holder will keep downloader not released while a data task is being executed.
+ // It will be set when the task started, and reset when the task finished.
+ var downloadHolder: ImageDownloader?
+
/**
This method is exposed since the compiler requests. Do not call it.
*/
- public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
+ internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
+
+ // If server response is not 200,201 or 304, inform the callback handler with InvalidStatusCode error.
+ // InvalidStatusCode error has userInfo which include statusCode and localizedString.
+ if let statusCode = (response as? NSHTTPURLResponse)?.statusCode, let URL = dataTask.originalRequest?.URL where statusCode != 200 && statusCode != 201 && statusCode != 304 {
+ callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidStatusCode.rawValue, userInfo: ["statusCode": statusCode, "localizedStringForStatusCode": NSHTTPURLResponse.localizedStringForStatusCode(statusCode)]), imageURL: URL, originalData: nil)
+ }
completionHandler(NSURLSessionResponseDisposition.Allow)
}
@@ -295,13 +385,19 @@ extension ImageDownloader: NSURLSessionDataDelegate {
/**
This method is exposed since the compiler requests. Do not call it.
*/
- public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
+ internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
- if let URL = dataTask.originalRequest?.URL, fetchLoad = fetchLoadForKey(URL) {
+ guard let downloader = downloadHolder else {
+ return
+ }
+
+ if let URL = dataTask.originalRequest?.URL, fetchLoad = downloader.fetchLoadForKey(URL) {
fetchLoad.responseData.appendData(data)
for callbackPair in fetchLoad.callbacks {
- callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength)
+ dispatch_async(dispatch_get_main_queue(), { () -> Void in
+ callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength)
+ })
}
}
}
@@ -309,7 +405,7 @@ extension ImageDownloader: NSURLSessionDataDelegate {
/**
This method is exposed since the compiler requests. Do not call it.
*/
- public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
+ internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let URL = task.originalRequest?.URL {
if let error = error { // Error happened
@@ -323,42 +419,56 @@ extension ImageDownloader: NSURLSessionDataDelegate {
/**
This method is exposed since the compiler requests. Do not call it.
*/
- public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
+ internal func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
- if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
- if let trustedHosts = trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) {
- let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
- completionHandler(.UseCredential, credential)
- return
- }
+ guard let downloader = downloadHolder else {
+ return
}
- completionHandler(.PerformDefaultHandling, nil)
+ downloader.authenticationChallengeResponder?.downloader(downloader, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
- private func callbackWithImage(image: UIImage?, error: NSError?, imageURL: NSURL, originalData: NSData?) {
- if let callbackPairs = fetchLoadForKey(imageURL)?.callbacks {
+ private func callbackWithImage(image: Image?, error: NSError?, imageURL: NSURL, originalData: NSData?) {
+
+ guard let downloader = downloadHolder else {
+ return
+ }
+
+ if let callbackPairs = downloader.fetchLoadForKey(imageURL)?.callbacks {
+ let options = downloader.fetchLoadForKey(imageURL)?.options ?? KingfisherEmptyOptionsInfo
- self.cleanForURL(imageURL)
+ downloader.cleanForURL(imageURL)
for callbackPair in callbackPairs {
- callbackPair.completionHander?(image: image, error: error, imageURL: imageURL, originalData: originalData)
+ dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
+ callbackPair.completionHander?(image: image, error: error, imageURL: imageURL, originalData: originalData)
+ })
+ }
+
+ if downloader.fetchLoads.isEmpty {
+ downloadHolder = nil
}
}
}
private func processImageForTask(task: NSURLSessionTask, URL: NSURL) {
+
+ guard let downloader = downloadHolder else {
+ return
+ }
+
// We are on main queue when receiving this.
- dispatch_async(processQueue, { () -> Void in
+ dispatch_async(downloader.processQueue, { () -> Void in
- if let fetchLoad = self.fetchLoadForKey(URL) {
+ if let fetchLoad = downloader.fetchLoadForKey(URL) {
- if let image = UIImage.kf_imageWithData(fetchLoad.responseData, scale: fetchLoad.scale) {
+ let options = fetchLoad.options ?? KingfisherEmptyOptionsInfo
+ if let image = Image.kf_imageWithData(fetchLoad.responseData, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) {
- self.delegate?.imageDownloader?(self, didDownloadImage: image, forURL: URL, withResponse: task.response!)
+ downloader.delegate?.imageDownloader?(downloader, didDownloadImage: image, forURL: URL, withResponse: task.response!)
- if fetchLoad.shouldDecode {
- self.callbackWithImage(image.kf_decodedImage(scale: fetchLoad.scale), error: nil, imageURL: URL, originalData: fetchLoad.responseData)
+ if options.backgroundDecode {
+ self.callbackWithImage(image.kf_decodedImage(scale: options.scaleFactor), error: nil, imageURL: URL, originalData: fetchLoad.responseData)
} else {
self.callbackWithImage(image, error: nil, imageURL: URL, originalData: fetchLoad.responseData)
}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/ImagePrefetcher.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImagePrefetcher.swift
new file mode 100644
index 0000000..8695bb7
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImagePrefetcher.swift
@@ -0,0 +1,270 @@
+//
+// ImagePrefetcher.swift
+// Kingfisher
+//
+// Created by Claire Knight on 24/02/2016
+//
+// Copyright (c) 2016 Wei Wang
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+
+#if os(OSX)
+ import AppKit
+#else
+ import UIKit
+#endif
+
+
+/// Progress update block of prefetcher.
+///
+/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
+/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
+/// - `completedResources`: An array of resources that are downloaded and cached successfully.
+public typealias PrefetcherProgressBlock = ((skippedResources: [Resource], failedResources: [Resource], completedResources: [Resource]) -> ())
+
+/// Completion block of prefetcher.
+///
+/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
+/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
+/// - `completedResources`: An array of resources that are downloaded and cached successfully.
+public typealias PrefetcherCompletionHandler = ((skippedResources: [Resource], failedResources: [Resource], completedResources: [Resource]) -> ())
+
+/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
+/// This is useful when you know a list of image resources and want to download them before showing.
+public class ImagePrefetcher {
+
+ /// The maximum concurrent downloads to use when prefetching images. Default is 5.
+ public var maxConcurrentDownloads = 5
+
+ private let prefetchResources: [Resource]
+ private let optionsInfo: KingfisherOptionsInfo
+ private var progressBlock: PrefetcherProgressBlock?
+ private var completionHandler: PrefetcherCompletionHandler?
+
+ private var tasks = [NSURL: RetrieveImageDownloadTask]()
+
+ private var pendingResources: ArraySlice
+ private var skippedResources = [Resource]()
+ private var completedResources = [Resource]()
+ private var failedResources = [Resource]()
+
+ private var stopped = false
+
+ // The created manager used for prefetch. We will use the helper method in manager.
+ private let manager: KingfisherManager
+
+ private var finished: Bool {
+ return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty
+ }
+
+ /**
+ Init an image prefetcher with an array of URLs.
+
+ The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
+ After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
+ The images already cached will be skipped without downloading again.
+
+ - parameter urls: The URLs which should be prefetched.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
+ - parameter completionHandler: Called when the whole prefetching process finished.
+
+ - returns: An `ImagePrefetcher` object.
+
+ - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
+ the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
+ Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
+ */
+ public convenience init(urls: [NSURL],
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: PrefetcherProgressBlock? = nil,
+ completionHandler: PrefetcherCompletionHandler? = nil)
+ {
+ let resources = urls.map { Resource(downloadURL: $0) }
+ self.init(resources: resources, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
+ }
+
+ /**
+ Init an image prefetcher with an array of resources.
+
+ The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable.
+ After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
+ The images already cached will be skipped without downloading again.
+
+ - parameter resources: The resources which should be prefetched. See `Resource` type for more.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
+ - parameter completionHandler: Called when the whole prefetching process finished.
+
+ - returns: An `ImagePrefetcher` object.
+
+ - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
+ the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
+ Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
+ */
+ public init(resources: [Resource],
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: PrefetcherProgressBlock? = nil,
+ completionHandler: PrefetcherCompletionHandler? = nil)
+ {
+ prefetchResources = resources
+ pendingResources = ArraySlice(resources)
+
+ // We want all callbacks from main queue, so we ignore the call back queue in options
+ let optionsInfoWithoutQueue = optionsInfo?.kf_removeAllMatchesIgnoringAssociatedValue(.CallbackDispatchQueue(nil))
+ self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo
+
+ let cache = self.optionsInfo.targetCache ?? ImageCache.defaultCache
+ let downloader = self.optionsInfo.downloader ?? ImageDownloader.defaultDownloader
+ manager = KingfisherManager(downloader: downloader, cache: cache)
+
+ self.progressBlock = progressBlock
+ self.completionHandler = completionHandler
+ }
+
+ /**
+ Start to download the resources and cache them. This can be useful for background downloading
+ of assets that are required for later use in an app. This code will not try and update any UI
+ with the results of the process.
+ */
+ public func start()
+ {
+ // Since we want to handle the resources cancellation in main thread only.
+ dispatch_async_safely_to_main_queue { () -> () in
+
+ guard !self.stopped else {
+ assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
+ self.handleComplete()
+ return
+ }
+
+ guard self.maxConcurrentDownloads > 0 else {
+ assertionFailure("There should be concurrent downloads value should be at least 1.")
+ self.handleComplete()
+ return
+ }
+
+ guard self.prefetchResources.count > 0 else {
+ self.handleComplete()
+ return
+ }
+
+ let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
+ for _ in 0 ..< initialConcurentDownloads {
+ if let resource = self.pendingResources.popFirst() {
+ self.startPrefetchingResource(resource)
+ }
+ }
+ }
+ }
+
+
+ /**
+ Stop current downloading progress, and cancel any future prefetching activity that might be occuring.
+ */
+ public func stop() {
+ dispatch_async_safely_to_main_queue {
+
+ if self.finished {
+ return
+ }
+
+ self.stopped = true
+ self.tasks.forEach { (_, task) -> () in
+ task.cancel()
+ }
+ }
+ }
+
+ func downloadAndCacheResource(resource: Resource) {
+
+ let downloadTaskCompletionHandler:CompletionHandler = { (image, error, _, _) -> () in
+ self.tasks.removeValueForKey(resource.downloadURL)
+
+ if let _ = error {
+ self.failedResources.append(resource)
+ } else {
+ self.completedResources.append(resource)
+ }
+
+ self.reportProgress()
+
+ if self.stopped {
+ if self.tasks.isEmpty {
+ self.failedResources.appendContentsOf(self.pendingResources)
+ self.handleComplete()
+ }
+ } else {
+ self.reportCompletionOrStartNext()
+ }
+ }
+
+ let downloadTask = manager.downloadAndCacheImageWithURL(resource.downloadURL,
+ forKey: resource.cacheKey,
+ retrieveImageTask: RetrieveImageTask(),
+ progressBlock: nil,
+ completionHandler: downloadTaskCompletionHandler,
+ options: optionsInfo)
+
+ if let downloadTask = downloadTask {
+ tasks[resource.downloadURL] = downloadTask
+ }
+ }
+
+ func appendCachedResource(resource: Resource) {
+ skippedResources.append(resource)
+
+ reportProgress()
+ reportCompletionOrStartNext()
+ }
+
+ func startPrefetchingResource(resource: Resource)
+ {
+ if optionsInfo.forceRefresh {
+ downloadAndCacheResource(resource)
+ } else {
+ let alreadyInCache = manager.cache.isImageCachedForKey(resource.cacheKey).cached
+ if alreadyInCache {
+ appendCachedResource(resource)
+ } else {
+ downloadAndCacheResource(resource)
+ }
+ }
+ }
+
+ func reportProgress() {
+ progressBlock?(skippedResources: skippedResources, failedResources: failedResources, completedResources: completedResources)
+ }
+
+ func reportCompletionOrStartNext() {
+ if let resource = pendingResources.popFirst() {
+ startPrefetchingResource(resource)
+ } else {
+ guard self.tasks.isEmpty else { return }
+ handleComplete()
+ }
+ }
+
+ func handleComplete() {
+ completionHandler?(skippedResources: skippedResources, failedResources: failedResources, completedResources: completedResources)
+ completionHandler = nil
+ progressBlock = nil
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageTransition.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageTransition.swift
similarity index 90%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageTransition.swift
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/ImageTransition.swift
index d7d9b41..6630fef 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageTransition.swift
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageTransition.swift
@@ -4,7 +4,7 @@
//
// Created by Wei Wang on 15/9/18.
//
-// Copyright (c) 2015 Wei Wang
+// Copyright (c) 2016 Wei Wang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -24,6 +24,27 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+#if os(OSX)
+// Not implemented for OSX and watchOS yet.
+
+import AppKit
+
+public enum ImageTransition {
+ case None
+ var duration: NSTimeInterval {
+ return 0
+ }
+}
+
+#elseif os(watchOS)
+import UIKit
+public enum ImageTransition {
+ case None
+ var duration: NSTimeInterval {
+ return 0
+ }
+}
+#else
import UIKit
/**
@@ -99,3 +120,4 @@ public enum ImageTransition {
}
}
}
+#endif
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
new file mode 100644
index 0000000..62b5007
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
@@ -0,0 +1,291 @@
+//
+// ImageView+Kingfisher.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/6.
+//
+// Copyright (c) 2016 Wei Wang
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+
+#if os(OSX)
+import AppKit
+typealias ImageView = NSImageView
+#else
+import UIKit
+typealias ImageView = UIImageView
+#endif
+
+// MARK: - Set Images
+/**
+* Set image to use from web.
+*/
+extension ImageView {
+
+ /**
+ Set an image with a URL, a placeholder image, options, progress handler and completion handler.
+
+ - parameter URL: The URL of image.
+ - parameter placeholderImage: A placeholder image when retrieving the image at URL.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called when the image downloading progress gets updated.
+ - parameter completionHandler: Called when the image retrieved and set.
+
+ - returns: A task represents the retrieving process.
+
+ - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
+ The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
+ */
+
+ public func kf_setImageWithURL(URL: NSURL?,
+ placeholderImage: Image? = nil,
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
+ {
+ let resource = URL.map { Resource(downloadURL: $0) }
+ return kf_setImageWithResource(resource,
+ placeholderImage: placeholderImage,
+ optionsInfo: optionsInfo,
+ progressBlock: progressBlock,
+ completionHandler: completionHandler)
+ }
+
+
+ /**
+ Set an image with a URL, a placeholder image, options, progress handler and completion handler.
+
+ - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
+ - parameter placeholderImage: A placeholder image when retrieving the image at URL.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called when the image downloading progress gets updated.
+ - parameter completionHandler: Called when the image retrieved and set.
+
+ - returns: A task represents the retrieving process.
+
+ - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
+ The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
+ */
+ public func kf_setImageWithResource(resource: Resource?,
+ placeholderImage: Image? = nil,
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
+ {
+ image = placeholderImage
+
+ guard let resource = resource else {
+ completionHandler?(image: nil, error: nil, cacheType: .None, imageURL: nil)
+ return RetrieveImageTask.emptyTask
+ }
+
+ let maybeIndicator = kf_indicator
+ maybeIndicator?.startAnimatingView()
+
+ kf_setWebURL(resource.downloadURL)
+
+ var options = optionsInfo ?? []
+ if shouldPreloadAllGIF() {
+ options.append(.PreloadAllGIFData)
+ }
+
+ let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: options,
+ progressBlock: { receivedSize, totalSize in
+ if let progressBlock = progressBlock {
+ progressBlock(receivedSize: receivedSize, totalSize: totalSize)
+ }
+ },
+ completionHandler: {[weak self] image, error, cacheType, imageURL in
+
+ dispatch_async_safely_to_main_queue {
+ guard let sSelf = self where imageURL == sSelf.kf_webURL else {
+ return
+ }
+
+ sSelf.kf_setImageTask(nil)
+
+ guard let image = image else {
+ maybeIndicator?.stopAnimatingView()
+ completionHandler?(image: nil, error: error, cacheType: cacheType, imageURL: imageURL)
+ return
+ }
+
+ if let transitionItem = options.kf_firstMatchIgnoringAssociatedValue(.Transition(.None)),
+ case .Transition(let transition) = transitionItem where ( options.forceTransition || cacheType == .None) {
+ #if !os(OSX)
+ UIView.transitionWithView(sSelf, duration: 0.0, options: [],
+ animations: {
+ maybeIndicator?.stopAnimatingView()
+ },
+ completion: { finished in
+ UIView.transitionWithView(sSelf, duration: transition.duration,
+ options: [transition.animationOptions, .AllowUserInteraction],
+ animations: {
+ // Set image property in the animation.
+ transition.animations?(sSelf, image)
+ },
+ completion: { finished in
+ transition.completion?(finished)
+ completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
+ })
+ })
+ #endif
+ } else {
+ maybeIndicator?.stopAnimatingView()
+ sSelf.image = image
+ completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
+ }
+ }
+ })
+
+ kf_setImageTask(task)
+
+ return task
+ }
+}
+
+extension ImageView {
+ func shouldPreloadAllGIF() -> Bool {
+ return true
+ }
+}
+
+extension ImageView {
+ /**
+ Cancel the image download task bounded to the image view if it is running.
+ Nothing will happen if the downloading has already finished.
+ */
+ public func kf_cancelDownloadTask() {
+ kf_imageTask?.downloadTask?.cancel()
+ }
+}
+
+/**
+ Enum for the types of indicators that the user can choose from.
+ */
+public enum IndicatorType {
+ /// No indicator.
+ case None
+ /// Use system activity indicator.
+ case Activity
+ /// Use an image as indicator. GIF is supported.
+ case Image(imageData: NSData)
+ /// Use a custom indicator, which conforms to the `Indicator` protocol.
+ case Custom(indicator: Indicator)
+}
+
+// MARK: - Associated Object
+private var lastURLKey: Void?
+private var indicatorKey: Void?
+private var indicatorTypeKey: Void?
+private var imageTaskKey: Void?
+
+extension ImageView {
+ /// Get the image URL binded to this image view.
+ public var kf_webURL: NSURL? {
+ return objc_getAssociatedObject(self, &lastURLKey) as? NSURL
+ }
+
+ private func kf_setWebURL(URL: NSURL) {
+ objc_setAssociatedObject(self, &lastURLKey, URL, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+
+
+ /// Whether show an animating activity indicator when the image view is loading an image or not.
+ /// Default is false.
+ public var kf_showIndicatorWhenLoading: Bool {
+ get {
+ switch kf_indicatorType {
+ case .None:
+ return false
+ case .Activity: fallthrough
+ case .Image(_): fallthrough
+ case .Custom(_): return true
+ }
+ }
+
+ set {
+ if kf_showIndicatorWhenLoading == newValue {
+ return
+ } else {
+ kf_indicatorType = newValue ? .Activity : .None
+ }
+ }
+ }
+
+ /// Holds which indicator type is going to be used.
+ /// Default is .None
+ public var kf_indicatorType: IndicatorType {
+ get {
+ let indicator = (objc_getAssociatedObject(self, &indicatorTypeKey) as? Box)?.value
+ return indicator ?? .None
+ }
+
+ set {
+ switch newValue {
+ case .None:
+ kf_indicator = nil
+ case .Activity:
+ kf_indicator = ActivityIndicator()
+ case .Image(let data):
+ kf_indicator = ImageIndicator(imageData: data)
+ case .Custom(let indicator):
+ kf_indicator = indicator
+ }
+
+ objc_setAssociatedObject(self, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+ }
+
+ /// `kf_indicator` holds any type that conforms to the protocol `Indicator`.
+ /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
+ /// Everything will be `nil` if `kf_indicatorType` is .None.
+ public private(set) var kf_indicator: Indicator? {
+ get {
+ return (objc_getAssociatedObject(self, &indicatorKey) as? Box)?.value
+ }
+
+ set {
+ // Remove previous
+ if let previousIndicator = kf_indicator {
+ previousIndicator.view.removeFromSuperview()
+ }
+
+ // Add new
+ if var newIndicator = newValue {
+ newIndicator.view.frame = self.frame
+ newIndicator.viewCenter = CGPoint(x: bounds.midX, y: bounds.midY)
+ newIndicator.view.hidden = true
+ self.addSubview(newIndicator.view)
+ }
+
+ // Save in associated object
+ objc_setAssociatedObject(self, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+ }
+
+ private var kf_imageTask: RetrieveImageTask? {
+ return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask
+ }
+
+ private func kf_setImageTask(task: RetrieveImageTask?) {
+ objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/Indicator.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/Indicator.swift
new file mode 100644
index 0000000..2d05e96
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/Indicator.swift
@@ -0,0 +1,176 @@
+//
+// Indicator.swift
+// Kingfisher
+//
+// Created by João D. Moreira on 30/08/16.
+//
+// Copyright (c) 2016 Wei Wang
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#if os(OSX)
+ import AppKit
+#else
+ import UIKit
+#endif
+
+#if os(OSX)
+ public typealias IndicatorView = NSView
+#else
+ public typealias IndicatorView = UIView
+#endif
+
+// MARK: - Indicator Protocol
+public protocol Indicator {
+ func startAnimatingView()
+ func stopAnimatingView()
+
+ var viewCenter: CGPoint { get set }
+ var view: IndicatorView { get }
+}
+
+extension Indicator {
+ #if os(OSX)
+ var viewCenter: CGPoint {
+ get {
+ let frame = view.frame
+ return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 )
+ }
+ set {
+ let frame = view.frame
+ let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0,
+ y: newValue.y - frame.size.height / 2.0,
+ width: frame.size.width,
+ height: frame.size.height)
+ view.frame = newFrame
+ }
+ }
+ #else
+ var viewCenter: CGPoint {
+ get {
+ return view.center
+ }
+ set {
+ view.center = newValue
+ }
+ }
+ #endif
+}
+
+// MARK: - ActivityIndicator
+// Displays a NSProgressIndicator / UIActivityIndicatorView
+struct ActivityIndicator: Indicator {
+
+ #if os(OSX)
+ private let activityIndicatorView: NSProgressIndicator
+ #else
+ private let activityIndicatorView: UIActivityIndicatorView
+ #endif
+
+ var view: IndicatorView {
+ return activityIndicatorView
+ }
+
+ func startAnimatingView() {
+ #if os(OSX)
+ activityIndicatorView.startAnimation(nil)
+ #else
+ activityIndicatorView.startAnimating()
+ #endif
+ activityIndicatorView.hidden = false
+ }
+
+ func stopAnimatingView() {
+ #if os(OSX)
+ activityIndicatorView.stopAnimation(nil)
+ #else
+ activityIndicatorView.stopAnimating()
+ #endif
+ activityIndicatorView.hidden = true
+ }
+
+ init() {
+ #if os(OSX)
+ activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
+
+ #if swift(>=2.3)
+ activityIndicatorView.controlSize = .Small
+ #else
+ activityIndicatorView.controlSize = .SmallControlSize
+ #endif
+ activityIndicatorView.style = .SpinningStyle
+ #else
+ #if os(tvOS)
+ let indicatorStyle = UIActivityIndicatorViewStyle.White
+ #else
+ let indicatorStyle = UIActivityIndicatorViewStyle.Gray
+ #endif
+ activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle)
+ activityIndicatorView.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin, .FlexibleTopMargin]
+ #endif
+ }
+}
+
+// MARK: - ImageIndicator
+// Displays an ImageView. Supports gif
+struct ImageIndicator: Indicator {
+ private let animatedImageIndicatorView: ImageView
+
+ var view: IndicatorView {
+ return animatedImageIndicatorView
+ }
+
+ init(imageData data: NSData) {
+
+ let image = Image.kf_imageWithData(data, scale: 1.0, preloadAllGIFData: true)
+ animatedImageIndicatorView = ImageView()
+ animatedImageIndicatorView.image = image
+
+ #if os(OSX)
+ // Need for gif to animate on OSX
+ self.animatedImageIndicatorView.imageScaling = .ScaleNone
+ self.animatedImageIndicatorView.canDrawSubviewsIntoLayer = true
+ #else
+ animatedImageIndicatorView.contentMode = .Center
+
+ animatedImageIndicatorView.autoresizingMask = [.FlexibleLeftMargin,
+ .FlexibleRightMargin,
+ .FlexibleBottomMargin,
+ .FlexibleTopMargin]
+ #endif
+ }
+
+ func startAnimatingView() {
+ #if os(OSX)
+ animatedImageIndicatorView.animates = true
+ #else
+ animatedImageIndicatorView.startAnimating()
+ #endif
+ animatedImageIndicatorView.hidden = false
+ }
+
+ func stopAnimatingView() {
+ #if os(OSX)
+ animatedImageIndicatorView.animates = false
+ #else
+ animatedImageIndicatorView.stopAnimating()
+ #endif
+ animatedImageIndicatorView.hidden = true
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/Kingfisher.h b/iOSSwiftStarter/Pods/Kingfisher/Sources/Kingfisher.h
similarity index 94%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/Kingfisher.h
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/Kingfisher.h
index 8e85128..05350ce 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/Kingfisher.h
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/Kingfisher.h
@@ -4,7 +4,7 @@
//
// Created by Wei Wang on 15/4/6.
//
-// Copyright (c) 2015 Wei Wang
+// Copyright (c) 2016 Wei Wang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -24,7 +24,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-#import
+#import
//! Project version number for Kingfisher.
FOUNDATION_EXPORT double KingfisherVersionNumber;
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherManager.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/KingfisherManager.swift
similarity index 65%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherManager.swift
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/KingfisherManager.swift
index 60ad24d..a75f7c9 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/KingfisherManager.swift
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/KingfisherManager.swift
@@ -4,7 +4,7 @@
//
// Created by Wei Wang on 15/4/6.
//
-// Copyright (c) 2015 Wei Wang
+// Copyright (c) 2016 Wei Wang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -24,18 +24,24 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+#if os(OSX)
+import AppKit
+#else
import UIKit
+#endif
public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
-public typealias CompletionHandler = ((image: UIImage?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
+public typealias CompletionHandler = ((image: Image?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
/// RetrieveImageTask represents a task of image retrieving process.
/// It contains an async task of getting image from disk and from network.
public class RetrieveImageTask {
+ static let emptyTask = RetrieveImageTask()
+
// If task is canceled before the download task started (which means the `downloadTask` is nil),
// the download task should not begin.
- var cancelledBeforeDownlodStarting: Bool = false
+ var cancelledBeforeDownloadStarting: Bool = false
/// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task.
public var diskRetrieveTask: RetrieveImageDiskTask?
@@ -57,7 +63,7 @@ public class RetrieveImageTask {
if let downloadTask = downloadTask {
downloadTask.cancel()
} else {
- cancelledBeforeDownlodStarting = true
+ cancelledBeforeDownloadStarting = true
}
}
}
@@ -70,17 +76,6 @@ private let instance = KingfisherManager()
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
-
- /// Options to control some downloader and cache behaviors.
- public typealias Options = (forceRefresh: Bool, lowPriority: Bool, cacheMemoryOnly: Bool, shouldDecode: Bool, queue: dispatch_queue_t!, scale: CGFloat)
-
- /// A preset option tuple with all value set to `false`.
- public static let OptionsNone: Options = {
- return (forceRefresh: false, lowPriority: false, cacheMemoryOnly: false, shouldDecode: false, queue: dispatch_get_main_queue(), scale: 1.0)
- }()
-
- /// The default set of options to be used by the manager to control some downloader and cache behaviors.
- public static var DefaultOptions: Options = OptionsNone
/// Shared manager used by the extensions across Kingfisher.
public class var sharedManager: KingfisherManager {
@@ -96,11 +91,15 @@ public class KingfisherManager {
/**
Default init method
- - returns: A Kingfisher manager object with default cache and default downloader.
+ - returns: A Kingfisher manager object with default cache, default downloader, and default prefetcher.
*/
- public init() {
- cache = ImageCache.defaultCache
- downloader = ImageDownloader.defaultDownloader
+ public convenience init() {
+ self.init(downloader: ImageDownloader.defaultDownloader, cache: ImageCache.defaultCache)
+ }
+
+ init(downloader: ImageDownloader, cache: ImageCache) {
+ self.downloader = downloader
+ self.cache = cache
}
/**
@@ -122,30 +121,21 @@ public class KingfisherManager {
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let task = RetrieveImageTask()
-
- // There is a bug in Swift compiler which prevents to write `let (options, targetCache) = parseOptionsInfo(optionsInfo)`
- // It will cause a compiler error.
- let parsedOptions = parseOptionsInfo(optionsInfo)
- let (options, targetCache, downloader) = (parsedOptions.0, parsedOptions.1, parsedOptions.2)
-
- if options.forceRefresh {
+
+ if let optionsInfo = optionsInfo where optionsInfo.forceRefresh {
downloadAndCacheImageWithURL(resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
- options: options,
- targetCache: targetCache,
- downloader: downloader)
+ options: optionsInfo)
} else {
tryToRetrieveImageFromCacheForKey(resource.cacheKey,
withURL: resource.downloadURL,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
- options: options,
- targetCache: targetCache,
- downloader: downloader)
+ options: optionsInfo)
}
return task
@@ -180,16 +170,16 @@ public class KingfisherManager {
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
- options: Options,
- targetCache: ImageCache,
- downloader: ImageDownloader)
+ options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask?
{
- downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options,
+ let downloader = options?.downloader ?? self.downloader
+ return downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options,
progressBlock: { receivedSize, totalSize in
progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
},
completionHandler: { image, error, imageURL, originalData in
+ let targetCache = options?.targetCache ?? self.cache
if let error = error where error.code == KingfisherError.NotModified.rawValue {
// Not modified. Try to find the image from cache.
// (The image should be in cache. It should be guaranteed by the framework users.)
@@ -201,12 +191,12 @@ public class KingfisherManager {
}
if let image = image, originalData = originalData {
- targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: !options.cacheMemoryOnly, completionHandler: nil)
+ targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: !(options?.cacheMemoryOnly ?? false), completionHandler: nil)
}
-
+
completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
- }
- )
+
+ })
}
func tryToRetrieveImageFromCacheForKey(key: String,
@@ -214,75 +204,32 @@ public class KingfisherManager {
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
- options: Options,
- targetCache: ImageCache,
- downloader: ImageDownloader)
+ options: KingfisherOptionsInfo?)
{
let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
// Break retain cycle created inside diskTask closure below
retrieveImageTask.diskRetrieveTask = nil
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
+
+ let targetCache = options?.targetCache ?? cache
let diskTask = targetCache.retrieveImageForKey(key, options: options,
completionHandler: { image, cacheType in
if image != nil {
diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: URL)
+ } else if let options = options where options.onlyFromCache {
+ let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotCached.rawValue, userInfo: nil)
+ diskTaskCompletionHandler(image: nil, error: error, cacheType:.None, imageURL: URL)
} else {
self.downloadAndCacheImageWithURL(URL,
forKey: key,
retrieveImageTask: retrieveImageTask,
progressBlock: progressBlock,
completionHandler: diskTaskCompletionHandler,
- options: options,
- targetCache: targetCache,
- downloader: downloader)
+ options: options)
}
}
)
retrieveImageTask.diskRetrieveTask = diskTask
}
-
- func parseOptionsInfo(optionsInfo: KingfisherOptionsInfo?) -> (Options, ImageCache, ImageDownloader) {
- var options = KingfisherManager.DefaultOptions
- var targetCache = self.cache
- var targetDownloader = self.downloader
-
- guard let optionsInfo = optionsInfo else {
- return (options, targetCache, targetDownloader)
- }
-
- if let optionsItem = optionsInfo.kf_firstMatchIgnoringAssociatedValue(.Options(.None)), case .Options(let optionsInOptionsInfo) = optionsItem {
-
- let queue = optionsInOptionsInfo.contains(KingfisherOptions.BackgroundCallback) ? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) : KingfisherManager.DefaultOptions.queue
- let scale = optionsInOptionsInfo.contains(KingfisherOptions.ScreenScale) ? UIScreen.mainScreen().scale : KingfisherManager.DefaultOptions.scale
-
- options = (forceRefresh: optionsInOptionsInfo.contains(KingfisherOptions.ForceRefresh),
- lowPriority: optionsInOptionsInfo.contains(KingfisherOptions.LowPriority),
- cacheMemoryOnly: optionsInOptionsInfo.contains(KingfisherOptions.CacheMemoryOnly),
- shouldDecode: optionsInOptionsInfo.contains(KingfisherOptions.BackgroundDecode),
- queue: queue, scale: scale)
- }
-
- if let optionsItem = optionsInfo.kf_firstMatchIgnoringAssociatedValue(.TargetCache(self.cache)), case .TargetCache(let cache) = optionsItem {
- targetCache = cache
- }
-
- if let optionsItem = optionsInfo.kf_firstMatchIgnoringAssociatedValue(.Downloader(self.downloader)), case .Downloader(let downloader) = optionsItem {
- targetDownloader = downloader
- }
-
- return (options, targetCache, targetDownloader)
- }
-}
-
-// MARK: - Deprecated
-public extension KingfisherManager {
- @available(*, deprecated=1.2, message="Use -retrieveImageWithURL:optionsInfo:progressBlock:completionHandler: instead.")
- public func retrieveImageWithURL(URL: NSURL,
- options: KingfisherOptions,
- progressBlock: DownloadProgressBlock?,
- completionHandler: CompletionHandler?) -> RetrieveImageTask
- {
- return retrieveImageWithURL(URL, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler)
- }
}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift
new file mode 100644
index 0000000..6932780
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift
@@ -0,0 +1,184 @@
+//
+// KingfisherOptionsInfo.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/23.
+//
+// Copyright (c) 2016 Wei Wang
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#if os(OSX)
+import AppKit
+#else
+import UIKit
+#endif
+
+
+/**
+* KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher.
+*/
+public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
+let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]()
+
+/**
+Items could be added into KingfisherOptionsInfo.
+
+- TargetCache: The associated value of this member should be an ImageCache object. Kingfisher will use the specified cache object when handling related operations, including trying to retrieve the cached images and store the downloaded image to it.
+- Downloader: The associated value of this member should be an ImageDownloader object. Kingfisher will use this downloader to download the images.
+- Transition: Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of this enum to animate the image in if it is downloaded from web. The transition will not happen when the image is retrieved from either memory or disk cache by default. If you need to do the transition even when the image being retrieved from cache, set `ForceTransition` as well.
+- DownloadPriority: Associated `Float` value will be set as the priority of image download task. The value for it should be between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used.
+- ForceRefresh: If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource.
+- ForceTransition: If set, setting the image to an image view will happen with transition even when retrieved from cache. See `Transition` option for more.
+- CacheMemoryOnly: If set, `Kingfisher` will only cache the value in memory but not in disk.
+- OnlyFromCache: If set, `Kingfisher` will only try to retrieve the image from cache not from network.
+- BackgroundDecode: Decode the image in background thread before using.
+- CallbackDispatchQueue: The associated value of this member will be used as the target queue of dispatch callbacks when retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks.
+- ScaleFactor: The associated value of this member will be used as the scale factor when converting retrieved data to an image.
+- PreloadAllGIFData: Whether all the GIF data should be preloaded. Default it false, which means following frames will be loaded on need. If true, all the GIF data will be loaded and decoded into memory. This option is mainly used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use corresponding image view type instead of setting this option.
+*/
+public enum KingfisherOptionsInfoItem {
+ case TargetCache(ImageCache?)
+ case Downloader(ImageDownloader?)
+ case Transition(ImageTransition)
+ case DownloadPriority(Float)
+ case ForceRefresh
+ case ForceTransition
+ case CacheMemoryOnly
+ case OnlyFromCache
+ case BackgroundDecode
+ case CallbackDispatchQueue(dispatch_queue_t?)
+ case ScaleFactor(CGFloat)
+ case PreloadAllGIFData
+}
+
+infix operator <== {
+ associativity none
+ precedence 160
+}
+
+// This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values.
+func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool {
+ switch (lhs, rhs) {
+ case (.TargetCache(_), .TargetCache(_)): fallthrough
+ case (.Downloader(_), .Downloader(_)): fallthrough
+ case (.Transition(_), .Transition(_)): fallthrough
+ case (.DownloadPriority(_), .DownloadPriority(_)): fallthrough
+ case (.ForceRefresh, .ForceRefresh): fallthrough
+ case (.ForceTransition, .ForceTransition): fallthrough
+ case (.CacheMemoryOnly, .CacheMemoryOnly): fallthrough
+ case (.OnlyFromCache, .OnlyFromCache): fallthrough
+ case (.BackgroundDecode, .BackgroundDecode): fallthrough
+ case (.CallbackDispatchQueue(_), .CallbackDispatchQueue(_)): fallthrough
+ case (.ScaleFactor(_), .ScaleFactor(_)): fallthrough
+ case (.PreloadAllGIFData, .PreloadAllGIFData): return true
+
+ default: return false
+ }
+}
+
+extension CollectionType where Generator.Element == KingfisherOptionsInfoItem {
+ func kf_firstMatchIgnoringAssociatedValue(target: Generator.Element) -> Generator.Element? {
+ return indexOf { $0 <== target }.flatMap { self[$0] }
+ }
+
+ func kf_removeAllMatchesIgnoringAssociatedValue(target: Generator.Element) -> [Generator.Element] {
+ return self.filter { !($0 <== target) }
+ }
+}
+
+extension CollectionType where Generator.Element == KingfisherOptionsInfoItem {
+ var targetCache: ImageCache? {
+ if let item = kf_firstMatchIgnoringAssociatedValue(.TargetCache(nil)),
+ case .TargetCache(let cache) = item
+ {
+ return cache
+ }
+ return nil
+ }
+
+ var downloader: ImageDownloader? {
+ if let item = kf_firstMatchIgnoringAssociatedValue(.Downloader(nil)),
+ case .Downloader(let downloader) = item
+ {
+ return downloader
+ }
+ return nil
+ }
+
+ var transition: ImageTransition {
+ if let item = kf_firstMatchIgnoringAssociatedValue(.Transition(.None)),
+ case .Transition(let transition) = item
+ {
+ return transition
+ }
+ return ImageTransition.None
+ }
+
+ var downloadPriority: Float {
+ if let item = kf_firstMatchIgnoringAssociatedValue(.DownloadPriority(0)),
+ case .DownloadPriority(let priority) = item
+ {
+ return priority
+ }
+ return NSURLSessionTaskPriorityDefault
+ }
+
+ var forceRefresh: Bool {
+ return contains{ $0 <== .ForceRefresh }
+ }
+
+ var forceTransition: Bool {
+ return contains{ $0 <== .ForceTransition }
+ }
+
+ var cacheMemoryOnly: Bool {
+ return contains{ $0 <== .CacheMemoryOnly }
+ }
+
+ var onlyFromCache: Bool {
+ return contains{ $0 <== .OnlyFromCache }
+ }
+
+ var backgroundDecode: Bool {
+ return contains{ $0 <== .BackgroundDecode }
+ }
+
+ var preloadAllGIFData: Bool {
+ return contains { $0 <== .PreloadAllGIFData }
+ }
+
+ var callbackDispatchQueue: dispatch_queue_t {
+ if let item = kf_firstMatchIgnoringAssociatedValue(.CallbackDispatchQueue(nil)),
+ case .CallbackDispatchQueue(let queue) = item
+ {
+ return queue ?? dispatch_get_main_queue()
+ }
+ return dispatch_get_main_queue()
+ }
+
+ var scaleFactor: CGFloat {
+ if let item = kf_firstMatchIgnoringAssociatedValue(.ScaleFactor(0)),
+ case .ScaleFactor(let scale) = item
+ {
+ return scale
+ }
+ return 1.0
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/Resource.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/Resource.swift
similarity index 66%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/Resource.swift
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/Resource.swift
index caf2c77..8c5479c 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/Resource.swift
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/Resource.swift
@@ -4,7 +4,7 @@
//
// Created by Wei Wang on 15/4/6.
//
-// Copyright (c) 2015 Wei Wang
+// Copyright (c) 2016 Wei Wang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -26,12 +26,33 @@
import Foundation
+/**
+ Resource is a simple combination of `downloadURL` and `cacheKey`.
+
+ When passed to image view set methods, Kingfisher will try to download the target
+ image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache.
+ */
public struct Resource {
+ /// The key used in cache.
public let cacheKey: String
+
+ /// The target image URL.
public let downloadURL: NSURL
+ /**
+ Create a resource.
+
+ - parameter downloadURL: The target image URL.
+ - parameter cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key.
+
+ - returns: A resource.
+ */
public init(downloadURL: NSURL, cacheKey: String? = nil) {
self.downloadURL = downloadURL
+ #if swift(>=2.3)
+ self.cacheKey = cacheKey ?? downloadURL.absoluteString!
+ #else
self.cacheKey = cacheKey ?? downloadURL.absoluteString
+ #endif
}
}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/String+MD5.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/String+MD5.swift
similarity index 64%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/String+MD5.swift
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/String+MD5.swift
index 8a3cb08..553b8b7 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/String+MD5.swift
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/String+MD5.swift
@@ -2,12 +2,9 @@
// String+MD5.swift
// Kingfisher
//
-// This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift
-// which is a modified version of CryptoSwift:
-//
// To date, adding CommonCrypto to a Swift framework is problematic. See:
// http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
-// We're using a subset of CryptoSwift as a (temporary?) alternative.
+// We're using a subset and modified version of CryptoSwift as an alternative.
// The following is an altered source version that only includes MD5. The original software can be found at:
// https://github.com/krzyzanowskim/CryptoSwift
// This is the original copyright notice:
@@ -25,13 +22,17 @@ Permission is granted to anyone to use this software for any purpose,including c
import Foundation
extension String {
- func kf_MD5() -> String {
+ var kf_MD5: String {
if let data = dataUsingEncoding(NSUTF8StringEncoding) {
- let MD5Calculator = MD5(data)
+ let MD5Calculator = MD5(Array(UnsafeBufferPointer(start: UnsafePointer(data.bytes), count: data.length)))
let MD5Data = MD5Calculator.calculate()
- let resultBytes = UnsafeMutablePointer(MD5Data.bytes)
- let resultEnumerator = UnsafeBufferPointer(start: resultBytes, count: MD5Data.length)
- return resultEnumerator.reduce(""){ $0 + String(format: "%02x", $1) }
+
+ let MD5String = NSMutableString()
+ for c in MD5Data {
+ MD5String.appendFormat("%02x", c)
+ }
+ return MD5String as String
+
} else {
return self
}
@@ -74,49 +75,98 @@ extension NSMutableData {
}
-class HashBase {
-
- var message: NSData
-
- init(_ message: NSData) {
- self.message = message
- }
+protocol HashProtocol {
+ var message: Array { get }
/** Common part for hash calculation. Prepare header data. */
- func prepare(len: Int = 64) -> NSMutableData {
- let tmpMessage: NSMutableData = NSMutableData(data: self.message)
+ func prepare(len: Int) -> Array
+}
+
+extension HashProtocol {
+
+ func prepare(len: Int) -> Array {
+ var tmpMessage = message
// Step 1. Append Padding Bits
- tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
+ tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
- var msgLength = tmpMessage.length
+ var msgLength = tmpMessage.count
var counter = 0
+
while msgLength % len != (len - 8) {
- counter++
- msgLength++
+ counter += 1
+ msgLength += 1
}
- let bufZeros = UnsafeMutablePointer(calloc(counter, sizeof(UInt8)))
- tmpMessage.appendBytes(bufZeros, length: counter)
-
- bufZeros.destroy()
- bufZeros.dealloc(1)
+ tmpMessage += Array(count: counter, repeatedValue: 0)
return tmpMessage
}
}
+func toUInt32Array(slice: ArraySlice) -> Array {
+ var result = Array()
+ result.reserveCapacity(16)
+
+ for idx in slice.startIndex.stride(to: slice.endIndex, by: sizeof(UInt32)) {
+ let d0 = UInt32(slice[idx.advancedBy(3)]) << 24
+ let d1 = UInt32(slice[idx.advancedBy(2)]) << 16
+ let d2 = UInt32(slice[idx.advancedBy(1)]) << 8
+ let d3 = UInt32(slice[idx])
+ let val: UInt32 = d0 | d1 | d2 | d3
+
+ result.append(val)
+ }
+ return result
+}
+
+struct BytesGenerator: GeneratorType {
+
+ let chunkSize: Int
+ let data: [UInt8]
+
+ init(chunkSize: Int, data: [UInt8]) {
+ self.chunkSize = chunkSize
+ self.data = data
+ }
+
+ var offset = 0
+
+ mutating func next() -> ArraySlice? {
+ let end = min(chunkSize, data.count - offset)
+ let result = data[offset.. 0 ? result : nil
+ }
+}
+
+struct BytesSequence: SequenceType {
+ let chunkSize: Int
+ let data: [UInt8]
+
+ func generate() -> BytesGenerator {
+ return BytesGenerator(chunkSize: chunkSize, data: data)
+ }
+}
+
func rotateLeft(value: UInt32, bits: UInt32) -> UInt32 {
return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits))
}
-class MD5: HashBase {
+class MD5: HashProtocol {
+
+ static let size = 16 // 128 / 8
+ let message: [UInt8]
+
+ init (_ message: [UInt8]) {
+ self.message = message
+ }
/** specifies the per-round shift amounts */
- private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
- 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
- 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
- 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
+ private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
+ 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
+ 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
+ 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
@@ -136,29 +186,27 @@ class MD5: HashBase {
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
- private let hashs: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
+ private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
- func calculate() -> NSData {
- let tmpMessage = prepare()
+ func calculate() -> [UInt8] {
+ var tmpMessage = prepare(64)
+ tmpMessage.reserveCapacity(tmpMessage.count + 4)
// hash values
- var hh = hashs
+ var hh = hashes
// Step 2. Append Length a 64-bit representation of lengthInBits
- let lengthInBits = (message.length * 8)
+ let lengthInBits = (message.count * 8)
let lengthBytes = lengthInBits.bytes(64 / 8)
- tmpMessage.appendBytes(Array(lengthBytes.reverse()))
-
+ tmpMessage += lengthBytes.reverse()
+
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
- var leftMessageBytes = tmpMessage.length
- for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) {
- let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes, leftMessageBytes)))
-
+
+ for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
- var M: [UInt32] = [UInt32](count: 16, repeatedValue: 0)
- let range = NSRange(location:0, length: M.count * sizeof(UInt32))
- chunk.getBytes(UnsafeMutablePointer(M), range: range)
+ var M = toUInt32Array(chunk)
+ assert(M.count == 16, "Invalid array")
// Initialize hash value for this chunk:
var A: UInt32 = hh[0]
@@ -206,12 +254,13 @@ class MD5: HashBase {
hh[3] = hh[3] &+ D
}
- let buf: NSMutableData = NSMutableData()
- hh.forEach({ (item) -> () in
- var i: UInt32 = item.littleEndian
- buf.appendBytes(&i, length: sizeofValue(i))
- })
+ var result = [UInt8]()
+ result.reserveCapacity(hh.count / 4)
- return NSData(data: buf)
+ hh.forEach {
+ let itemLE = $0.littleEndian
+ result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)]
+ }
+ return result
}
}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ThreadHelper.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/ThreadHelper.swift
similarity index 68%
rename from iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ThreadHelper.swift
rename to iOSSwiftStarter/Pods/Kingfisher/Sources/ThreadHelper.swift
index 95c7c81..26818ba 100644
--- a/iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ThreadHelper.swift
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/ThreadHelper.swift
@@ -4,7 +4,7 @@
//
// Created by Wei Wang on 15/10/9.
//
-// Copyright (c) 2015 Wei Wang
+// Copyright (c) 2016 Wei Wang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -26,11 +26,18 @@
import Foundation
-func dispatch_async_safely_main_queue(block: ()->()) {
- if NSThread.isMainThread() {
+func dispatch_async_safely_to_main_queue(block: ()->()) {
+ dispatch_async_safely_to_queue(dispatch_get_main_queue(), block)
+}
+
+// This method will dispatch the `block` to a specified `queue`.
+// If the `queue` is the main queue, and current thread is main thread, the block
+// will be invoked immediately instead of being dispatched.
+func dispatch_async_safely_to_queue(queue: dispatch_queue_t, _ block: ()->()) {
+ if queue === dispatch_get_main_queue() && NSThread.isMainThread() {
block()
} else {
- dispatch_async(dispatch_get_main_queue()) {
+ dispatch_async(queue) {
block()
}
}
diff --git a/iOSSwiftStarter/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift b/iOSSwiftStarter/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift
new file mode 100644
index 0000000..4453af6
--- /dev/null
+++ b/iOSSwiftStarter/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift
@@ -0,0 +1,317 @@
+//
+// UIButton+Kingfisher.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/13.
+//
+// Copyright (c) 2016 Wei Wang
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import UIKit
+
+/**
+* Set image to use from web for a specified state.
+*/
+extension UIButton {
+ /**
+ Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
+
+ - parameter URL: The URL of image for specified state.
+ - parameter state: The state that uses the specified image.
+ - parameter placeholderImage: A placeholder image when retrieving the image at URL.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called when the image downloading progress gets updated.
+ - parameter completionHandler: Called when the image retrieved and set.
+
+ - returns: A task represents the retrieving process.
+
+ - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
+ The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
+ */
+ public func kf_setImageWithURL(URL: NSURL?,
+ forState state: UIControlState,
+ placeholderImage: UIImage? = nil,
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
+ {
+ let resource = URL.map { Resource(downloadURL: $0) }
+ return kf_setImageWithResource(resource,
+ forState: state,
+ placeholderImage: placeholderImage,
+ optionsInfo: optionsInfo,
+ progressBlock: progressBlock,
+ completionHandler: completionHandler)
+ }
+
+
+ /**
+ Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
+
+ - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
+ - parameter state: The state that uses the specified image.
+ - parameter placeholderImage: A placeholder image when retrieving the image at URL.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called when the image downloading progress gets updated.
+ - parameter completionHandler: Called when the image retrieved and set.
+
+ - returns: A task represents the retrieving process.
+
+ - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
+ The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
+ */
+ public func kf_setImageWithResource(resource: Resource?,
+ forState state: UIControlState,
+ placeholderImage: UIImage? = nil,
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
+ {
+ setImage(placeholderImage, forState: state)
+
+ guard let resource = resource else {
+ completionHandler?(image: nil, error: nil, cacheType: .None, imageURL: nil)
+ return RetrieveImageTask.emptyTask
+ }
+
+ kf_setWebURL(resource.downloadURL, forState: state)
+ let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
+ progressBlock: { receivedSize, totalSize in
+ if let progressBlock = progressBlock {
+ progressBlock(receivedSize: receivedSize, totalSize: totalSize)
+ }
+ },
+ completionHandler: {[weak self] image, error, cacheType, imageURL in
+ dispatch_async_safely_to_main_queue {
+ guard let sSelf = self where imageURL == sSelf.kf_webURLForState(state) else {
+ return
+ }
+
+ sSelf.kf_setImageTask(nil)
+
+ if image != nil {
+ sSelf.setImage(image, forState: state)
+ }
+
+ completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
+ }
+ })
+
+ kf_setImageTask(task)
+ return task
+ }
+}
+
+private var lastURLKey: Void?
+private var imageTaskKey: Void?
+
+// MARK: - Runtime for UIButton image
+extension UIButton {
+ /**
+ Get the image URL binded to this button for a specified state.
+
+ - parameter state: The state that uses the specified image.
+
+ - returns: Current URL for image.
+ */
+ public func kf_webURLForState(state: UIControlState) -> NSURL? {
+ return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
+ }
+
+ private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
+ kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
+ }
+
+ private var kf_webURLs: NSMutableDictionary {
+ var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
+ if dictionary == nil {
+ dictionary = NSMutableDictionary()
+ kf_setWebURLs(dictionary!)
+ }
+ return dictionary!
+ }
+
+ private func kf_setWebURLs(URLs: NSMutableDictionary) {
+ objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+
+ private var kf_imageTask: RetrieveImageTask? {
+ return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask
+ }
+
+ private func kf_setImageTask(task: RetrieveImageTask?) {
+ objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+}
+
+/**
+* Set background image to use from web for a specified state.
+*/
+extension UIButton {
+ /**
+ Set the background image to use for a specified state with a URL,
+ a placeholder image, options progress handler and completion handler.
+
+ - parameter URL: The URL of image for specified state.
+ - parameter state: The state that uses the specified image.
+ - parameter placeholderImage: A placeholder image when retrieving the image at URL.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called when the image downloading progress gets updated.
+ - parameter completionHandler: Called when the image retrieved and set.
+
+ - returns: A task represents the retrieving process.
+
+ - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
+ The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
+ */
+ public func kf_setBackgroundImageWithURL(URL: NSURL?,
+ forState state: UIControlState,
+ placeholderImage: UIImage? = nil,
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
+ {
+ let resource = URL.map { Resource(downloadURL: $0) }
+ return kf_setBackgroundImageWithResource(resource,
+ forState: state,
+ placeholderImage: placeholderImage,
+ optionsInfo: optionsInfo,
+ progressBlock: progressBlock,
+ completionHandler: completionHandler)
+ }
+
+
+ /**
+ Set the background image to use for a specified state with a resource,
+ a placeholder image, options progress handler and completion handler.
+
+ - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
+ - parameter state: The state that uses the specified image.
+ - parameter placeholderImage: A placeholder image when retrieving the image at URL.
+ - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ - parameter progressBlock: Called when the image downloading progress gets updated.
+ - parameter completionHandler: Called when the image retrieved and set.
+
+ - returns: A task represents the retrieving process.
+
+ - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
+ The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
+ */
+ public func kf_setBackgroundImageWithResource(resource: Resource?,
+ forState state: UIControlState,
+ placeholderImage: UIImage? = nil,
+ optionsInfo: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
+ {
+ setBackgroundImage(placeholderImage, forState: state)
+
+ guard let resource = resource else {
+ completionHandler?(image: nil, error: nil, cacheType: .None, imageURL: nil)
+ return RetrieveImageTask.emptyTask
+ }
+
+ kf_setBackgroundWebURL(resource.downloadURL, forState: state)
+ let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
+ progressBlock: { receivedSize, totalSize in
+ if let progressBlock = progressBlock {
+ progressBlock(receivedSize: receivedSize, totalSize: totalSize)
+ }
+ },
+ completionHandler: { [weak self] image, error, cacheType, imageURL in
+ dispatch_async_safely_to_main_queue {
+ guard let sSelf = self where imageURL == sSelf.kf_backgroundWebURLForState(state) else {
+ return
+ }
+
+ sSelf.kf_setBackgroundImageTask(nil)
+
+ if image != nil {
+ sSelf.setBackgroundImage(image, forState: state)
+ }
+ completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
+ }
+ })
+
+ kf_setBackgroundImageTask(task)
+ return task
+ }
+}
+
+private var lastBackgroundURLKey: Void?
+private var backgroundImageTaskKey: Void?
+
+// MARK: - Runtime for UIButton background image
+extension UIButton {
+ /**
+ Get the background image URL binded to this button for a specified state.
+
+ - parameter state: The state that uses the specified background image.
+
+ - returns: Current URL for background image.
+ */
+ public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
+ return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
+ }
+
+ private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
+ kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
+ }
+
+ private var kf_backgroundWebURLs: NSMutableDictionary {
+ var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
+ if dictionary == nil {
+ dictionary = NSMutableDictionary()
+ kf_setBackgroundWebURLs(dictionary!)
+ }
+ return dictionary!
+ }
+
+ private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
+ objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+
+ private var kf_backgroundImageTask: RetrieveImageTask? {
+ return objc_getAssociatedObject(self, &backgroundImageTaskKey) as? RetrieveImageTask
+ }
+
+ private func kf_setBackgroundImageTask(task: RetrieveImageTask?) {
+ objc_setAssociatedObject(self, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+}
+
+// MARK: - Cancel image download tasks.
+extension UIButton {
+ /**
+ Cancel the image download task bounded to the image view if it is running.
+ Nothing will happen if the downloading has already finished.
+ */
+ public func kf_cancelImageDownloadTask() {
+ kf_imageTask?.downloadTask?.cancel()
+ }
+
+ /**
+ Cancel the background image download task bounded to the image view if it is running.
+ Nothing will happen if the downloading has already finished.
+ */
+ public func kf_cancelBackgroundImageDownloadTask() {
+ kf_backgroundImageTask?.downloadTask?.cancel()
+ }
+}
diff --git a/iOSSwiftStarter/Pods/Manifest.lock b/iOSSwiftStarter/Pods/Manifest.lock
index 1b7f2d4..1841449 100644
--- a/iOSSwiftStarter/Pods/Manifest.lock
+++ b/iOSSwiftStarter/Pods/Manifest.lock
@@ -1,17 +1,17 @@
PODS:
- - Alamofire (3.1.4)
- - AlamofireObjectMapper (2.1.0):
- - Alamofire (~> 3.1.0)
+ - Alamofire (3.5.1)
+ - AlamofireObjectMapper (3.0.2):
+ - Alamofire (~> 3.2)
- ObjectMapper (~> 1.0)
- AsyncSwift (1.6.4)
- CoreStore (1.6.10):
- GCDKit (= 1.2.5)
- GCDKit (1.2.5)
- Hakuba (2.1.1)
- - Kingfisher (1.9.2)
+ - Kingfisher (2.6.1)
- Kugel (0.1.0)
- Nimble (4.0.1)
- - ObjectMapper (1.3.0)
+ - ObjectMapper (1.5.0)
- Quick (0.9.2)
- ReactKit (0.12.0):
- SwiftTask (~> 4.0.0)
@@ -19,13 +19,13 @@ PODS:
- SwiftTask (4.0.0)
DEPENDENCIES:
- - Alamofire (~> 3.0)
- - AlamofireObjectMapper (~> 2.1)
- - AsyncSwift
+ - Alamofire (~> 3.5.0)
+ - AlamofireObjectMapper (~> 3.0.2)
+ - AsyncSwift (~> 1.6.4)
- CoreStore
- Hakuba
- - Kingfisher (~> 1.8)
- - Kugel
+ - Kingfisher (~> 2.6.1)
+ - Kugel (~> 0.1.0)
- Nimble
- ObjectMapper (~> 1.0)
- Quick
@@ -33,21 +33,21 @@ DEPENDENCIES:
- StatefulViewController (~> 1.0)
SPEC CHECKSUMS:
- Alamofire: fbc829692f351fa1d8a31dd75fd7f7f56fea31fb
- AlamofireObjectMapper: 24097576202064f8b0a583452dd934064f78dc0e
+ Alamofire: 0dfba1184a543e2aa160f4e39cac4e8aba48d223
+ AlamofireObjectMapper: 70f97cbf45c01c48d26aa07a1a7059a60ed7411d
AsyncSwift: 3c90beed237324f1b57e1f1c414dc5501985d208
CoreStore: 17dd4d1673e9dd165262c55abe37d37b8132f643
GCDKit: ed6646fcf761ff139162aaac518b9ec1fb7aa720
Hakuba: bc5a0422290d086c33a6424a26dd58c1a1136e94
- Kingfisher: 7b6df0fa9d211807152c32c46494f9bc08f0e07b
+ Kingfisher: 7e5515bf6c4f2acad91f6400955d2257549cab7b
Kugel: 2efb1b1e3abe0911aca6f41d9c7560630e88f566
Nimble: 0f3c8b8b084cda391209c3c5efbb48bedeeb920a
- ObjectMapper: 4eb08a726e9791a93b2632049951b56a7c17e471
+ ObjectMapper: 386645adca9d9d23b95eda43090b09d66444cf14
Quick: 18d057bc66451eedd5d1c8dc99ba2a5db6e60226
ReactKit: a2b705e8a8674b9cb38b8112c07891df87e8e62b
StatefulViewController: 2a0e5ab30d9ade8e366253fb759baa9fbf458f3e
SwiftTask: 724ff63fc8bd9b366d242696d4aff098f6de3c3a
-PODFILE CHECKSUM: f3d7954ea384e9f7f62712fd425e07113253d445
+PODFILE CHECKSUM: 6e64c3853e61b3e9e20893fe4fc4bcfcdf9f1db8
-COCOAPODS: 1.0.0
+COCOAPODS: 1.1.1
diff --git a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift
index 32cb48b..0d4268a 100755
--- a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift
+++ b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift
@@ -46,7 +46,7 @@ internal final class FromJSON {
}
/// Mappable object
- class func object(inout field: N, map: Map) {
+ class func object(inout field: N, map: Map) {
if map.toObject {
Mapper(context: map.context).map(map.currentValue, toObject: field)
} else if let value: N = Mapper(context: map.context).map(map.currentValue) {
@@ -55,7 +55,7 @@ internal final class FromJSON {
}
/// Optional Mappable Object
- class func optionalObject(inout field: N?, map: Map) {
+ class func optionalObject(inout field: N?, map: Map) {
if let field = field where map.toObject && map.currentValue != nil {
Mapper(context: map.context).map(map.currentValue, toObject: field)
} else {
@@ -64,7 +64,7 @@ internal final class FromJSON {
}
/// Implicitly unwrapped Optional Mappable Object
- class func optionalObject(inout field: N!, map: Map) {
+ class func optionalObject(inout field: N!, map: Map) {
if let field = field where map.toObject && map.currentValue != nil {
Mapper(context: map.context).map(map.currentValue, toObject: field)
} else {
@@ -73,14 +73,14 @@ internal final class FromJSON {
}
/// mappable object array
- class func objectArray(inout field: Array, map: Map) {
+ class func objectArray(inout field: Array, map: Map) {
if let objects = Mapper(context: map.context).mapArray(map.currentValue) {
field = objects
}
}
/// optional mappable object array
- class func optionalObjectArray(inout field: Array?, map: Map) {
+ class func optionalObjectArray(inout field: Array?, map: Map) {
if let objects: Array = Mapper(context: map.context).mapArray(map.currentValue) {
field = objects
} else {
@@ -89,7 +89,7 @@ internal final class FromJSON {
}
/// Implicitly unwrapped optional mappable object array
- class func optionalObjectArray(inout field: Array!, map: Map) {
+ class func optionalObjectArray(inout field: Array!, map: Map) {
if let objects: Array = Mapper(context: map.context).mapArray(map.currentValue) {
field = objects
} else {
@@ -98,24 +98,24 @@ internal final class FromJSON {
}
/// mappable object array
- class func twoDimensionalObjectArray(inout field: Array>, map: Map) {
+ class func twoDimensionalObjectArray(inout field: Array>, map: Map) {
if let objects = Mapper(context: map.context).mapArrayOfArrays(map.currentValue) {
field = objects
}
}
/// optional mappable 2 dimentional object array
- class func optionalTwoDimensionalObjectArray(inout field: Array>?, map: Map) {
+ class func optionalTwoDimensionalObjectArray(inout field: Array>?, map: Map) {
field = Mapper(context: map.context).mapArrayOfArrays(map.currentValue)
}
/// Implicitly unwrapped optional 2 dimentional mappable object array
- class func optionalTwoDimensionalObjectArray(inout field: Array>!, map: Map) {
+ class func optionalTwoDimensionalObjectArray(inout field: Array>!, map: Map) {
field = Mapper(context: map.context).mapArrayOfArrays(map.currentValue)
}
/// Dctionary containing Mappable objects
- class func objectDictionary(inout field: Dictionary, map: Map) {
+ class func objectDictionary(inout field: Dictionary, map: Map) {
if map.toObject {
Mapper(context: map.context).mapDictionary(map.currentValue, toDictionary: field)
} else {
@@ -126,7 +126,7 @@ internal final class FromJSON {
}
/// Optional dictionary containing Mappable objects
- class func optionalObjectDictionary(inout field: Dictionary?, map: Map) {
+ class func optionalObjectDictionary(inout field: Dictionary?, map: Map) {
if let field = field where map.toObject && map.currentValue != nil {
Mapper(context: map.context).mapDictionary(map.currentValue, toDictionary: field)
} else {
@@ -135,7 +135,7 @@ internal final class FromJSON {
}
/// Implicitly unwrapped Dictionary containing Mappable objects
- class func optionalObjectDictionary(inout field: Dictionary!, map: Map) {
+ class func optionalObjectDictionary(inout field: Dictionary!, map: Map) {
if let field = field where map.toObject && map.currentValue != nil {
Mapper(context: map.context).mapDictionary(map.currentValue, toDictionary: field)
} else {
@@ -144,36 +144,36 @@ internal final class FromJSON {
}
/// Dictionary containing Array of Mappable objects
- class func objectDictionaryOfArrays(inout field: Dictionary, map: Map) {
+ class func objectDictionaryOfArrays(inout field: Dictionary, map: Map) {
if let objects = Mapper(context: map.context).mapDictionaryOfArrays(map.currentValue) {
field = objects
}
}
/// Optional Dictionary containing Array of Mappable objects
- class func optionalObjectDictionaryOfArrays(inout field: Dictionary?, map: Map) {
+ class func optionalObjectDictionaryOfArrays(inout field: Dictionary?, map: Map) {
field = Mapper(context: map.context).mapDictionaryOfArrays(map.currentValue)
}
/// Implicitly unwrapped Dictionary containing Array of Mappable objects
- class func optionalObjectDictionaryOfArrays(inout field: Dictionary!, map: Map) {
+ class func optionalObjectDictionaryOfArrays(inout field: Dictionary!, map: Map) {
field = Mapper(context: map.context).mapDictionaryOfArrays(map.currentValue)
}
/// mappable object Set
- class func objectSet(inout field: Set, map: Map) {
+ class func objectSet(inout field: Set, map: Map) {
if let objects = Mapper(context: map.context).mapSet(map.currentValue) {
field = objects
}
}
/// optional mappable object array
- class func optionalObjectSet(inout field: Set?, map: Map) {
+ class func optionalObjectSet(inout field: Set?, map: Map) {
field = Mapper(context: map.context).mapSet(map.currentValue)
}
/// Implicitly unwrapped optional mappable object array
- class func optionalObjectSet(inout field: Set!, map: Map) {
+ class func optionalObjectSet(inout field: Set!, map: Map) {
field = Mapper(context: map.context).mapSet(map.currentValue)
}
diff --git a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Map.swift b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Map.swift
index 1683ef7..08d290c 100644
--- a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Map.swift
+++ b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Map.swift
@@ -38,7 +38,7 @@ public protocol MapContext {
public final class Map {
public let mappingType: MappingType
- public internal(set) var JSONDictionary: [String : AnyObject] = [:]
+ public internal(set) var JSONDictionary: [String: AnyObject] = [:]
public internal(set) var isKeyPresent = false
public var currentValue: AnyObject?
public var context: MapContext?
@@ -50,7 +50,7 @@ public final class Map {
/// Counter for failing cases of deserializing values to `let` properties.
private var failedCount: Int = 0
- public init(mappingType: MappingType, JSONDictionary: [String : AnyObject], toObject: Bool = false, context: MapContext? = nil) {
+ public init(mappingType: MappingType, JSONDictionary: [String: AnyObject], toObject: Bool = false, context: MapContext? = nil) {
self.mappingType = mappingType
self.JSONDictionary = JSONDictionary
self.toObject = toObject
@@ -62,10 +62,19 @@ public final class Map {
public subscript(key: String) -> Map {
// save key and value associated to it
let nested = key.containsString(".")
- return self[key, nested: nested]
+ return self[key, nested: nested, ignoreNil: false]
}
public subscript(key: String, nested nested: Bool) -> Map {
+ return self[key, nested: nested, ignoreNil: false]
+ }
+
+ public subscript(key: String, ignoreNil ignoreNil: Bool) -> Map {
+ let nested = key.containsString(".")
+ return self[key, nested: nested, ignoreNil: ignoreNil]
+ }
+
+ public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> Map {
// save key and value associated to it
currentKey = key
keyIsNested = nested
@@ -82,6 +91,11 @@ public final class Map {
(isKeyPresent, currentValue) = valueFor(ArraySlice(key.componentsSeparatedByString(".")), dictionary: JSONDictionary)
}
+ // update isKeyPresent if ignoreNil is true
+ if ignoreNil && currentValue == nil {
+ isKeyPresent = false
+ }
+
return self
}
@@ -128,7 +142,7 @@ private func valueFor(keyPathComponents: ArraySlice, dictionary: [String
let object = dictionary[keyPath]
if object is NSNull {
return (true, nil)
- } else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 {
+ } else if let dict = object as? [String: AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
} else if let array = object as? [AnyObject] where keyPathComponents.count > 1 {
@@ -161,7 +175,7 @@ private func valueFor(keyPathComponents: ArraySlice, array: [AnyObject])
} else if let array = object as? [AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, array: array)
- } else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 {
+ } else if let dict = object as? [String: AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
} else {
diff --git a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift
index 6e7343c..dc3af58 100644
--- a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift
+++ b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift
@@ -8,22 +8,25 @@
import Foundation
-public protocol Mappable {
- /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
- init?(_ map: Map)
+/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead
+public protocol BaseMappable {
/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
mutating func mapping(map: Map)
- /// This is an optional function that can be used to:
+}
+
+public protocol Mappable: BaseMappable {
+ /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
+ init?(_ map: Map)
+}
+
+public protocol StaticMappable: BaseMappable {
+ /// This is function that can be used to:
/// 1) provide an existing cached object to be used for mapping
/// 2) return an object of another class (which conforms to Mappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping
- static func objectForMapping(map: Map) -> Mappable?
+ static func objectForMapping(map: Map) -> BaseMappable?
}
-public extension Mappable {
-
- public static func objectForMapping(map: Map) -> Mappable? {
- return nil
- }
+public extension BaseMappable {
/// Initializes object from a JSON String
public init?(JSONString: String) {
@@ -35,7 +38,7 @@ public extension Mappable {
}
/// Initializes object from a JSON Dictionary
- public init?(JSON: [String : AnyObject]) {
+ public init?(JSON: [String: AnyObject]) {
if let obj: Self = Mapper().map(JSON) {
self = obj
} else {
@@ -54,7 +57,7 @@ public extension Mappable {
}
}
-public extension Array where Element: Mappable {
+public extension Array where Element: BaseMappable {
/// Initialize Array from a JSON String
public init?(JSONString: String) {
@@ -66,7 +69,7 @@ public extension Array where Element: Mappable {
}
/// Initialize Array from a JSON Array
- public init?(JSONArray: [[String : AnyObject]]) {
+ public init?(JSONArray: [[String: AnyObject]]) {
if let obj: [Element] = Mapper().mapArray(JSONArray) {
self = obj
} else {
@@ -75,7 +78,7 @@ public extension Array where Element: Mappable {
}
/// Returns the JSON Array
- public func toJSON() -> [[String : AnyObject]] {
+ public func toJSON() -> [[String: AnyObject]] {
return Mapper().toJSONArray(self)
}
@@ -85,7 +88,7 @@ public extension Array where Element: Mappable {
}
}
-public extension Set where Element: Mappable {
+public extension Set where Element: BaseMappable {
/// Initializes a set from a JSON String
public init?(JSONString: String) {
@@ -97,7 +100,7 @@ public extension Set where Element: Mappable {
}
/// Initializes a set from JSON
- public init?(JSONArray: [[String : AnyObject]]) {
+ public init?(JSONArray: [[String: AnyObject]]) {
if let obj: Set = Mapper().mapSet(JSONArray) {
self = obj
} else {
@@ -106,7 +109,7 @@ public extension Set where Element: Mappable {
}
/// Returns the JSON Set
- public func toJSON() -> [[String : AnyObject]] {
+ public func toJSON() -> [[String: AnyObject]] {
return Mapper().toJSONSet(self)
}
diff --git a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift
index 90f4221..8dfa760 100755
--- a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift
+++ b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift
@@ -34,7 +34,7 @@ public enum MappingType {
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
-public final class Mapper {
+public final class Mapper {
public var context: MapContext?
@@ -46,7 +46,7 @@ public final class Mapper {
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSON: AnyObject?, toObject object: N) -> N {
- if let JSON = JSON as? [String : AnyObject] {
+ if let JSON = JSON as? [String: AnyObject] {
return map(JSON, toObject: object)
}
@@ -63,7 +63,7 @@ public final class Mapper {
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
- public func map(JSONDictionary: [String : AnyObject], toObject object: N) -> N {
+ public func map(JSONDictionary: [String: AnyObject], toObject object: N) -> N {
var mutableObject = object
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, toObject: true, context: context)
mutableObject.mapping(map)
@@ -97,7 +97,7 @@ public final class Mapper {
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSON: AnyObject?) -> N? {
- if let JSON = JSON as? [String : AnyObject] {
+ if let JSON = JSON as? [String: AnyObject] {
return map(JSON)
}
@@ -105,21 +105,25 @@ public final class Mapper {
}
/// Maps a JSON dictionary to an object that conforms to Mappable
- public func map(JSONDictionary: [String : AnyObject]) -> N? {
+ public func map(JSONDictionary: [String: AnyObject]) -> N? {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, context: context)
- // check if objectForMapping returns an object for mapping
- if var object = N.self.objectForMapping(map) as? N {
- object.mapping(map)
- return object
+ // check if object is StaticMappable
+ if let klass = N.self as? StaticMappable.Type {
+ if var object = klass.objectForMapping(map) as? N {
+ object.mapping(map)
+ return object
+ }
}
-
+
// fall back to using init? to create N
- if var object = N(map) {
- object.mapping(map)
- return object
+ if let klass = N.self as? Mappable.Type {
+ if var object = klass.init(map) as? N {
+ object.mapping(map)
+ return object
+ }
}
-
+
return nil
}
@@ -153,7 +157,7 @@ public final class Mapper {
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSON: AnyObject?) -> [N]? {
- if let JSONArray = JSON as? [[String : AnyObject]] {
+ if let JSONArray = JSON as? [[String: AnyObject]] {
return mapArray(JSONArray)
}
@@ -161,21 +165,21 @@ public final class Mapper {
}
/// Maps an array of JSON dictionary to an array of Mappable objects
- public func mapArray(JSONArray: [[String : AnyObject]]) -> [N]? {
+ public func mapArray(JSONArray: [[String: AnyObject]]) -> [N]? {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
- public func mapDictionary(JSONString: String) -> [String : N]? {
+ public func mapDictionary(JSONString: String) -> [String: N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
return mapDictionary(parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
- public func mapDictionary(JSON: AnyObject?) -> [String : N]? {
- if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
+ public func mapDictionary(JSON: AnyObject?) -> [String: N]? {
+ if let JSONDictionary = JSON as? [String: [String: AnyObject]] {
return mapDictionary(JSONDictionary)
}
@@ -183,7 +187,7 @@ public final class Mapper {
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects
- public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N]? {
+ public func mapDictionary(JSONDictionary: [String: [String: AnyObject]]) -> [String: N]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap(map)
if result.isEmpty == false {
@@ -194,8 +198,8 @@ public final class Mapper {
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
- public func mapDictionary(JSON: AnyObject?, toDictionary dictionary: [String : N]) -> [String : N] {
- if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
+ public func mapDictionary(JSON: AnyObject?, toDictionary dictionary: [String: N]) -> [String: N] {
+ if let JSONDictionary = JSON as? [String: [String: AnyObject]] {
return mapDictionary(JSONDictionary, toDictionary: dictionary)
}
@@ -203,13 +207,13 @@ public final class Mapper {
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappble objects
- public func mapDictionary(JSONDictionary: [String : [String : AnyObject]], toDictionary dictionary: [String : N]) -> [String : N] {
+ public func mapDictionary(JSONDictionary: [String: [String: AnyObject]], toDictionary dictionary: [String: N]) -> [String: N] {
var mutableDictionary = dictionary
for (key, value) in JSONDictionary {
if let object = dictionary[key] {
- Mapper(context: context).map(value, toObject: object)
+ map(value, toObject: object)
} else {
- mutableDictionary[key] = Mapper(context: context).map(value)
+ mutableDictionary[key] = map(value)
}
}
@@ -217,8 +221,8 @@ public final class Mapper {
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
- public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? {
- if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] {
+ public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String: [N]]? {
+ if let JSONDictionary = JSON as? [String: [[String: AnyObject]]] {
return mapDictionaryOfArrays(JSONDictionary)
}
@@ -226,7 +230,7 @@ public final class Mapper {
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
- public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]]? {
+ public func mapDictionaryOfArrays(JSONDictionary: [String: [[String: AnyObject]]]) -> [String: [N]]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap {
mapArray($0)
@@ -241,7 +245,7 @@ public final class Mapper {
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSON: AnyObject?) -> [[N]]? {
- if let JSONArray = JSON as? [[[String : AnyObject]]] {
+ if let JSONArray = JSON as? [[[String: AnyObject]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
if let array = mapArray(innerJSONArray){
@@ -260,14 +264,14 @@ public final class Mapper {
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary using NSJSONSerialization
- public static func parseJSONDictionary(JSON: String) -> [String : AnyObject]? {
+ public static func parseJSONDictionary(JSON: String) -> [String: AnyObject]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSON)
return Mapper.parseJSONDictionary(parsedJSON)
}
/// Convert a JSON Object into a Dictionary using NSJSONSerialization
- public static func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? {
- if let JSONDict = JSON as? [String : AnyObject] {
+ public static func parseJSONDictionary(JSON: AnyObject?) -> [String: AnyObject]? {
+ if let JSONDict = JSON as? [String: AnyObject] {
return JSONDict
}
@@ -296,16 +300,16 @@ extension Mapper {
// MARK: Functions that create JSON from objects
- ///Maps an object that conforms to Mappable to a JSON dictionary
- public func toJSON( object: N) -> [String : AnyObject] {
+ ///Maps an object that conforms to Mappable to a JSON dictionary
+ public func toJSON(object: N) -> [String: AnyObject] {
var mutableObject = object
let map = Map(mappingType: .ToJSON, JSONDictionary: [:], context: context)
mutableObject.mapping(map)
return map.JSONDictionary
}
- ///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]]
- public func toJSONArray(array: [N]) -> [[String : AnyObject]] {
+ ///Maps an array of Objects to an array of JSON dictionaries [[String: AnyObject]]
+ public func toJSONArray(array: [N]) -> [[String: AnyObject]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
@@ -313,7 +317,7 @@ extension Mapper {
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
- public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] {
+ public func toJSONDictionary(dictionary: [String: N]) -> [String: [String: AnyObject]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
@@ -321,7 +325,7 @@ extension Mapper {
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
- public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] {
+ public func toJSONDictionaryOfArrays(dictionary: [String: [N]]) -> [String: [[String: AnyObject]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
@@ -342,23 +346,32 @@ extension Mapper {
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
- public static func toJSONString(JSONObject: AnyObject, prettyPrint: Bool) -> String? {
- if NSJSONSerialization.isValidJSONObject(JSONObject) {
- let JSONData: NSData?
- do {
- let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : []
- JSONData = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: options)
- } catch let error {
- print(error)
- JSONData = nil
- }
-
- if let JSON = JSONData {
- return String(data: JSON, encoding: NSUTF8StringEncoding)
- }
- }
- return nil
- }
+ /// Converts an Object to a JSON string with option of pretty formatting
+ public static func toJSONString(JSONObject: AnyObject, prettyPrint: Bool) -> String? {
+ let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : []
+ if let JSON = Mapper.toJSONData(JSONObject, options: options) {
+ return String(data: JSON, encoding: NSUTF8StringEncoding)
+ }
+
+ return nil
+ }
+
+ /// Converts an Object to JSON data with options
+ public static func toJSONData(JSONObject: AnyObject, options: NSJSONWritingOptions) -> NSData? {
+ if NSJSONSerialization.isValidJSONObject(JSONObject) {
+ let JSONData: NSData?
+ do {
+ JSONData = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: options)
+ } catch let error {
+ print(error)
+ JSONData = nil
+ }
+
+ return JSONData
+ }
+
+ return nil
+ }
}
extension Mapper where N: Hashable {
@@ -367,7 +380,7 @@ extension Mapper where N: Hashable {
public func mapSet(JSONString: String) -> Set? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
- if let objectArray = mapArray(parsedJSON){
+ if let objectArray = mapArray(parsedJSON) {
return Set(objectArray)
}
@@ -382,7 +395,7 @@ extension Mapper where N: Hashable {
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSON: AnyObject?) -> Set? {
- if let JSONArray = JSON as? [[String : AnyObject]] {
+ if let JSONArray = JSON as? [[String: AnyObject]] {
return mapSet(JSONArray)
}
@@ -390,13 +403,13 @@ extension Mapper where N: Hashable {
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
- public func mapSet(JSONArray: [[String : AnyObject]]) -> Set {
+ public func mapSet(JSONArray: [[String: AnyObject]]) -> Set {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : AnyObject]]
- public func toJSONSet(set: Set) -> [[String : AnyObject]] {
+ public func toJSONSet(set: Set) -> [[String: AnyObject]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
@@ -412,8 +425,8 @@ extension Mapper where N: Hashable {
}
extension Dictionary {
- internal func map(@noescape f: Element -> (K, V)) -> [K : V] {
- var mapped = [K : V]()
+ internal func map(@noescape f: Element -> (K, V)) -> [K: V] {
+ var mapped = [K: V]()
for element in self {
let newElement = f(element)
@@ -423,8 +436,8 @@ extension Dictionary {
return mapped
}
- internal func map(@noescape f: Element -> (K, [V])) -> [K : [V]] {
- var mapped = [K : [V]]()
+ internal func map(@noescape f: Element -> (K, [V])) -> [K: [V]] {
+ var mapped = [K: [V]]()
for element in self {
let newElement = f(element)
@@ -435,11 +448,11 @@ extension Dictionary {
}
- internal func filterMap(@noescape f: Value -> U?) -> [Key : U] {
- var mapped = [Key : U]()
+ internal func filterMap(@noescape f: Value -> U?) -> [Key: U] {
+ var mapped = [Key: U]()
for (key, value) in self {
- if let newValue = f(value){
+ if let newValue = f(value) {
mapped[key] = newValue
}
}
diff --git a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift
index f592335..479ea2b 100755
--- a/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift
+++ b/iOSSwiftStarter/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift
@@ -280,10 +280,10 @@ private func toJSONDictionaryWithTransform(input: [Str
}
}
-// MARK:- Mappable Objects -
+// MARK:- Mappable Objects -
/// Object conforming to Mappable
-public func <- (inout left: T, right: Map) {
+public func <- (inout left: T, right: Map) {
switch right.mappingType {
case .FromJSON:
FromJSON.object(&left, map: right)
@@ -293,7 +293,7 @@ public func <- (inout left: T, right: Map) {
}
/// Optional Mappable objects
-public func <- (inout left: T?, right: Map) {
+public func <- (inout left: T?, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.optionalObject(&left, map: right)
@@ -304,7 +304,7 @@ public func <- (inout left: T?, right: Map) {
}
/// Implicitly unwrapped optional Mappable objects
-public func <- (inout left: T!, right: Map) {
+public func <- (inout left: T!, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.optionalObject(&left, map: right)
@@ -314,10 +314,10 @@ public func <- (inout left: T!, right: Map) {
}
}
-// MARK:- Transforms of Mappable Objects -
+// MARK:- Transforms of Mappable Objects -
/// Object conforming to Mappable that have transforms
-public func <- (inout left: Transform.Object, right: (Map, Transform)) {
+public func <- (inout left: Transform.Object, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .FromJSON where map.isKeyPresent:
@@ -331,7 +331,7 @@ public func <- (inout
}
/// Optional Mappable objects that have transforms
-public func <- (inout left: Transform.Object?, right: (Map, Transform)) {
+public func <- (inout left: Transform.Object?, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .FromJSON where map.isKeyPresent:
@@ -345,7 +345,7 @@ public func <- (inout
}
/// Implicitly unwrapped optional Mappable objects that have transforms
-public func <- (inout left: Transform.Object!, right: (Map, Transform)) {
+public func <- (inout left: Transform.Object!, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .FromJSON where map.isKeyPresent:
@@ -358,10 +358,10 @@ public func <- (inout
}
}
-// MARK:- Dictionary of Mappable objects - Dictionary
+// MARK:- Dictionary of Mappable objects - Dictionary
-/// Dictionary of Mappable objects
-public func <- (inout left: Dictionary, right: Map) {
+/// Dictionary of Mappable objects
+public func <- (inout left: Dictionary, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.objectDictionary(&left, map: right)
@@ -371,8 +371,8 @@ public func <- (inout left: Dictionary, right: Map) {
}
}
-/// Optional Dictionary of Mappable object
-public func <- (inout left: Dictionary?, right: Map) {
+/// Optional Dictionary of Mappable object
+public func <- (inout left: Dictionary?, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionary(&left, map: right)
@@ -382,8 +382,8 @@ public func <- (inout left: Dictionary?, right: Map) {
}
}
-/// Implicitly unwrapped Optional Dictionary of Mappable object
-public func <- (inout left: Dictionary!, right: Map) {
+/// Implicitly unwrapped Optional Dictionary of Mappable object
+public func <- (inout left: Dictionary!, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionary(&left, map: right)
@@ -393,8 +393,8 @@ public func <- (inout left: Dictionary!, right: Map) {
}
}
-/// Dictionary of Mappable objects
-public func <- (inout left: Dictionary, right: Map) {
+/// Dictionary of Mappable objects
+public func <- (inout left: Dictionary, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.objectDictionaryOfArrays(&left, map: right)
@@ -404,8 +404,8 @@ public func <- (inout left: Dictionary, right: Map) {
}
}
-/// Optional Dictionary of Mappable object
-public func <- (inout left: Dictionary?, right: Map) {
+/// Optional Dictionary of Mappable object
+public func <- (inout left: Dictionary?, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionaryOfArrays(&left, map: right)
@@ -415,8 +415,8 @@ public func <- (inout left: Dictionary?, right: Map) {
}
}
-/// Implicitly unwrapped Optional Dictionary of Mappable object
-public func <- (inout left: Dictionary!, right: Map) {
+/// Implicitly unwrapped Optional Dictionary of Mappable object
+public func <- (inout left: Dictionary!, right: Map) {
switch right.mappingType {
case .FromJSON where right.isKeyPresent:
FromJSON.optionalObjectDictionaryOfArrays(&left, map: right)
@@ -426,12 +426,12 @@ public func <- (inout left: Dictionary!, right: Map) {
}
}
-// MARK:- Dictionary of Mappable objects with a transform - Dictionary
+// MARK:- Dictionary of Mappable objects with a transform - Dictionary
-/// Dictionary of Mappable objects with a transform
-public func <- (inout left: Dictionary, right: (Map, Transform)) {
+/// Dictionary of Mappable objects with a transform
+public func <- (inout left: Dictionary, right: (Map, Transform)) {
let (map, transform) = right
- if let object = map.currentValue as? [String : AnyObject] where map.mappingType == .FromJSON && map.isKeyPresent {
+ if let object = map.currentValue as? [String: AnyObject] where map.mappingType == .FromJSON && map.isKeyPresent {
let value = fromJSONDictionaryWithTransform(object, transform: transform) ?? left
FromJSON.basicType(&left, object: value)
} else if map.mappingType == .ToJSON {
@@ -440,10 +440,10 @@ public func <- (inout
}
}
-/// Optional Dictionary of Mappable object with a transform
-public func <- (inout left: Dictionary?, right: (Map, Transform)) {
+/// Optional Dictionary of Mappable object with a transform
+public func <- (inout left: Dictionary?, right: (Map, Transform)) {
let (map, transform) = right
- if let object = map.currentValue as? [String : AnyObject] where map.mappingType == .FromJSON && map.isKeyPresent {
+ if let object = map.currentValue as? [String: AnyObject] where map.mappingType == .FromJSON && map.isKeyPresent {
let value = fromJSONDictionaryWithTransform(object, transform: transform) ?? left
FromJSON.optionalBasicType(&left, object: value)
} else if map.mappingType == .ToJSON {
@@ -452,10 +452,10 @@ public func <- (inout
}
}
-/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform
-public func <- (inout left: Dictionary!, right: (Map, Transform)) {
+/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform
+public func <- (inout left: Dictionary!, right: (Map, Transform)) {
let (map, transform) = right
- if let dictionary = map.currentValue as? [String : AnyObject] where map.mappingType == .FromJSON && map.isKeyPresent {
+ if let dictionary = map.currentValue as? [String: AnyObject] where map.mappingType == .FromJSON && map.isKeyPresent {
let transformedDictionary = fromJSONDictionaryWithTransform(dictionary, transform: transform) ?? left
FromJSON.optionalBasicType(&left, object: transformedDictionary)
} else if map.mappingType == .ToJSON {
@@ -464,61 +464,79 @@ public func <- (inout
}
}
-/// Dictionary of Mappable objects with a transform
-public func <-