switch to Alamofire
This commit is contained in:
parent
79628c8824
commit
4a3e92aba5
@ -2,5 +2,4 @@ platform :osx, '10.9'
|
||||
workspace 'ipbc-Client'
|
||||
use_frameworks!
|
||||
|
||||
pod 'SwiftHTTP', '~> 0.9.4'
|
||||
pod 'ReachabilitySwift', git: 'https://github.com/ashleymills/Reachability.swift'
|
||||
pod 'Alamofire', '~> 3.0'
|
||||
|
||||
@ -1,22 +1,10 @@
|
||||
PODS:
|
||||
- ReachabilitySwift (1.1)
|
||||
- SwiftHTTP (0.9.5)
|
||||
- Alamofire (3.1.2)
|
||||
|
||||
DEPENDENCIES:
|
||||
- ReachabilitySwift (from `https://github.com/ashleymills/Reachability.swift`)
|
||||
- SwiftHTTP (~> 0.9.4)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
ReachabilitySwift:
|
||||
:git: https://github.com/ashleymills/Reachability.swift
|
||||
|
||||
CHECKOUT OPTIONS:
|
||||
ReachabilitySwift:
|
||||
:commit: eca2517c69b321e9c4ce464be45c33f3a8dfe14e
|
||||
:git: https://github.com/ashleymills/Reachability.swift
|
||||
- Alamofire (~> 3.0)
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
ReachabilitySwift: 1e53abddb01111deac0d229dabdb8bb043567b18
|
||||
SwiftHTTP: cd7b248bc07db02926ff54cf19b580b78f7abfa1
|
||||
Alamofire: 7c16ca65f3c7e681fd925fd7f2dec7747ff96855
|
||||
|
||||
COCOAPODS: 0.38.2
|
||||
COCOAPODS: 0.39.0
|
||||
|
||||
19
ipbc-Client/Pods/Alamofire/LICENSE
generated
Normal file
19
ipbc-Client/Pods/Alamofire/LICENSE
generated
Normal file
@ -0,0 +1,19 @@
|
||||
Copyright (c) 2014–2015 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.
|
||||
1147
ipbc-Client/Pods/Alamofire/README.md
generated
Normal file
1147
ipbc-Client/Pods/Alamofire/README.md
generated
Normal file
File diff suppressed because it is too large
Load Diff
368
ipbc-Client/Pods/Alamofire/Source/Alamofire.swift
generated
Normal file
368
ipbc-Client/Pods/Alamofire/Source/Alamofire.swift
generated
Normal file
@ -0,0 +1,368 @@
|
||||
// Alamofire.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - URLStringConvertible
|
||||
|
||||
/**
|
||||
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
|
||||
construct URL requests.
|
||||
*/
|
||||
public protocol URLStringConvertible {
|
||||
/**
|
||||
A URL that conforms to RFC 2396.
|
||||
|
||||
Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
|
||||
|
||||
See https://tools.ietf.org/html/rfc2396
|
||||
See https://tools.ietf.org/html/rfc1738
|
||||
See https://tools.ietf.org/html/rfc1808
|
||||
*/
|
||||
var URLString: String { get }
|
||||
}
|
||||
|
||||
extension String: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURL: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return absoluteString
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURLComponents: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return URL!.URLString
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURLRequest: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return URL!.URLString
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - URLRequestConvertible
|
||||
|
||||
/**
|
||||
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
|
||||
*/
|
||||
public protocol URLRequestConvertible {
|
||||
/// The URL request.
|
||||
var URLRequest: NSMutableURLRequest { get }
|
||||
}
|
||||
|
||||
extension NSURLRequest: URLRequestConvertible {
|
||||
public var URLRequest: NSMutableURLRequest {
|
||||
return self.mutableCopy() as! NSMutableURLRequest
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Convenience
|
||||
|
||||
func URLRequest(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil)
|
||||
-> NSMutableURLRequest
|
||||
{
|
||||
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
|
||||
mutableURLRequest.HTTPMethod = method.rawValue
|
||||
|
||||
if let headers = headers {
|
||||
for (headerField, headerValue) in headers {
|
||||
mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField)
|
||||
}
|
||||
}
|
||||
|
||||
return mutableURLRequest
|
||||
}
|
||||
|
||||
// MARK: - Request Methods
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for the specified method, URL string, parameters, and
|
||||
parameter encoding.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.request(
|
||||
method,
|
||||
URLString,
|
||||
parameters: parameters,
|
||||
encoding: encoding,
|
||||
headers: headers
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(URLRequest: URLRequestConvertible) -> Request {
|
||||
return Manager.sharedInstance.request(URLRequest.URLRequest)
|
||||
}
|
||||
|
||||
// MARK: - Upload Methods
|
||||
|
||||
// MARK: File
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter file: The file to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
file: NSURL)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and file.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter file: The file to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, file: file)
|
||||
}
|
||||
|
||||
// MARK: Data
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
data: NSData)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and data.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, data: data)
|
||||
}
|
||||
|
||||
// MARK: Stream
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
stream: NSInputStream)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and stream.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, stream: stream)
|
||||
}
|
||||
|
||||
// MARK: MultipartFormData
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
return Manager.sharedInstance.upload(
|
||||
method,
|
||||
URLString,
|
||||
headers: headers,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
URLRequest: URLRequestConvertible,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
return Manager.sharedInstance.upload(
|
||||
URLRequest,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Download Methods
|
||||
|
||||
// MARK: URL Request
|
||||
|
||||
/**
|
||||
Creates a download request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil,
|
||||
destination: Request.DownloadFileDestination)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.download(
|
||||
method,
|
||||
URLString,
|
||||
parameters: parameters,
|
||||
encoding: encoding,
|
||||
headers: headers,
|
||||
destination: destination
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a download request using the shared manager instance for the specified URL request.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
|
||||
return Manager.sharedInstance.download(URLRequest, destination: destination)
|
||||
}
|
||||
|
||||
// MARK: Resume Data
|
||||
|
||||
/**
|
||||
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
|
||||
information.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
|
||||
return Manager.sharedInstance.download(data, destination: destination)
|
||||
}
|
||||
244
ipbc-Client/Pods/Alamofire/Source/Download.swift
generated
Normal file
244
ipbc-Client/Pods/Alamofire/Source/Download.swift
generated
Normal file
@ -0,0 +1,244 @@
|
||||
// Download.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Manager {
|
||||
private enum Downloadable {
|
||||
case Request(NSURLRequest)
|
||||
case ResumeData(NSData)
|
||||
}
|
||||
|
||||
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
|
||||
var downloadTask: NSURLSessionDownloadTask!
|
||||
|
||||
switch downloadable {
|
||||
case .Request(let request):
|
||||
dispatch_sync(queue) {
|
||||
downloadTask = self.session.downloadTaskWithRequest(request)
|
||||
}
|
||||
case .ResumeData(let resumeData):
|
||||
dispatch_sync(queue) {
|
||||
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
|
||||
}
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: downloadTask)
|
||||
|
||||
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
|
||||
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
|
||||
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
|
||||
}
|
||||
}
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: Request
|
||||
|
||||
/**
|
||||
Creates a download request for the specified method, URL string, parameters, parameter encoding, headers
|
||||
and destination.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil,
|
||||
destination: Request.DownloadFileDestination)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
|
||||
|
||||
return download(encodedURLRequest, destination: destination)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for downloading from the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
|
||||
return download(.Request(URLRequest.URLRequest), destination: destination)
|
||||
}
|
||||
|
||||
// MARK: Resume Data
|
||||
|
||||
/**
|
||||
Creates a request for downloading from the resume data produced from a previous request cancellation.
|
||||
|
||||
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
|
||||
additional information.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
|
||||
return download(.ResumeData(resumeData), destination: destination)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
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
|
||||
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
|
||||
file URL in the first available directory with the specified search path directory and search path domain mask.
|
||||
|
||||
- parameter directory: The search path directory. `.DocumentDirectory` by default.
|
||||
- parameter domain: The search path domain mask. `.UserDomainMask` by default.
|
||||
|
||||
- returns: A download file destination closure.
|
||||
*/
|
||||
public class func suggestedDownloadDestination(
|
||||
directory directory: NSSearchPathDirectory = .DocumentDirectory,
|
||||
domain: NSSearchPathDomainMask = .UserDomainMask)
|
||||
-> DownloadFileDestination
|
||||
{
|
||||
return { temporaryURL, response -> NSURL in
|
||||
let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)
|
||||
|
||||
if !directoryURLs.isEmpty {
|
||||
return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!)
|
||||
}
|
||||
|
||||
return temporaryURL
|
||||
}
|
||||
}
|
||||
|
||||
/// The resume data of the underlying download task if available after a failure.
|
||||
public var resumeData: NSData? {
|
||||
var data: NSData?
|
||||
|
||||
if let delegate = delegate as? DownloadTaskDelegate {
|
||||
data = delegate.resumeData
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
// MARK: - DownloadTaskDelegate
|
||||
|
||||
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
|
||||
var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
|
||||
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
|
||||
|
||||
var resumeData: NSData?
|
||||
override var data: NSData? { return resumeData }
|
||||
|
||||
// MARK: - NSURLSessionDownloadDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
|
||||
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
|
||||
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didFinishDownloadingToURL location: NSURL)
|
||||
{
|
||||
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
|
||||
do {
|
||||
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
|
||||
try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination)
|
||||
} catch {
|
||||
self.error = error as NSError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64)
|
||||
{
|
||||
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
|
||||
downloadTaskDidWriteData(
|
||||
session,
|
||||
downloadTask,
|
||||
bytesWritten,
|
||||
totalBytesWritten,
|
||||
totalBytesExpectedToWrite
|
||||
)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToWrite
|
||||
progress.completedUnitCount = totalBytesWritten
|
||||
|
||||
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didResumeAtOffset fileOffset: Int64,
|
||||
expectedTotalBytes: Int64)
|
||||
{
|
||||
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
|
||||
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
|
||||
} else {
|
||||
progress.totalUnitCount = expectedTotalBytes
|
||||
progress.completedUnitCount = fileOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
66
ipbc-Client/Pods/Alamofire/Source/Error.swift
generated
Normal file
66
ipbc-Client/Pods/Alamofire/Source/Error.swift
generated
Normal file
@ -0,0 +1,66 @@
|
||||
// Error.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors.
|
||||
public struct Error {
|
||||
/// The domain used for creating all Alamofire errors.
|
||||
public static let Domain = "com.alamofire.error"
|
||||
|
||||
/// The custom error codes generated by Alamofire.
|
||||
public enum Code: Int {
|
||||
case InputStreamReadFailed = -6000
|
||||
case OutputStreamWriteFailed = -6001
|
||||
case ContentTypeValidationFailed = -6002
|
||||
case StatusCodeValidationFailed = -6003
|
||||
case DataSerializationFailed = -6004
|
||||
case StringSerializationFailed = -6005
|
||||
case JSONSerializationFailed = -6006
|
||||
case PropertyListSerializationFailed = -6007
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
public static func errorWithCode(code: Code, failureReason: String) -> NSError {
|
||||
return errorWithCode(code.rawValue, failureReason: failureReason)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
public static func errorWithCode(code: Int, failureReason: String) -> NSError {
|
||||
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
|
||||
return NSError(domain: Domain, code: code, userInfo: userInfo)
|
||||
}
|
||||
}
|
||||
708
ipbc-Client/Pods/Alamofire/Source/Manager.swift
generated
Normal file
708
ipbc-Client/Pods/Alamofire/Source/Manager.swift
generated
Normal file
@ -0,0 +1,708 @@
|
||||
// Manager.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
|
||||
*/
|
||||
public class Manager {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/**
|
||||
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 = {
|
||||
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
||||
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
|
||||
|
||||
return Manager(configuration: configuration)
|
||||
}()
|
||||
|
||||
/**
|
||||
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
|
||||
*/
|
||||
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"
|
||||
|
||||
// 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(",")
|
||||
}()
|
||||
|
||||
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
|
||||
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"
|
||||
|
||||
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
|
||||
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
|
||||
|
||||
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) {
|
||||
return mutableUserAgent as String
|
||||
}
|
||||
}
|
||||
|
||||
return "Alamofire"
|
||||
}()
|
||||
|
||||
return [
|
||||
"Accept-Encoding": acceptEncoding,
|
||||
"Accept-Language": acceptLanguage,
|
||||
"User-Agent": userAgent
|
||||
]
|
||||
}()
|
||||
|
||||
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
/// The underlying session.
|
||||
public let session: NSURLSession
|
||||
|
||||
/// The session delegate handling all the task and session delegate callbacks.
|
||||
public let delegate: SessionDelegate
|
||||
|
||||
/// Whether to start requests immediately after being constructed. `true` by default.
|
||||
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
|
||||
will automatically call the handler.
|
||||
|
||||
If you need to handle your own events before the handler is called, then you need to override the
|
||||
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
|
||||
|
||||
`nil` by default.
|
||||
*/
|
||||
public var backgroundCompletionHandler: (() -> Void)?
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/**
|
||||
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
|
||||
|
||||
- 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
|
||||
challenges. `nil` by default.
|
||||
|
||||
- returns: The new `Manager` instance.
|
||||
*/
|
||||
public init(
|
||||
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
|
||||
delegate: SessionDelegate = SessionDelegate(),
|
||||
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
|
||||
{
|
||||
self.delegate = delegate
|
||||
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
|
||||
|
||||
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
|
||||
|
||||
- parameter session: The URL session.
|
||||
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
|
||||
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
|
||||
challenges. `nil` by default.
|
||||
|
||||
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
|
||||
*/
|
||||
public init?(
|
||||
session: NSURLSession,
|
||||
delegate: SessionDelegate,
|
||||
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
|
||||
{
|
||||
self.delegate = delegate
|
||||
self.session = session
|
||||
|
||||
guard delegate === session.delegate else { return nil }
|
||||
|
||||
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
|
||||
}
|
||||
|
||||
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
|
||||
session.serverTrustPolicyManager = serverTrustPolicyManager
|
||||
|
||||
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
|
||||
guard let strongSelf = self else { return }
|
||||
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
session.invalidateAndCancel()
|
||||
}
|
||||
|
||||
// MARK: - Request
|
||||
|
||||
/**
|
||||
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
|
||||
return request(encodedURLRequest)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(URLRequest: URLRequestConvertible) -> Request {
|
||||
var dataTask: NSURLSessionDataTask!
|
||||
|
||||
dispatch_sync(queue) {
|
||||
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: dataTask)
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: - SessionDelegate
|
||||
|
||||
/**
|
||||
Responsible for handling all delegate callbacks for the underlying session.
|
||||
*/
|
||||
public final 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? {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes the `SessionDelegate` instance.
|
||||
|
||||
- returns: The new `SessionDelegate` instance.
|
||||
*/
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
|
||||
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
|
||||
|
||||
/// 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)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the session has been invalidated.
|
||||
|
||||
- parameter session: The session object that was invalidated.
|
||||
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
|
||||
sessionDidBecomeInvalidWithError?(session, error)
|
||||
}
|
||||
|
||||
/**
|
||||
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
|
||||
|
||||
- parameter session: The session containing the task that requested authentication.
|
||||
- parameter challenge: An object that contains the request for authentication.
|
||||
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
||||
var credential: NSURLCredential?
|
||||
|
||||
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
|
||||
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
|
||||
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
|
||||
let host = challenge.protectionSpace.host
|
||||
|
||||
if let
|
||||
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
|
||||
serverTrust = challenge.protectionSpace.serverTrust
|
||||
{
|
||||
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
|
||||
disposition = .UseCredential
|
||||
credential = NSURLCredential(forTrust: serverTrust)
|
||||
} else {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
completionHandler(disposition, credential)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that all messages enqueued for a session have been delivered.
|
||||
|
||||
- parameter session: The session that no longer has any outstanding requests.
|
||||
*/
|
||||
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
|
||||
sessionDidFinishEventsForBackgroundURLSession?(session)
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
|
||||
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
|
||||
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
|
||||
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
|
||||
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
|
||||
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the remote server requested an HTTP redirect.
|
||||
|
||||
- parameter session: The session containing the task whose request resulted in a redirect.
|
||||
- parameter task: The task whose request resulted in a redirect.
|
||||
- parameter response: An object containing the server’s response to the original request.
|
||||
- parameter request: A URL request object filled out with the new location.
|
||||
- parameter completionHandler: A closure that your handler should call with either the value of the request
|
||||
parameter, a modified URL request object, or NULL to refuse the redirect and
|
||||
return the body of the redirect response.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
willPerformHTTPRedirection response: NSHTTPURLResponse,
|
||||
newRequest request: NSURLRequest,
|
||||
completionHandler: ((NSURLRequest?) -> Void))
|
||||
{
|
||||
var redirectRequest: NSURLRequest? = request
|
||||
|
||||
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
|
||||
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
|
||||
}
|
||||
|
||||
completionHandler(redirectRequest)
|
||||
}
|
||||
|
||||
/**
|
||||
Requests credentials from the delegate in response to an authentication request from the remote server.
|
||||
|
||||
- parameter session: The session containing the task whose request requires authentication.
|
||||
- parameter task: The task whose request requires authentication.
|
||||
- parameter challenge: An object that contains the request for authentication.
|
||||
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
completionHandler(taskDidReceiveChallenge(session, task, challenge))
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
task: task,
|
||||
didReceiveChallenge: challenge,
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
} else {
|
||||
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate when a task requires a new request body stream to send to the remote server.
|
||||
|
||||
- parameter session: The session containing the task that needs a new body stream.
|
||||
- parameter task: The task that needs a new body stream.
|
||||
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
|
||||
{
|
||||
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
|
||||
completionHandler(taskNeedNewBodyStream(session, task))
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Periodically informs the delegate of the progress of sending body content to the server.
|
||||
|
||||
- parameter session: The session containing the data task.
|
||||
- parameter task: The data task.
|
||||
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
|
||||
- parameter totalBytesSent: The total number of bytes sent so far.
|
||||
- parameter totalBytesExpectedToSend: The expected length of the body data.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didSendBodyData bytesSent: Int64,
|
||||
totalBytesSent: Int64,
|
||||
totalBytesExpectedToSend: Int64)
|
||||
{
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
task: task,
|
||||
didSendBodyData: bytesSent,
|
||||
totalBytesSent: totalBytesSent,
|
||||
totalBytesExpectedToSend: totalBytesExpectedToSend
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the task finished transferring data.
|
||||
|
||||
- parameter session: The session containing the task whose request finished transferring data.
|
||||
- parameter task: The task whose request finished transferring data.
|
||||
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let taskDidComplete = taskDidComplete {
|
||||
taskDidComplete(session, task, error)
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, didCompleteWithError: error)
|
||||
}
|
||||
|
||||
self[task] = nil
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDataDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
|
||||
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
|
||||
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
|
||||
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
|
||||
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task received the initial reply (headers) from the server.
|
||||
|
||||
- parameter session: The session containing the data task that received an initial reply.
|
||||
- parameter dataTask: The data task that received an initial reply.
|
||||
- parameter response: A URL response object populated with headers.
|
||||
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
|
||||
constant to indicate whether the transfer should continue as a data task or
|
||||
should become a download task.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse response: NSURLResponse,
|
||||
completionHandler: ((NSURLSessionResponseDisposition) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionResponseDisposition = .Allow
|
||||
|
||||
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
|
||||
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
|
||||
}
|
||||
|
||||
completionHandler(disposition)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task was changed to a download task.
|
||||
|
||||
- parameter session: The session containing the task that was replaced by a download task.
|
||||
- parameter dataTask: The data task that was replaced by a download task.
|
||||
- parameter downloadTask: The new download task that replaced the data task.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
|
||||
{
|
||||
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
|
||||
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
|
||||
} else {
|
||||
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
|
||||
self[downloadTask] = downloadDelegate
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task has received some of the expected data.
|
||||
|
||||
- parameter session: The session containing the data task that provided data.
|
||||
- parameter dataTask: The data task that provided data.
|
||||
- parameter data: A data object containing the transferred data.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
|
||||
dataTaskDidReceiveData(session, dataTask, data)
|
||||
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
|
||||
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Asks the delegate whether the data (or upload) task should store the response in the cache.
|
||||
|
||||
- parameter session: The session containing the data (or upload) task.
|
||||
- parameter dataTask: The data (or upload) task.
|
||||
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
|
||||
caching policy and the values of certain received headers, such as the Pragma
|
||||
and Cache-Control headers.
|
||||
- parameter completionHandler: A block that your handler must call, providing either the original proposed
|
||||
response, a modified version of that response, or NULL to prevent caching the
|
||||
response. If your delegate implements this method, it must call this completion
|
||||
handler; otherwise, your app leaks memory.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
willCacheResponse proposedResponse: NSCachedURLResponse,
|
||||
completionHandler: ((NSCachedURLResponse?) -> Void))
|
||||
{
|
||||
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
|
||||
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
|
||||
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
dataTask: dataTask,
|
||||
willCacheResponse: proposedResponse,
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
} else {
|
||||
completionHandler(proposedResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDownloadDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
|
||||
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
|
||||
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
|
||||
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that a download task has finished downloading.
|
||||
|
||||
- parameter session: The session containing the download task that finished.
|
||||
- parameter downloadTask: The download task that finished.
|
||||
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
|
||||
open the file for reading or move it to a permanent location in your app’s sandbox
|
||||
container directory before returning from this delegate method.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didFinishDownloadingToURL location: NSURL)
|
||||
{
|
||||
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
|
||||
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Periodically informs the delegate about the download’s progress.
|
||||
|
||||
- parameter session: The session containing the download task.
|
||||
- parameter downloadTask: The download task.
|
||||
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
|
||||
method was called.
|
||||
- parameter totalBytesWritten: The total number of bytes transferred so far.
|
||||
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
|
||||
header. If this header was not provided, the value is
|
||||
`NSURLSessionTransferSizeUnknown`.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64)
|
||||
{
|
||||
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
|
||||
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
downloadTask: downloadTask,
|
||||
didWriteData: bytesWritten,
|
||||
totalBytesWritten: totalBytesWritten,
|
||||
totalBytesExpectedToWrite: totalBytesExpectedToWrite
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the download task has resumed downloading.
|
||||
|
||||
- parameter session: The session containing the download task that finished.
|
||||
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
|
||||
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
|
||||
existing content, then this value is zero. Otherwise, this value is an
|
||||
integer representing the number of bytes on disk that do not need to be
|
||||
retrieved again.
|
||||
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
|
||||
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didResumeAtOffset fileOffset: Int64,
|
||||
expectedTotalBytes: Int64)
|
||||
{
|
||||
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
|
||||
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
downloadTask: downloadTask,
|
||||
didResumeAtOffset: fileOffset,
|
||||
expectedTotalBytes: expectedTotalBytes
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionStreamDelegate
|
||||
|
||||
var _streamTaskReadClosed: Any?
|
||||
var _streamTaskWriteClosed: Any?
|
||||
var _streamTaskBetterRouteDiscovered: Any?
|
||||
var _streamTaskDidBecomeInputStream: Any?
|
||||
|
||||
// MARK: - NSObject
|
||||
|
||||
public override func respondsToSelector(selector: Selector) -> Bool {
|
||||
switch selector {
|
||||
case "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
|
||||
default:
|
||||
return self.dynamicType.instancesRespondToSelector(selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
669
ipbc-Client/Pods/Alamofire/Source/MultipartFormData.swift
generated
Normal file
669
ipbc-Client/Pods/Alamofire/Source/MultipartFormData.swift
generated
Normal file
@ -0,0 +1,669 @@
|
||||
// MultipartFormData.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(iOS) || os(watchOS) || os(tvOS)
|
||||
import MobileCoreServices
|
||||
#elseif os(OSX)
|
||||
import CoreServices
|
||||
#endif
|
||||
|
||||
/**
|
||||
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
|
||||
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
|
||||
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
|
||||
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
|
||||
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
|
||||
|
||||
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
|
||||
and the w3 form documentation.
|
||||
|
||||
- https://www.ietf.org/rfc/rfc2388.txt
|
||||
- https://www.ietf.org/rfc/rfc2045.txt
|
||||
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
|
||||
*/
|
||||
public class MultipartFormData {
|
||||
|
||||
// MARK: - Helper Types
|
||||
|
||||
struct EncodingCharacters {
|
||||
static let CRLF = "\r\n"
|
||||
}
|
||||
|
||||
struct BoundaryGenerator {
|
||||
enum BoundaryType {
|
||||
case Initial, Encapsulated, Final
|
||||
}
|
||||
|
||||
static func randomBoundary() -> String {
|
||||
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
|
||||
}
|
||||
|
||||
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
|
||||
let boundaryText: String
|
||||
|
||||
switch boundaryType {
|
||||
case .Initial:
|
||||
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
|
||||
case .Encapsulated:
|
||||
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
|
||||
case .Final:
|
||||
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
|
||||
}
|
||||
|
||||
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
}
|
||||
}
|
||||
|
||||
class BodyPart {
|
||||
let headers: [String: String]
|
||||
let bodyStream: NSInputStream
|
||||
let bodyContentLength: UInt64
|
||||
var hasInitialBoundary = false
|
||||
var hasFinalBoundary = false
|
||||
|
||||
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
|
||||
self.headers = headers
|
||||
self.bodyStream = bodyStream
|
||||
self.bodyContentLength = bodyContentLength
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
|
||||
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
|
||||
|
||||
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
|
||||
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
|
||||
|
||||
/// The boundary used to separate the body parts in the encoded form data.
|
||||
public let boundary: String
|
||||
|
||||
private var bodyParts: [BodyPart]
|
||||
private var bodyPartError: NSError?
|
||||
private let streamBufferSize: Int
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/**
|
||||
Creates a multipart form data object.
|
||||
|
||||
- returns: The multipart form data object.
|
||||
*/
|
||||
public init() {
|
||||
self.boundary = BoundaryGenerator.randomBoundary()
|
||||
self.bodyParts = []
|
||||
|
||||
/**
|
||||
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
|
||||
* information, please refer to the following article:
|
||||
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
|
||||
*/
|
||||
|
||||
self.streamBufferSize = 1024
|
||||
}
|
||||
|
||||
// MARK: - Body Parts
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
|
||||
- Encoded data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String) {
|
||||
let headers = contentHeaders(name: name)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
|
||||
- `Content-Type: #{generated mimeType}` (HTTP Header)
|
||||
- Encoded data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, mimeType: mimeType)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
|
||||
- `Content-Type: #{mimeType}` (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the file and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
|
||||
- `Content-Type: #{generated mimeType}` (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
|
||||
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
|
||||
system associated MIME type.
|
||||
|
||||
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
|
||||
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
|
||||
if let
|
||||
fileName = fileURL.lastPathComponent,
|
||||
pathExtension = fileURL.pathExtension
|
||||
{
|
||||
let mimeType = mimeTypeForPathExtension(pathExtension)
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the file and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
|
||||
- Content-Type: #{mimeType} (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
|
||||
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
|
||||
//============================================================
|
||||
// Check 1 - is file URL?
|
||||
//============================================================
|
||||
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 2 - is file URL reachable?
|
||||
//============================================================
|
||||
|
||||
var isReachable = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
|
||||
}
|
||||
|
||||
guard isReachable else {
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 3 - is file URL a directory?
|
||||
//============================================================
|
||||
|
||||
var isDirectory: ObjCBool = false
|
||||
|
||||
guard let
|
||||
path = fileURL.path
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 4 - can the file size be extracted?
|
||||
//============================================================
|
||||
|
||||
var bodyContentLength: UInt64?
|
||||
|
||||
do {
|
||||
if let
|
||||
path = fileURL.path,
|
||||
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
|
||||
{
|
||||
bodyContentLength = fileSize.unsignedLongLongValue
|
||||
}
|
||||
} catch {
|
||||
// No-op
|
||||
}
|
||||
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 5 - can a stream be created from file URL?
|
||||
//============================================================
|
||||
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the stream and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
|
||||
- `Content-Type: #{mimeType}` (HTTP Header)
|
||||
- Encoded stream data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter stream: The input stream to encode in the multipart form data.
|
||||
- parameter length: The content length of the stream.
|
||||
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(
|
||||
stream stream: NSInputStream,
|
||||
length: UInt64,
|
||||
name: String,
|
||||
fileName: String,
|
||||
mimeType: String)
|
||||
{
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- HTTP headers
|
||||
- Encoded stream data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter stream: The input stream to encode in the multipart form data.
|
||||
- parameter length: The content length of the stream.
|
||||
- parameter headers: The HTTP headers for the body part.
|
||||
*/
|
||||
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
|
||||
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
|
||||
bodyParts.append(bodyPart)
|
||||
}
|
||||
|
||||
// MARK: - Data Encoding
|
||||
|
||||
/**
|
||||
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
|
||||
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
|
||||
|
||||
- throws: An `NSError` if encoding encounters an error.
|
||||
|
||||
- returns: The encoded `NSData` if encoding is successful.
|
||||
*/
|
||||
public func encode() throws -> NSData {
|
||||
if let bodyPartError = bodyPartError {
|
||||
throw bodyPartError
|
||||
}
|
||||
|
||||
let encoded = NSMutableData()
|
||||
|
||||
bodyParts.first?.hasInitialBoundary = true
|
||||
bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in bodyParts {
|
||||
let encodedData = try encodeBodyPart(bodyPart)
|
||||
encoded.appendData(encodedData)
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
/**
|
||||
Writes the appended body parts into the given file URL.
|
||||
|
||||
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
|
||||
this approach is very memory efficient and should be used for large body part data.
|
||||
|
||||
- parameter fileURL: The file URL to write the multipart form data into.
|
||||
|
||||
- throws: An `NSError` if encoding encounters an error.
|
||||
*/
|
||||
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
|
||||
if let bodyPartError = bodyPartError {
|
||||
throw bodyPartError
|
||||
}
|
||||
|
||||
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)
|
||||
} else if !fileURL.fileURL {
|
||||
let failureReason = "The URL does not point to a valid file: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
}
|
||||
|
||||
let outputStream: NSOutputStream
|
||||
|
||||
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
|
||||
outputStream = possibleOutputStream
|
||||
} else {
|
||||
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
}
|
||||
|
||||
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outputStream.open()
|
||||
|
||||
self.bodyParts.first?.hasInitialBoundary = true
|
||||
self.bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in self.bodyParts {
|
||||
try writeBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
outputStream.close()
|
||||
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
}
|
||||
|
||||
// MARK: - Private - Body Part Encoding
|
||||
|
||||
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
|
||||
let encoded = NSMutableData()
|
||||
|
||||
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
|
||||
encoded.appendData(initialData)
|
||||
|
||||
let headerData = encodeHeaderDataForBodyPart(bodyPart)
|
||||
encoded.appendData(headerData)
|
||||
|
||||
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
|
||||
encoded.appendData(bodyStreamData)
|
||||
|
||||
if bodyPart.hasFinalBoundary {
|
||||
encoded.appendData(finalBoundaryData())
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
|
||||
var headerText = ""
|
||||
|
||||
for (key, value) in bodyPart.headers {
|
||||
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
|
||||
}
|
||||
headerText += EncodingCharacters.CRLF
|
||||
|
||||
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
}
|
||||
|
||||
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
|
||||
let inputStream = bodyPart.bodyStream
|
||||
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream.open()
|
||||
|
||||
var error: NSError?
|
||||
let encoded = NSMutableData()
|
||||
|
||||
while inputStream.hasBytesAvailable {
|
||||
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
|
||||
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
|
||||
|
||||
if inputStream.streamError != nil {
|
||||
error = inputStream.streamError
|
||||
break
|
||||
}
|
||||
|
||||
if bytesRead > 0 {
|
||||
encoded.appendBytes(buffer, length: bytesRead)
|
||||
} else if bytesRead < 0 {
|
||||
let failureReason = "Failed to read from input stream: \(inputStream)"
|
||||
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
|
||||
break
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
|
||||
if let error = error {
|
||||
throw error
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
// MARK: - Private - Writing Body Part to Output Stream
|
||||
|
||||
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeInitialBoundaryDataForBodyPart(
|
||||
bodyPart: BodyPart,
|
||||
toOutputStream outputStream: NSOutputStream)
|
||||
throws
|
||||
{
|
||||
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
|
||||
return try writeData(initialData, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
let headerData = encodeHeaderDataForBodyPart(bodyPart)
|
||||
return try writeData(headerData, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
let inputStream = bodyPart.bodyStream
|
||||
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream.open()
|
||||
|
||||
while inputStream.hasBytesAvailable {
|
||||
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
|
||||
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
|
||||
|
||||
if let streamError = inputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
|
||||
if bytesRead > 0 {
|
||||
if buffer.count != bytesRead {
|
||||
buffer = Array(buffer[0..<bytesRead])
|
||||
}
|
||||
|
||||
try writeBuffer(&buffer, toOutputStream: outputStream)
|
||||
} else if bytesRead < 0 {
|
||||
let failureReason = "Failed to read from input stream: \(inputStream)"
|
||||
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
}
|
||||
|
||||
private func writeFinalBoundaryDataForBodyPart(
|
||||
bodyPart: BodyPart,
|
||||
toOutputStream outputStream: NSOutputStream)
|
||||
throws
|
||||
{
|
||||
if bodyPart.hasFinalBoundary {
|
||||
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private - Writing Buffered Data to Output Stream
|
||||
|
||||
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
|
||||
var buffer = [UInt8](count: data.length, repeatedValue: 0)
|
||||
data.getBytes(&buffer, length: data.length)
|
||||
|
||||
return try writeBuffer(&buffer, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
|
||||
var bytesToWrite = buffer.count
|
||||
|
||||
while bytesToWrite > 0 {
|
||||
if outputStream.hasSpaceAvailable {
|
||||
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
|
||||
|
||||
if let streamError = outputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
|
||||
if bytesWritten < 0 {
|
||||
let failureReason = "Failed to write to output stream: \(outputStream)"
|
||||
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason)
|
||||
}
|
||||
|
||||
bytesToWrite -= bytesWritten
|
||||
|
||||
if bytesToWrite > 0 {
|
||||
buffer = Array(buffer[bytesWritten..<buffer.count])
|
||||
}
|
||||
} else if let streamError = outputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private - Mime Type
|
||||
|
||||
private func mimeTypeForPathExtension(pathExtension: String) -> String {
|
||||
if let
|
||||
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
|
||||
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
|
||||
{
|
||||
return contentType as String
|
||||
}
|
||||
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
// MARK: - Private - Content Headers
|
||||
|
||||
private func contentHeaders(name name: String) -> [String: String] {
|
||||
return ["Content-Disposition": "form-data; name=\"\(name)\""]
|
||||
}
|
||||
|
||||
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
|
||||
return [
|
||||
"Content-Disposition": "form-data; name=\"\(name)\"",
|
||||
"Content-Type": "\(mimeType)"
|
||||
]
|
||||
}
|
||||
|
||||
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
|
||||
return [
|
||||
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
|
||||
"Content-Type": "\(mimeType)"
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Private - Boundary Encoding
|
||||
|
||||
private func initialBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
|
||||
}
|
||||
|
||||
private func encapsulatedBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
|
||||
}
|
||||
|
||||
private func finalBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
|
||||
}
|
||||
|
||||
// MARK: - Private - Errors
|
||||
|
||||
private func setBodyPartError(error: NSError) {
|
||||
if bodyPartError == nil {
|
||||
bodyPartError = error
|
||||
}
|
||||
}
|
||||
}
|
||||
251
ipbc-Client/Pods/Alamofire/Source/ParameterEncoding.swift
generated
Normal file
251
ipbc-Client/Pods/Alamofire/Source/ParameterEncoding.swift
generated
Normal file
@ -0,0 +1,251 @@
|
||||
// ParameterEncoding.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
HTTP method definitions.
|
||||
|
||||
See https://tools.ietf.org/html/rfc7231#section-4.3
|
||||
*/
|
||||
public enum Method: String {
|
||||
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
|
||||
}
|
||||
|
||||
// MARK: ParameterEncoding
|
||||
|
||||
/**
|
||||
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
|
||||
`Content-Type` HTTP header field of an encoded request with HTTP body is set to
|
||||
`application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
|
||||
for how to encode collection types, the convention of appending `[]` to the key for array
|
||||
values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested
|
||||
dictionary values (`foo[bar]=baz`).
|
||||
|
||||
- `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
|
||||
set to `application/json`.
|
||||
|
||||
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
|
||||
according to the associated format and write options values, which is set as the body of the
|
||||
request. The `Content-Type` HTTP header field of an encoded request is set to
|
||||
`application/x-plist`.
|
||||
|
||||
- `Custom`: Uses the associated closure value to construct a new request given an existing request and
|
||||
parameters.
|
||||
*/
|
||||
public enum ParameterEncoding {
|
||||
case URL
|
||||
case URLEncodedInURL
|
||||
case JSON
|
||||
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
|
||||
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
|
||||
|
||||
/**
|
||||
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
|
||||
|
||||
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
|
||||
if any.
|
||||
*/
|
||||
public func encode(
|
||||
URLRequest: URLRequestConvertible,
|
||||
parameters: [String: AnyObject]?)
|
||||
-> (NSMutableURLRequest, NSError?)
|
||||
{
|
||||
var mutableURLRequest = URLRequest.URLRequest
|
||||
|
||||
guard let parameters = parameters else {
|
||||
return (mutableURLRequest, nil)
|
||||
}
|
||||
|
||||
var encodingError: NSError? = nil
|
||||
|
||||
switch self {
|
||||
case .URL, .URLEncodedInURL:
|
||||
func query(parameters: [String: AnyObject]) -> String {
|
||||
var components: [(String, String)] = []
|
||||
|
||||
for key in parameters.keys.sort(<) {
|
||||
let value = parameters[key]!
|
||||
components += queryComponents(key, value)
|
||||
}
|
||||
|
||||
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
|
||||
}
|
||||
|
||||
func encodesParametersInURL(method: Method) -> Bool {
|
||||
switch self {
|
||||
case .URLEncodedInURL:
|
||||
return true
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch method {
|
||||
case .GET, .HEAD, .DELETE:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
|
||||
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
|
||||
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
|
||||
URLComponents.percentEncodedQuery = percentEncodedQuery
|
||||
mutableURLRequest.URL = URLComponents.URL
|
||||
}
|
||||
} else {
|
||||
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
|
||||
mutableURLRequest.setValue(
|
||||
"application/x-www-form-urlencoded; charset=utf-8",
|
||||
forHTTPHeaderField: "Content-Type"
|
||||
)
|
||||
}
|
||||
|
||||
mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding(
|
||||
NSUTF8StringEncoding,
|
||||
allowLossyConversion: false
|
||||
)
|
||||
}
|
||||
case .JSON:
|
||||
do {
|
||||
let options = NSJSONWritingOptions()
|
||||
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
|
||||
|
||||
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
mutableURLRequest.HTTPBody = data
|
||||
} catch {
|
||||
encodingError = error as NSError
|
||||
}
|
||||
case .PropertyList(let format, let options):
|
||||
do {
|
||||
let data = try NSPropertyListSerialization.dataWithPropertyList(
|
||||
parameters,
|
||||
format: format,
|
||||
options: options
|
||||
)
|
||||
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
|
||||
mutableURLRequest.HTTPBody = data
|
||||
} catch {
|
||||
encodingError = error as NSError
|
||||
}
|
||||
case .Custom(let closure):
|
||||
(mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
|
||||
}
|
||||
|
||||
return (mutableURLRequest, encodingError)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
|
||||
|
||||
- parameter key: The key of the query component.
|
||||
- parameter value: The value of the query component.
|
||||
|
||||
- returns: The percent-escaped, URL encoded query string components.
|
||||
*/
|
||||
public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
|
||||
var components: [(String, String)] = []
|
||||
|
||||
if let dictionary = value as? [String: AnyObject] {
|
||||
for (nestedKey, value) in dictionary {
|
||||
components += queryComponents("\(key)[\(nestedKey)]", value)
|
||||
}
|
||||
} else if let array = value as? [AnyObject] {
|
||||
for value in array {
|
||||
components += queryComponents("\(key)[]", value)
|
||||
}
|
||||
} else {
|
||||
components.append((escape(key), escape("\(value)")))
|
||||
}
|
||||
|
||||
return components
|
||||
}
|
||||
|
||||
/**
|
||||
Returns a percent-escaped string following RFC 3986 for a query string key or value.
|
||||
|
||||
RFC 3986 states that the following characters are "reserved" characters.
|
||||
|
||||
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
|
||||
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
|
||||
|
||||
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
|
||||
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
|
||||
should be percent-escaped in the query string.
|
||||
|
||||
- parameter string: The string to be percent-escaped.
|
||||
|
||||
- returns: The percent-escaped string.
|
||||
*/
|
||||
public func escape(string: String) -> String {
|
||||
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
|
||||
let subDelimitersToEncode = "!$&'()*+,;="
|
||||
|
||||
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
|
||||
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
|
||||
|
||||
var escaped = ""
|
||||
|
||||
//==========================================================================================================
|
||||
//
|
||||
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
|
||||
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
|
||||
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
|
||||
// info, please refer to:
|
||||
//
|
||||
// - https://github.com/Alamofire/Alamofire/issues/206
|
||||
//
|
||||
//==========================================================================================================
|
||||
|
||||
if #available(iOS 8.3, OSX 10.10, *) {
|
||||
escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
|
||||
} else {
|
||||
let batchSize = 50
|
||||
var index = string.startIndex
|
||||
|
||||
while index != string.endIndex {
|
||||
let startIndex = index
|
||||
let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
|
||||
let range = Range(start: startIndex, end: endIndex)
|
||||
|
||||
let substring = string.substringWithRange(range)
|
||||
|
||||
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring
|
||||
|
||||
index = endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
}
|
||||
536
ipbc-Client/Pods/Alamofire/Source/Request.swift
generated
Normal file
536
ipbc-Client/Pods/Alamofire/Source/Request.swift
generated
Normal file
@ -0,0 +1,536 @@
|
||||
// Request.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 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 sending a request and receiving the response and associated data from the server, as well as
|
||||
managing its underlying `NSURLSessionTask`.
|
||||
*/
|
||||
public class Request {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The delegate for the underlying task.
|
||||
public let delegate: TaskDelegate
|
||||
|
||||
/// The underlying task.
|
||||
public var task: NSURLSessionTask { return delegate.task }
|
||||
|
||||
/// The session belonging to the underlying task.
|
||||
public let session: NSURLSession
|
||||
|
||||
/// The request sent or to be sent to the server.
|
||||
public var request: NSURLRequest? { return task.originalRequest }
|
||||
|
||||
/// The response received from the server, if any.
|
||||
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
|
||||
|
||||
/// The progress of the request lifecycle.
|
||||
public var progress: NSProgress { return delegate.progress }
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
init(session: NSURLSession, task: NSURLSessionTask) {
|
||||
self.session = session
|
||||
|
||||
switch task {
|
||||
case is NSURLSessionUploadTask:
|
||||
self.delegate = UploadTaskDelegate(task: task)
|
||||
case is NSURLSessionDataTask:
|
||||
self.delegate = DataTaskDelegate(task: task)
|
||||
case is NSURLSessionDownloadTask:
|
||||
self.delegate = DownloadTaskDelegate(task: task)
|
||||
default:
|
||||
self.delegate = TaskDelegate(task: task)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Authentication
|
||||
|
||||
/**
|
||||
Associates an HTTP Basic credential with the request.
|
||||
|
||||
- parameter user: The user.
|
||||
- parameter password: The password.
|
||||
- parameter persistence: The URL credential persistence. `.ForSession` by default.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func authenticate(
|
||||
user user: String,
|
||||
password: String,
|
||||
persistence: NSURLCredentialPersistence = .ForSession)
|
||||
-> Self
|
||||
{
|
||||
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
|
||||
|
||||
return authenticate(usingCredential: credential)
|
||||
}
|
||||
|
||||
/**
|
||||
Associates a specified credential with the request.
|
||||
|
||||
- parameter credential: The credential.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
|
||||
delegate.credential = credential
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Progress
|
||||
|
||||
/**
|
||||
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
|
||||
to write.
|
||||
- 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.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
|
||||
if let uploadDelegate = delegate as? UploadTaskDelegate {
|
||||
uploadDelegate.uploadProgress = closure
|
||||
} else if let dataDelegate = delegate as? DataTaskDelegate {
|
||||
dataDelegate.dataProgress = closure
|
||||
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
|
||||
downloadDelegate.downloadProgress = closure
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
|
||||
|
||||
This closure returns the bytes most recently received from the server, not including data from previous calls.
|
||||
If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
|
||||
also important to note that the `response` closure will be called with nil `responseData`.
|
||||
|
||||
- parameter closure: The code to be executed periodically during the lifecycle of the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func stream(closure: (NSData -> Void)? = nil) -> Self {
|
||||
if let dataDelegate = delegate as? DataTaskDelegate {
|
||||
dataDelegate.dataStream = closure
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/**
|
||||
Suspends the request.
|
||||
*/
|
||||
public func suspend() {
|
||||
task.suspend()
|
||||
}
|
||||
|
||||
/**
|
||||
Resumes the request.
|
||||
*/
|
||||
public func resume() {
|
||||
task.resume()
|
||||
}
|
||||
|
||||
/**
|
||||
Cancels the request.
|
||||
*/
|
||||
public func cancel() {
|
||||
if let
|
||||
downloadDelegate = delegate as? DownloadTaskDelegate,
|
||||
downloadTask = downloadDelegate.downloadTask
|
||||
{
|
||||
downloadTask.cancelByProducingResumeData { data in
|
||||
downloadDelegate.resumeData = data
|
||||
}
|
||||
} else {
|
||||
task.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TaskDelegate
|
||||
|
||||
/**
|
||||
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 {
|
||||
|
||||
/// The serial operation queue used to execute all operations after the task completes.
|
||||
public let queue: NSOperationQueue
|
||||
|
||||
let task: NSURLSessionTask
|
||||
let progress: NSProgress
|
||||
|
||||
var data: NSData? { return nil }
|
||||
var error: NSError?
|
||||
|
||||
var credential: NSURLCredential?
|
||||
|
||||
init(task: NSURLSessionTask) {
|
||||
self.task = task
|
||||
self.progress = NSProgress(totalUnitCount: 0)
|
||||
self.queue = {
|
||||
let operationQueue = NSOperationQueue()
|
||||
operationQueue.maxConcurrentOperationCount = 1
|
||||
operationQueue.suspended = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
operationQueue.qualityOfService = NSQualityOfService.Utility
|
||||
}
|
||||
|
||||
return operationQueue
|
||||
}()
|
||||
}
|
||||
|
||||
deinit {
|
||||
queue.cancelAllOperations()
|
||||
queue.suspended = false
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
|
||||
var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
|
||||
var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
willPerformHTTPRedirection response: NSHTTPURLResponse,
|
||||
newRequest request: NSURLRequest,
|
||||
completionHandler: ((NSURLRequest?) -> Void))
|
||||
{
|
||||
var redirectRequest: NSURLRequest? = request
|
||||
|
||||
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
|
||||
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
|
||||
}
|
||||
|
||||
completionHandler(redirectRequest)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
||||
var credential: NSURLCredential?
|
||||
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
|
||||
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
|
||||
let host = challenge.protectionSpace.host
|
||||
|
||||
if let
|
||||
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
|
||||
serverTrust = challenge.protectionSpace.serverTrust
|
||||
{
|
||||
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
|
||||
disposition = .UseCredential
|
||||
credential = NSURLCredential(forTrust: serverTrust)
|
||||
} else {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if challenge.previousFailureCount > 0 {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
} else {
|
||||
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
|
||||
|
||||
if credential != nil {
|
||||
disposition = .UseCredential
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
completionHandler(disposition, credential)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
|
||||
{
|
||||
var bodyStream: NSInputStream?
|
||||
|
||||
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
|
||||
bodyStream = taskNeedNewBodyStream(session, task)
|
||||
}
|
||||
|
||||
completionHandler(bodyStream)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let taskDidCompleteWithError = taskDidCompleteWithError {
|
||||
taskDidCompleteWithError(session, task, error)
|
||||
} else {
|
||||
if let error = error {
|
||||
self.error = error
|
||||
|
||||
if let
|
||||
downloadDelegate = self as? DownloadTaskDelegate,
|
||||
userInfo = error.userInfo as? [String: AnyObject],
|
||||
resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
|
||||
{
|
||||
downloadDelegate.resumeData = resumeData
|
||||
}
|
||||
}
|
||||
|
||||
queue.suspended = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DataTaskDelegate
|
||||
|
||||
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
|
||||
var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
|
||||
|
||||
private var totalBytesReceived: Int64 = 0
|
||||
private var mutableData: NSMutableData
|
||||
override var data: NSData? {
|
||||
if dataStream != nil {
|
||||
return nil
|
||||
} else {
|
||||
return mutableData
|
||||
}
|
||||
}
|
||||
|
||||
private var expectedContentLength: Int64?
|
||||
private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
|
||||
private var dataStream: ((data: NSData) -> Void)?
|
||||
|
||||
override init(task: NSURLSessionTask) {
|
||||
mutableData = NSMutableData()
|
||||
super.init(task: task)
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDataDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
|
||||
var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
|
||||
var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
|
||||
var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse response: NSURLResponse,
|
||||
completionHandler: (NSURLSessionResponseDisposition -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionResponseDisposition = .Allow
|
||||
|
||||
expectedContentLength = response.expectedContentLength
|
||||
|
||||
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
|
||||
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
|
||||
}
|
||||
|
||||
completionHandler(disposition)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
|
||||
{
|
||||
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
|
||||
dataTaskDidReceiveData(session, dataTask, data)
|
||||
} else {
|
||||
if let dataStream = dataStream {
|
||||
dataStream(data: data)
|
||||
} else {
|
||||
mutableData.appendData(data)
|
||||
}
|
||||
|
||||
totalBytesReceived += data.length
|
||||
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
|
||||
|
||||
progress.totalUnitCount = totalBytesExpected
|
||||
progress.completedUnitCount = totalBytesReceived
|
||||
|
||||
dataProgress?(
|
||||
bytesReceived: Int64(data.length),
|
||||
totalBytesReceived: totalBytesReceived,
|
||||
totalBytesExpectedToReceive: totalBytesExpected
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
willCacheResponse proposedResponse: NSCachedURLResponse,
|
||||
completionHandler: ((NSCachedURLResponse?) -> Void))
|
||||
{
|
||||
var cachedResponse: NSCachedURLResponse? = proposedResponse
|
||||
|
||||
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
|
||||
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
|
||||
}
|
||||
|
||||
completionHandler(cachedResponse)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Request: CustomStringConvertible {
|
||||
|
||||
/**
|
||||
The textual representation used when written to an output stream, which includes the HTTP method and URL, as
|
||||
well as the response status code if a response has been received.
|
||||
*/
|
||||
public var description: String {
|
||||
var components: [String] = []
|
||||
|
||||
if let HTTPMethod = request?.HTTPMethod {
|
||||
components.append(HTTPMethod)
|
||||
}
|
||||
|
||||
if let URLString = request?.URL?.absoluteString {
|
||||
components.append(URLString)
|
||||
}
|
||||
|
||||
if let response = response {
|
||||
components.append("(\(response.statusCode))")
|
||||
}
|
||||
|
||||
return components.joinWithSeparator(" ")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Request: CustomDebugStringConvertible {
|
||||
func cURLRepresentation() -> String {
|
||||
var components = ["$ curl -i"]
|
||||
|
||||
guard let request = self.request 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!,
|
||||
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
|
||||
)
|
||||
|
||||
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values {
|
||||
for credential in credentials {
|
||||
components.append("-u \(credential.user!):\(credential.password!)")
|
||||
}
|
||||
} else {
|
||||
if let credential = delegate.credential {
|
||||
components.append("-u \(credential.user!):\(credential.password!)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if session.configuration.HTTPShouldSetCookies {
|
||||
if let
|
||||
cookieStorage = session.configuration.HTTPCookieStorage,
|
||||
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)\"")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
|
||||
for (field, value) in additionalHeaders {
|
||||
switch field {
|
||||
case "Cookie":
|
||||
continue
|
||||
default:
|
||||
components.append("-H \"\(field): \(value)\"")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let
|
||||
HTTPBodyData = request.HTTPBody,
|
||||
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
|
||||
{
|
||||
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
|
||||
components.append("-d \"\(escapedBody)\"")
|
||||
}
|
||||
|
||||
components.append("\"\(URL!.absoluteString)\"")
|
||||
|
||||
return components.joinWithSeparator(" \\\n\t")
|
||||
}
|
||||
|
||||
/// The textual representation used when written to an output stream, in the form of a cURL command.
|
||||
public var debugDescription: String {
|
||||
return cURLRepresentation()
|
||||
}
|
||||
}
|
||||
83
ipbc-Client/Pods/Alamofire/Source/Response.swift
generated
Normal file
83
ipbc-Client/Pods/Alamofire/Source/Response.swift
generated
Normal file
@ -0,0 +1,83 @@
|
||||
// Response.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Used to store all response data returned from a completed `Request`.
|
||||
public struct Response<Value, Error: ErrorType> {
|
||||
/// The URL request sent to the server.
|
||||
public let request: NSURLRequest?
|
||||
|
||||
/// The server's response to the URL request.
|
||||
public let response: NSHTTPURLResponse?
|
||||
|
||||
/// The data returned by the server.
|
||||
public let data: NSData?
|
||||
|
||||
/// The result of response serialization.
|
||||
public let result: Result<Value, Error>
|
||||
|
||||
/**
|
||||
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.
|
||||
|
||||
- returns: the new `Response` instance.
|
||||
*/
|
||||
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) {
|
||||
self.request = request
|
||||
self.response = response
|
||||
self.data = data
|
||||
self.result = result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Response: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure.
|
||||
public var description: String {
|
||||
return result.debugDescription
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Response: CustomDebugStringConvertible {
|
||||
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
|
||||
/// response, the server data and the response serialization result.
|
||||
public var debugDescription: String {
|
||||
var output: [String] = []
|
||||
|
||||
output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
|
||||
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
|
||||
output.append("[Data]: \(data?.length ?? 0) bytes")
|
||||
output.append("[Result]: \(result.debugDescription)")
|
||||
|
||||
return output.joinWithSeparator("\n")
|
||||
}
|
||||
}
|
||||
355
ipbc-Client/Pods/Alamofire/Source/ResponseSerialization.swift
generated
Normal file
355
ipbc-Client/Pods/Alamofire/Source/ResponseSerialization.swift
generated
Normal file
@ -0,0 +1,355 @@
|
||||
// ResponseSerialization.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: ResponseSerializer
|
||||
|
||||
/**
|
||||
The type in which all response serializers must conform to in order to serialize a response.
|
||||
*/
|
||||
public protocol ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializerType`.
|
||||
typealias SerializedObject
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
typealias ErrorObject: ErrorType
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/**
|
||||
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
|
||||
*/
|
||||
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializer`.
|
||||
public typealias SerializedObject = Value
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
public typealias ErrorObject = Error
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
|
||||
|
||||
/**
|
||||
Initializes the `ResponseSerializer` instance with the given serialize response closure.
|
||||
|
||||
- parameter serializeResponse: The closure used to serialize the response.
|
||||
|
||||
- returns: The new generic response serializer instance.
|
||||
*/
|
||||
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
|
||||
self.serializeResponse = serializeResponse
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Default
|
||||
|
||||
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 completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter queue: The queue on which the completion handler is dispatched.
|
||||
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
|
||||
and data.
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response<T: ResponseSerializerType>(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
responseSerializer: T,
|
||||
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
let result = responseSerializer.serializeResponse(
|
||||
self.request,
|
||||
self.response,
|
||||
self.delegate.data,
|
||||
self.delegate.error
|
||||
)
|
||||
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
let response = Response<T.SerializedObject, T.ErrorObject>(
|
||||
request: self.request,
|
||||
response: self.response,
|
||||
data: self.delegate.data,
|
||||
result: result
|
||||
)
|
||||
|
||||
completionHandler(response)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Data
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns the associated data as-is.
|
||||
|
||||
- returns: A data response serializer.
|
||||
*/
|
||||
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
|
||||
|
||||
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 .Success(validData)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
|
||||
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - String
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
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
|
||||
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)
|
||||
-> ResponseSerializer<String, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success("") }
|
||||
|
||||
guard let validData = data else {
|
||||
let failureReason = "String could not be serialized. Input data was nil."
|
||||
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
if let encodingName = response?.textEncodingName where encoding == nil {
|
||||
encoding = CFStringConvertEncodingToNSStringEncoding(
|
||||
CFStringConvertIANACharSetNameToEncoding(encodingName)
|
||||
)
|
||||
}
|
||||
|
||||
let actualEncoding = encoding ?? 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)
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
|
||||
server response, falling back to the default HTTP default character set,
|
||||
ISO-8859-1.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseString(
|
||||
encoding encoding: NSStringEncoding? = nil,
|
||||
completionHandler: Response<String, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSON
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
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.
|
||||
|
||||
- returns: A JSON object response serializer.
|
||||
*/
|
||||
public static func JSONResponseSerializer(
|
||||
options options: NSJSONReadingOptions = .AllowFragments)
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
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)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
|
||||
return .Success(JSON)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseJSON(
|
||||
options options: NSJSONReadingOptions = .AllowFragments,
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.JSONResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Property List
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
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.
|
||||
|
||||
- returns: A property list object response serializer.
|
||||
*/
|
||||
public static func propertyListResponseSerializer(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
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)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
|
||||
return .Success(plist)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- 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
|
||||
produced while creating the property list.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responsePropertyList(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.propertyListResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
101
ipbc-Client/Pods/Alamofire/Source/Result.swift
generated
Normal file
101
ipbc-Client/Pods/Alamofire/Source/Result.swift
generated
Normal file
@ -0,0 +1,101 @@
|
||||
// Result.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Used to represent whether a request was successful or encountered an error.
|
||||
|
||||
- Success: The request and all post processing operations were successful resulting in the serialization of the
|
||||
provided associated value.
|
||||
- Failure: The request encountered an error resulting in a failure. The associated values are the original data
|
||||
provided by the server as well as the error that caused the failure.
|
||||
*/
|
||||
public enum Result<Value, Error: ErrorType> {
|
||||
case Success(Value)
|
||||
case Failure(Error)
|
||||
|
||||
/// Returns `true` if the result is a success, `false` otherwise.
|
||||
public var isSuccess: Bool {
|
||||
switch self {
|
||||
case .Success:
|
||||
return true
|
||||
case .Failure:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the result is a failure, `false` otherwise.
|
||||
public var isFailure: Bool {
|
||||
return !isSuccess
|
||||
}
|
||||
|
||||
/// Returns the associated value if the result is a success, `nil` otherwise.
|
||||
public var value: Value? {
|
||||
switch self {
|
||||
case .Success(let value):
|
||||
return value
|
||||
case .Failure:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the associated error value if the result is a failure, `nil` otherwise.
|
||||
public var error: Error? {
|
||||
switch self {
|
||||
case .Success:
|
||||
return nil
|
||||
case .Failure(let error):
|
||||
return error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Result: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .Success:
|
||||
return "SUCCESS"
|
||||
case .Failure:
|
||||
return "FAILURE"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Result: CustomDebugStringConvertible {
|
||||
/// The debug textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure in addition to the value or error.
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .Success(let value):
|
||||
return "SUCCESS: \(value)"
|
||||
case .Failure(let error):
|
||||
return "FAILURE: \(error)"
|
||||
}
|
||||
}
|
||||
}
|
||||
305
ipbc-Client/Pods/Alamofire/Source/ServerTrustPolicy.swift
generated
Normal file
305
ipbc-Client/Pods/Alamofire/Source/ServerTrustPolicy.swift
generated
Normal file
@ -0,0 +1,305 @@
|
||||
// ServerTrustPolicy.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
|
||||
public class ServerTrustPolicyManager {
|
||||
/// The dictionary of policies mapped to a particular host.
|
||||
public let policies: [String: ServerTrustPolicy]
|
||||
|
||||
/**
|
||||
Initializes the `ServerTrustPolicyManager` instance with the given policies.
|
||||
|
||||
Since different servers and web services can have different leaf certificates, intermediate and even root
|
||||
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
|
||||
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
|
||||
pinning for host3 and disabling evaluation for host4.
|
||||
|
||||
- parameter policies: A dictionary of all policies mapped to a particular host.
|
||||
|
||||
- returns: The new `ServerTrustPolicyManager` instance.
|
||||
*/
|
||||
public init(policies: [String: ServerTrustPolicy]) {
|
||||
self.policies = policies
|
||||
}
|
||||
|
||||
/**
|
||||
Returns the `ServerTrustPolicy` for the given host if applicable.
|
||||
|
||||
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
|
||||
this method and implement more complex mapping implementations such as wildcards.
|
||||
|
||||
- parameter host: The host to use when searching for a matching policy.
|
||||
|
||||
- returns: The server trust policy for the given host if found.
|
||||
*/
|
||||
public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
|
||||
return policies[host]
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension NSURLSession {
|
||||
private struct AssociatedKeys {
|
||||
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
|
||||
}
|
||||
|
||||
var serverTrustPolicyManager: ServerTrustPolicyManager? {
|
||||
get {
|
||||
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
|
||||
}
|
||||
set (manager) {
|
||||
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ServerTrustPolicy
|
||||
|
||||
/**
|
||||
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
|
||||
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
|
||||
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
|
||||
|
||||
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
|
||||
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
|
||||
to route all communication over an HTTPS connection with pinning enabled.
|
||||
|
||||
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
|
||||
validate the host provided by the challenge. Applications are encouraged to always
|
||||
validate the host in production environments to guarantee the validity of the server's
|
||||
certificate chain.
|
||||
|
||||
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
|
||||
considered valid if one of the pinned certificates match one of the server certificates.
|
||||
By validating both the certificate chain and host, certificate pinning provides a very
|
||||
secure form of server trust validation mitigating most, if not all, MITM attacks.
|
||||
Applications are encouraged to always validate the host and require a valid certificate
|
||||
chain in production environments.
|
||||
|
||||
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
|
||||
valid if one of the pinned public keys match one of the server certificate public keys.
|
||||
By validating both the certificate chain and host, public key pinning provides a very
|
||||
secure form of server trust validation mitigating most, if not all, MITM attacks.
|
||||
Applications are encouraged to always validate the host and require a valid certificate
|
||||
chain in production environments.
|
||||
|
||||
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
|
||||
|
||||
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
|
||||
*/
|
||||
public enum ServerTrustPolicy {
|
||||
case PerformDefaultEvaluation(validateHost: Bool)
|
||||
case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
|
||||
case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
|
||||
case DisableEvaluation
|
||||
case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
|
||||
|
||||
// MARK: - Bundle Location
|
||||
|
||||
/**
|
||||
Returns all certificates within the given bundle with a `.cer` file extension.
|
||||
|
||||
- parameter bundle: The bundle to search for all `.cer` files.
|
||||
|
||||
- returns: All certificates within the given bundle.
|
||||
*/
|
||||
public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] {
|
||||
var certificates: [SecCertificate] = []
|
||||
|
||||
for path in bundle.pathsForResourcesOfType(".cer", inDirectory: nil) {
|
||||
if let
|
||||
certificateData = NSData(contentsOfFile: path),
|
||||
certificate = SecCertificateCreateWithData(nil, certificateData)
|
||||
{
|
||||
certificates.append(certificate)
|
||||
}
|
||||
}
|
||||
|
||||
return certificates
|
||||
}
|
||||
|
||||
/**
|
||||
Returns all public keys within the given bundle with a `.cer` file extension.
|
||||
|
||||
- parameter bundle: The bundle to search for all `*.cer` files.
|
||||
|
||||
- returns: All public keys within the given bundle.
|
||||
*/
|
||||
public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] {
|
||||
var publicKeys: [SecKey] = []
|
||||
|
||||
for certificate in certificatesInBundle(bundle) {
|
||||
if let publicKey = publicKeyForCertificate(certificate) {
|
||||
publicKeys.append(publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
return publicKeys
|
||||
}
|
||||
|
||||
// MARK: - Evaluation
|
||||
|
||||
/**
|
||||
Evaluates whether the server trust is valid for the given host.
|
||||
|
||||
- parameter serverTrust: The server trust to evaluate.
|
||||
- parameter host: The host of the challenge protection space.
|
||||
|
||||
- returns: Whether the server trust is valid.
|
||||
*/
|
||||
public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
|
||||
var serverTrustIsValid = false
|
||||
|
||||
switch self {
|
||||
case let .PerformDefaultEvaluation(validateHost):
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
serverTrustIsValid = trustIsValid(serverTrust)
|
||||
case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
|
||||
if validateCertificateChain {
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
|
||||
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
|
||||
|
||||
serverTrustIsValid = trustIsValid(serverTrust)
|
||||
} else {
|
||||
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
|
||||
|
||||
//======================================================================================================
|
||||
// The following `[] +` is a temporary workaround for a Swift 2.0 compiler error. This workaround should
|
||||
// be removed once the following radar has been resolved:
|
||||
// - http://openradar.appspot.com/radar?id=6082025006039040
|
||||
//======================================================================================================
|
||||
|
||||
let pinnedCertificatesDataArray = certificateDataForCertificates([] + pinnedCertificates)
|
||||
|
||||
outerLoop: for serverCertificateData in serverCertificatesDataArray {
|
||||
for pinnedCertificateData in pinnedCertificatesDataArray {
|
||||
if serverCertificateData.isEqualToData(pinnedCertificateData) {
|
||||
serverTrustIsValid = true
|
||||
break outerLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
|
||||
var certificateChainEvaluationPassed = true
|
||||
|
||||
if validateCertificateChain {
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
certificateChainEvaluationPassed = trustIsValid(serverTrust)
|
||||
}
|
||||
|
||||
if certificateChainEvaluationPassed {
|
||||
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
|
||||
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
|
||||
if serverPublicKey.isEqual(pinnedPublicKey) {
|
||||
serverTrustIsValid = true
|
||||
break outerLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case .DisableEvaluation:
|
||||
serverTrustIsValid = true
|
||||
case let .CustomEvaluation(closure):
|
||||
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
|
||||
}
|
||||
|
||||
return serverTrustIsValid
|
||||
}
|
||||
|
||||
// MARK: - Private - Trust Validation
|
||||
|
||||
private func trustIsValid(trust: SecTrust) -> Bool {
|
||||
var isValid = false
|
||||
|
||||
var result = SecTrustResultType(kSecTrustResultInvalid)
|
||||
let status = SecTrustEvaluate(trust, &result)
|
||||
|
||||
if status == errSecSuccess {
|
||||
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
|
||||
let proceed = SecTrustResultType(kSecTrustResultProceed)
|
||||
|
||||
isValid = result == unspecified || result == proceed
|
||||
}
|
||||
|
||||
return isValid
|
||||
}
|
||||
|
||||
// MARK: - Private - Certificate Data
|
||||
|
||||
private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
|
||||
var certificates: [SecCertificate] = []
|
||||
|
||||
for index in 0..<SecTrustGetCertificateCount(trust) {
|
||||
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
|
||||
certificates.append(certificate)
|
||||
}
|
||||
}
|
||||
|
||||
return certificateDataForCertificates(certificates)
|
||||
}
|
||||
|
||||
private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
|
||||
return certificates.map { SecCertificateCopyData($0) as NSData }
|
||||
}
|
||||
|
||||
// MARK: - Private - Public Key Extraction
|
||||
|
||||
private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
|
||||
var publicKeys: [SecKey] = []
|
||||
|
||||
for index in 0..<SecTrustGetCertificateCount(trust) {
|
||||
if let
|
||||
certificate = SecTrustGetCertificateAtIndex(trust, index),
|
||||
publicKey = publicKeyForCertificate(certificate)
|
||||
{
|
||||
publicKeys.append(publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
return publicKeys
|
||||
}
|
||||
|
||||
private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
|
||||
var publicKey: SecKey?
|
||||
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
var trust: SecTrust?
|
||||
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
|
||||
|
||||
if let trust = trust where trustCreationStatus == errSecSuccess {
|
||||
publicKey = SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
|
||||
return publicKey
|
||||
}
|
||||
}
|
||||
180
ipbc-Client/Pods/Alamofire/Source/Stream.swift
generated
Normal file
180
ipbc-Client/Pods/Alamofire/Source/Stream.swift
generated
Normal file
@ -0,0 +1,180 @@
|
||||
// Stream.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(watchOS)
|
||||
|
||||
@available(iOS 9.0, OSX 10.11, *)
|
||||
extension Manager {
|
||||
private enum Streamable {
|
||||
case Stream(String, Int)
|
||||
case NetService(NSNetService)
|
||||
}
|
||||
|
||||
private func stream(streamable: Streamable) -> Request {
|
||||
var streamTask: NSURLSessionStreamTask!
|
||||
|
||||
switch streamable {
|
||||
case .Stream(let hostName, let port):
|
||||
dispatch_sync(queue) {
|
||||
streamTask = self.session.streamTaskWithHostName(hostName, port: port)
|
||||
}
|
||||
case .NetService(let netService):
|
||||
dispatch_sync(queue) {
|
||||
streamTask = self.session.streamTaskWithNetService(netService)
|
||||
}
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: streamTask)
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for bidirectional streaming with the given hostname and port.
|
||||
|
||||
- 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.
|
||||
*/
|
||||
public func stream(hostName hostName: String, port: Int) -> Request {
|
||||
return stream(.Stream(hostName, port))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for bidirectional streaming with the given `NSNetService`.
|
||||
|
||||
- parameter netService: The net service used to identify the endpoint.
|
||||
|
||||
- returns: The created stream request.
|
||||
*/
|
||||
public func stream(netService netService: NSNetService) -> Request {
|
||||
return stream(.NetService(netService))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
@available(iOS 9.0, OSX 10.11, *)
|
||||
extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`.
|
||||
public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskReadClosed = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`.
|
||||
public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskWriteClosed = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`.
|
||||
public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskBetterRouteDiscovered = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`.
|
||||
public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? {
|
||||
get {
|
||||
return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskDidBecomeInputStream = newValue
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the read side of the connection has been closed.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskReadClosed?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the write side of the connection has been closed.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskWriteClosed?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the system has determined that a better route to the host is available.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskBetterRouteDiscovered?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the stream task has been completed and provides the unopened stream objects.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
- parameter inputStream: The new input stream.
|
||||
- parameter outputStream: The new output stream.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
streamTask: NSURLSessionStreamTask,
|
||||
didBecomeInputStream inputStream: NSInputStream,
|
||||
outputStream: NSOutputStream)
|
||||
{
|
||||
streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
372
ipbc-Client/Pods/Alamofire/Source/Upload.swift
generated
Normal file
372
ipbc-Client/Pods/Alamofire/Source/Upload.swift
generated
Normal file
@ -0,0 +1,372 @@
|
||||
// Upload.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Manager {
|
||||
private enum Uploadable {
|
||||
case Data(NSURLRequest, NSData)
|
||||
case File(NSURLRequest, NSURL)
|
||||
case Stream(NSURLRequest, NSInputStream)
|
||||
}
|
||||
|
||||
private func upload(uploadable: Uploadable) -> Request {
|
||||
var uploadTask: NSURLSessionUploadTask!
|
||||
var HTTPBodyStream: NSInputStream?
|
||||
|
||||
switch uploadable {
|
||||
case .Data(let request, let data):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
|
||||
}
|
||||
case .File(let request, let fileURL):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
|
||||
}
|
||||
case .Stream(let request, let stream):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithStreamedRequest(request)
|
||||
}
|
||||
|
||||
HTTPBodyStream = stream
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: uploadTask)
|
||||
|
||||
if HTTPBodyStream != nil {
|
||||
request.delegate.taskNeedNewBodyStream = { _, _ in
|
||||
return HTTPBodyStream
|
||||
}
|
||||
}
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: File
|
||||
|
||||
/**
|
||||
Creates a request for uploading a file to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
- parameter file: The file to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
|
||||
return upload(.File(URLRequest.URLRequest, file))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading a file to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter file: The file to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
file: NSURL)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
return upload(mutableURLRequest, file: file)
|
||||
}
|
||||
|
||||
// MARK: Data
|
||||
|
||||
/**
|
||||
Creates a request for uploading data to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
|
||||
return upload(.Data(URLRequest.URLRequest, data))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading data to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter data: The data to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
data: NSData)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(mutableURLRequest, data: data)
|
||||
}
|
||||
|
||||
// MARK: Stream
|
||||
|
||||
/**
|
||||
Creates a request for uploading a stream to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
|
||||
return upload(.Stream(URLRequest.URLRequest, stream))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading a stream to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
stream: NSInputStream)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(mutableURLRequest, stream: stream)
|
||||
}
|
||||
|
||||
// MARK: MultipartFormData
|
||||
|
||||
/// Default memory threshold used when encoding `MultipartFormData`.
|
||||
public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024
|
||||
|
||||
/**
|
||||
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
|
||||
streaming information.
|
||||
- Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
|
||||
error.
|
||||
*/
|
||||
public enum MultipartFormDataEncodingResult {
|
||||
case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?)
|
||||
case Failure(ErrorType)
|
||||
}
|
||||
|
||||
/**
|
||||
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
|
||||
used for larger payloads such as video content.
|
||||
|
||||
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
|
||||
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
|
||||
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
|
||||
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
|
||||
technique was used.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(
|
||||
mutableURLRequest,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
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
|
||||
used for larger payloads such as video content.
|
||||
|
||||
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
|
||||
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
|
||||
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
|
||||
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
|
||||
technique was used.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
URLRequest: URLRequestConvertible,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
|
||||
let formData = MultipartFormData()
|
||||
multipartFormData(formData)
|
||||
|
||||
let URLRequestWithContentType = URLRequest.URLRequest
|
||||
URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
|
||||
|
||||
let isBackgroundSession = self.session.configuration.identifier != nil
|
||||
|
||||
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
|
||||
do {
|
||||
let data = try formData.encode()
|
||||
let encodingResult = MultipartFormDataEncodingResult.Success(
|
||||
request: self.upload(URLRequestWithContentType, data: data),
|
||||
streamingFromDisk: false,
|
||||
streamFileURL: nil
|
||||
)
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(encodingResult)
|
||||
}
|
||||
} catch {
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(.Failure(error as NSError))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let fileManager = NSFileManager.defaultManager()
|
||||
let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
|
||||
let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data")
|
||||
let fileName = NSUUID().UUIDString
|
||||
let fileURL = directoryURL.URLByAppendingPathComponent(fileName)
|
||||
|
||||
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),
|
||||
streamingFromDisk: true,
|
||||
streamFileURL: fileURL
|
||||
)
|
||||
encodingCompletion?(encodingResult)
|
||||
}
|
||||
} catch {
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(.Failure(error as NSError))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Request {
|
||||
|
||||
// MARK: - UploadTaskDelegate
|
||||
|
||||
class UploadTaskDelegate: DataTaskDelegate {
|
||||
var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask }
|
||||
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didSendBodyData bytesSent: Int64,
|
||||
totalBytesSent: Int64,
|
||||
totalBytesExpectedToSend: Int64)
|
||||
{
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToSend
|
||||
progress.completedUnitCount = totalBytesSent
|
||||
|
||||
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
189
ipbc-Client/Pods/Alamofire/Source/Validation.swift
generated
Normal file
189
ipbc-Client/Pods/Alamofire/Source/Validation.swift
generated
Normal file
@ -0,0 +1,189 @@
|
||||
// Validation.swift
|
||||
//
|
||||
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Used to represent whether validation was successful or encountered an error resulting in a failure.
|
||||
|
||||
- Success: The validation was successful.
|
||||
- Failure: The validation failed encountering the provided error.
|
||||
*/
|
||||
public enum ValidationResult {
|
||||
case Success
|
||||
case Failure(NSError)
|
||||
}
|
||||
|
||||
/**
|
||||
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
|
||||
|
||||
/**
|
||||
Validates the request, using the specified closure.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter validation: A closure to validate the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate(validation: Validation) -> Self {
|
||||
delegate.queue.addOperationWithBlock {
|
||||
if let
|
||||
response = self.response where self.delegate.error == nil,
|
||||
case let .Failure(error) = validation(self.request, response)
|
||||
{
|
||||
self.delegate.error = error
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Status Code
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the specified range.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter range: The range of acceptable status codes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
|
||||
return validate { _, response in
|
||||
if acceptableStatusCode.contains(response.statusCode) {
|
||||
return .Success
|
||||
} else {
|
||||
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
|
||||
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Content-Type
|
||||
|
||||
private struct MIMEType {
|
||||
let type: String
|
||||
let subtype: String
|
||||
|
||||
init?(_ string: String) {
|
||||
let components: [String] = {
|
||||
let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
|
||||
let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
|
||||
return split.componentsSeparatedByString("/")
|
||||
}()
|
||||
|
||||
if let
|
||||
type = components.first,
|
||||
subtype = components.last
|
||||
{
|
||||
self.type = type
|
||||
self.subtype = subtype
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func matches(MIME: MIMEType) -> Bool {
|
||||
switch (type, subtype) {
|
||||
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Validates that the response has a content type in the specified array.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
|
||||
return validate { _, response in
|
||||
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
|
||||
|
||||
if let
|
||||
responseContentType = response.MIMEType,
|
||||
responseMIMEType = MIMEType(responseContentType)
|
||||
{
|
||||
for contentType in acceptableContentTypes {
|
||||
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for contentType in acceptableContentTypes {
|
||||
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let failureReason: String
|
||||
|
||||
if let responseContentType = response.MIMEType {
|
||||
failureReason = (
|
||||
"Response content type \"\(responseContentType)\" does not match any acceptable " +
|
||||
"content types: \(acceptableContentTypes)"
|
||||
)
|
||||
} else {
|
||||
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
|
||||
}
|
||||
|
||||
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Automatic
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
|
||||
type matches any specified in the Accept HTTP header field.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate() -> Self {
|
||||
let acceptableStatusCodes: Range<Int> = 200..<300
|
||||
let acceptableContentTypes: [String] = {
|
||||
if let accept = request?.valueForHTTPHeaderField("Accept") {
|
||||
return accept.componentsSeparatedByString(",")
|
||||
}
|
||||
|
||||
return ["*/*"]
|
||||
}()
|
||||
|
||||
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
|
||||
}
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
{
|
||||
"name": "ReachabilitySwift",
|
||||
"version": "1.1",
|
||||
"homepage": "https://github.com/ashleymills/Reachability.swift",
|
||||
"authors": {
|
||||
"Ashley Mills": "ashleymills@mac.com"
|
||||
},
|
||||
"summary": "Replacement for Apple's Reachability re-written in Swift with callbacks.",
|
||||
"license": {
|
||||
"type": "MIT"
|
||||
},
|
||||
"platforms": {
|
||||
"ios": "8.0",
|
||||
"osx": "10.9"
|
||||
},
|
||||
"source": {
|
||||
"git": "https://github.com/ashleymills/Reachability.swift.git",
|
||||
"tag": "v1.1"
|
||||
},
|
||||
"source_files": "Reachability.swift",
|
||||
"frameworks": "SystemConfiguration",
|
||||
"requires_arc": true
|
||||
}
|
||||
20
ipbc-Client/Pods/Manifest.lock
generated
20
ipbc-Client/Pods/Manifest.lock
generated
@ -1,22 +1,10 @@
|
||||
PODS:
|
||||
- ReachabilitySwift (1.1)
|
||||
- SwiftHTTP (0.9.5)
|
||||
- Alamofire (3.1.2)
|
||||
|
||||
DEPENDENCIES:
|
||||
- ReachabilitySwift (from `https://github.com/ashleymills/Reachability.swift`)
|
||||
- SwiftHTTP (~> 0.9.4)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
ReachabilitySwift:
|
||||
:git: https://github.com/ashleymills/Reachability.swift
|
||||
|
||||
CHECKOUT OPTIONS:
|
||||
ReachabilitySwift:
|
||||
:commit: eca2517c69b321e9c4ce464be45c33f3a8dfe14e
|
||||
:git: https://github.com/ashleymills/Reachability.swift
|
||||
- Alamofire (~> 3.0)
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
ReachabilitySwift: 1e53abddb01111deac0d229dabdb8bb043567b18
|
||||
SwiftHTTP: cd7b248bc07db02926ff54cf19b580b78f7abfa1
|
||||
Alamofire: 7c16ca65f3c7e681fd925fd7f2dec7747ff96855
|
||||
|
||||
COCOAPODS: 0.38.2
|
||||
COCOAPODS: 0.39.0
|
||||
|
||||
619
ipbc-Client/Pods/Pods.xcodeproj/project.pbxproj
generated
619
ipbc-Client/Pods/Pods.xcodeproj/project.pbxproj
generated
@ -7,116 +7,153 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
01259B29E7B75268A2E4639449AE759B /* HTTPRequestSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8F691D8FF9BB3BC94F769A03D7BF6E9 /* HTTPRequestSerializer.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
|
||||
0349D3641FA40BDE258EBB89DAB0CE56 /* Pods-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 32E45C833AF7E16855BBB75F3725A934 /* Pods-dummy.m */; };
|
||||
0FBBF858C750BD72A6B9D05357699EAE /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F92D703483EAB54823ABF39B5C024CEC /* Cocoa.framework */; };
|
||||
2EADFA6A6D8F80BF28466A3207F1880F /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DB25E462135DFC183C89E6E66E596FD /* SystemConfiguration.framework */; };
|
||||
4CB56104486E20F3D1A8F0F048473FD5 /* HTTPSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F10E5E0800AB435D50B75E004F0E5E /* HTTPSecurity.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
|
||||
50CB3873CE44B09068C6650F7BC1B62E /* ReachabilitySwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 40BA696D0257C0C38DB22F4F7C0B3024 /* ReachabilitySwift-dummy.m */; };
|
||||
588B0C8E4C2F7849023F60069A7AF094 /* HTTPTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = D15F651F060B286D433A13109B37091C /* HTTPTask.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
|
||||
5C601DFC35BD0AA393A1C6B29E45B133 /* HTTPUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EF017F3903CAB51D4BF613B96370A46 /* HTTPUpload.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
|
||||
69079EC9A7A8AB065AD21904666AACEC /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F92D703483EAB54823ABF39B5C024CEC /* Cocoa.framework */; };
|
||||
6E0B32BB9D7E10891D49EF9D239B20D8 /* ReachabilitySwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 42443BE4CFDB3686DCE7BD49A7251FBD /* ReachabilitySwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
719D747C7DAF00843C07D2368BD9BB8F /* Pods-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7B4DE76AFBBDE97856185D579F920FFA /* Pods-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
723C10D67F21BFB2AE43FCE47E18A921 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F92D703483EAB54823ABF39B5C024CEC /* Cocoa.framework */; };
|
||||
7EACDBE6B531B186A1ECDF5838A92549 /* SwiftHTTP-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F67503E72BAEAD05D13DF670F7D88CCD /* SwiftHTTP-dummy.m */; };
|
||||
82FEFB5F8E2CE9FF43EDE67D41F774D6 /* Reachability.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1C786CCECAB03DBBA6174C79837A10 /* Reachability.swift */; };
|
||||
C9D551E664541B6D44F0DDDBC094DE22 /* SwiftHTTP-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E9E80ACD8021743B20121DDA0D7F457 /* SwiftHTTP-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
F556360A6CF9AD4B39927790324A61AA /* HTTPResponseSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C533A7E04B2700CB774CD9B10CC75014 /* HTTPResponseSerializer.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
|
||||
03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */; };
|
||||
0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */; };
|
||||
2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
31F7DD538B22F0EBE774CF164AF5F64B /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1CA6EBC2E57D96052268211209D6AA52 /* Cocoa.framework */; };
|
||||
385267D5E1667CA0120A7DDFAE7C05AD /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1CA6EBC2E57D96052268211209D6AA52 /* Cocoa.framework */; };
|
||||
4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */; };
|
||||
80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */; };
|
||||
82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */; };
|
||||
8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */; };
|
||||
91C36C428505A897B4AED8BC3F27ECAA /* Pods-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */; };
|
||||
A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */; };
|
||||
B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */; };
|
||||
B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */; };
|
||||
C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 779B19103BE8402A434ED95F67573911 /* Validation.swift */; };
|
||||
D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */; };
|
||||
D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */; };
|
||||
EA6FDB353E0AE2963BFCD155E100F836 /* Pods-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */; };
|
||||
FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */; };
|
||||
FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
039A210DD9F51E9946D160F7EEDCCA0B /* PBXContainerItemProxy */ = {
|
||||
66FB30F40015337B10768205C744F9CB /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 0C66C30381F86C3D642FC983CCADEBB6;
|
||||
remoteInfo = ReachabilitySwift;
|
||||
};
|
||||
EC3ED57D07B7D0FB9BC30494E35FFDB9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = AB33B84630B10DE253DA6B29E233F61D;
|
||||
remoteInfo = SwiftHTTP;
|
||||
remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC;
|
||||
remoteInfo = Alamofire;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
095D927AF11FDF42492621C1C67329C0 /* SwiftHTTP.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftHTTP.xcconfig; sourceTree = "<group>"; };
|
||||
097C0D457717655774F1C6B4482469C1 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
0EF017F3903CAB51D4BF613B96370A46 /* HTTPUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HTTPUpload.swift; sourceTree = "<group>"; };
|
||||
0FF578386D2320C3DA2C2060D0EBD622 /* ReachabilitySwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = ReachabilitySwift.modulemap; sourceTree = "<group>"; };
|
||||
15348E9E02C583262BCE9E2DF83BB390 /* SwiftHTTP-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftHTTP-prefix.pch"; sourceTree = "<group>"; };
|
||||
1AFB0CBFBAAD243441BFBACC7D2D8DFE /* SwiftHTTP.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftHTTP.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
32E45C833AF7E16855BBB75F3725A934 /* Pods-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-dummy.m"; sourceTree = "<group>"; };
|
||||
3E9E80ACD8021743B20121DDA0D7F457 /* SwiftHTTP-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftHTTP-umbrella.h"; sourceTree = "<group>"; };
|
||||
4057D82490BD357705895A1E889818DC /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.debug.xcconfig; sourceTree = "<group>"; };
|
||||
40BA696D0257C0C38DB22F4F7C0B3024 /* ReachabilitySwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "ReachabilitySwift-dummy.m"; sourceTree = "<group>"; };
|
||||
42443BE4CFDB3686DCE7BD49A7251FBD /* ReachabilitySwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ReachabilitySwift-umbrella.h"; sourceTree = "<group>"; };
|
||||
4C1C786CCECAB03DBBA6174C79837A10 /* Reachability.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Reachability.swift; sourceTree = "<group>"; };
|
||||
4DB25E462135DFC183C89E6E66E596FD /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; };
|
||||
57F10E5E0800AB435D50B75E004F0E5E /* HTTPSecurity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HTTPSecurity.swift; sourceTree = "<group>"; };
|
||||
62384151EBD793096A1AAF3E92D94B8D /* ReachabilitySwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ReachabilitySwift.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
649885E5C778C58AB64D51F0C20CED29 /* SwiftHTTP-Private.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "SwiftHTTP-Private.xcconfig"; sourceTree = "<group>"; };
|
||||
10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = "<group>"; };
|
||||
107E36DD8FC301E2139617F854F330D5 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
1CA6EBC2E57D96052268211209D6AA52 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/Cocoa.framework; sourceTree = DEVELOPER_DIR; };
|
||||
21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = "<group>"; };
|
||||
23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = "<group>"; };
|
||||
2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-umbrella.h"; sourceTree = "<group>"; };
|
||||
4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = "<group>"; };
|
||||
5241F56B5C8C48BD734958D586267D1A /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = "<group>"; };
|
||||
52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = "<group>"; };
|
||||
5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = "<group>"; };
|
||||
5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
779B19103BE8402A434ED95F67573911 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = "<group>"; };
|
||||
7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = "<group>"; };
|
||||
79A9DEDC89FE8336BF5FEDAAF75BF7FC /* Pods.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Pods.modulemap; sourceTree = "<group>"; };
|
||||
7B4DE76AFBBDE97856185D579F920FFA /* Pods-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-umbrella.h"; sourceTree = "<group>"; };
|
||||
801610C316E9613869C090D4FB50D508 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = "<group>"; };
|
||||
83957AB2EE778B52399CC4C903539BD0 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = "<group>"; };
|
||||
87B213035BAC5F75386F62D3C75D2342 /* Pods-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-acknowledgements.plist"; sourceTree = "<group>"; };
|
||||
A951EEB50E667EEF07D87DD479DA9433 /* ReachabilitySwift-Private.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "ReachabilitySwift-Private.xcconfig"; sourceTree = "<group>"; };
|
||||
AD3DFA8DA99A0DD784441E8ACE3379F9 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.release.xcconfig; sourceTree = "<group>"; };
|
||||
B278AD891AF3B8F6DC8F36A5A6C29417 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
B8F691D8FF9BB3BC94F769A03D7BF6E9 /* HTTPRequestSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HTTPRequestSerializer.swift; sourceTree = "<group>"; };
|
||||
894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-dummy.m"; sourceTree = "<group>"; };
|
||||
8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = "<group>"; };
|
||||
8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = "<group>"; };
|
||||
948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = "<group>"; };
|
||||
977577C045EDA9D9D1F46E2598D19FC7 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.debug.xcconfig; sourceTree = "<group>"; };
|
||||
ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = "<group>"; };
|
||||
BA6428E9F66FD5A23C0A2E06ED26CD2F /* Podfile */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; };
|
||||
C533A7E04B2700CB774CD9B10CC75014 /* HTTPResponseSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HTTPResponseSerializer.swift; sourceTree = "<group>"; };
|
||||
C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = "<group>"; };
|
||||
CBC0F7C552B739C909B650A0F42F7F38 /* Pods-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-resources.sh"; sourceTree = "<group>"; };
|
||||
CDDCD49DDDF6C0B9F82260F1AF13A942 /* ReachabilitySwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = ReachabilitySwift.xcconfig; sourceTree = "<group>"; };
|
||||
D0405803033A2A777B8E4DFA0C1800ED /* Pods-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-acknowledgements.markdown"; sourceTree = "<group>"; };
|
||||
D15F651F060B286D433A13109B37091C /* HTTPTask.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HTTPTask.swift; sourceTree = "<group>"; };
|
||||
D9B9FD9DAD14DAAC21B5423D800BBD0C /* SwiftHTTP.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = SwiftHTTP.modulemap; sourceTree = "<group>"; };
|
||||
DA312349A49333542E6F4B36B329960E /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.release.xcconfig; sourceTree = "<group>"; };
|
||||
DD434AED73B642F39D982866408EDC1A /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = "<group>"; };
|
||||
E7F21354943D9F42A70697D5A5EF72E9 /* Pods-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-frameworks.sh"; sourceTree = "<group>"; };
|
||||
E8446514FBAD26C0E18F24A5715AEF67 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
EB4AF5086CB3AC13E75C2E1F7D39F72E /* ReachabilitySwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ReachabilitySwift-prefix.pch"; sourceTree = "<group>"; };
|
||||
F67503E72BAEAD05D13DF670F7D88CCD /* SwiftHTTP-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftHTTP-dummy.m"; sourceTree = "<group>"; };
|
||||
F92D703483EAB54823ABF39B5C024CEC /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/Cocoa.framework; sourceTree = DEVELOPER_DIR; };
|
||||
F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = "<group>"; };
|
||||
FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
10CE6206C906127554A7B0BF49A457CC /* Frameworks */ = {
|
||||
53B0606A91496E4CC56EEA761EF840B9 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
0FBBF858C750BD72A6B9D05357699EAE /* Cocoa.framework in Frameworks */,
|
||||
2EADFA6A6D8F80BF28466A3207F1880F /* SystemConfiguration.framework in Frameworks */,
|
||||
385267D5E1667CA0120A7DDFAE7C05AD /* Cocoa.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
3B6CEF09D80635B1C1A67720265E1C26 /* Frameworks */ = {
|
||||
909917B11D3F3C55D5CC83D172253A08 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
723C10D67F21BFB2AE43FCE47E18A921 /* Cocoa.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
E7AF66B94C382A3D9361923B020E023F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
69079EC9A7A8AB065AD21904666AACEC /* Cocoa.framework in Frameworks */,
|
||||
31F7DD538B22F0EBE774CF164AF5F64B /* Cocoa.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
4D8D4937101166A85BFF2FBAF40F5516 /* ReachabilitySwift */ = {
|
||||
09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
4C1C786CCECAB03DBBA6174C79837A10 /* Reachability.swift */,
|
||||
D8FEE5B31C6CE8B956341F5F06BC1F02 /* Support Files */,
|
||||
23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */,
|
||||
ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */,
|
||||
83957AB2EE778B52399CC4C903539BD0 /* Error.swift */,
|
||||
5241F56B5C8C48BD734958D586267D1A /* Manager.swift */,
|
||||
10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */,
|
||||
5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */,
|
||||
FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */,
|
||||
8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */,
|
||||
F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */,
|
||||
7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */,
|
||||
52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */,
|
||||
C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */,
|
||||
948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */,
|
||||
779B19103BE8402A434ED95F67573911 /* Validation.swift */,
|
||||
405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */,
|
||||
);
|
||||
path = ReachabilitySwift;
|
||||
path = Alamofire;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */,
|
||||
);
|
||||
name = Pods;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
28C17CEF104526ACA07B6EEE217EC43E /* OS X */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1CA6EBC2E57D96052268211209D6AA52 /* Cocoa.framework */,
|
||||
);
|
||||
name = "OS X";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
39E9EE8210D861DFD82346C1F5EB7218 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
28C17CEF104526ACA07B6EEE217EC43E /* OS X */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */,
|
||||
7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */,
|
||||
8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */,
|
||||
E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */,
|
||||
4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */,
|
||||
5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */,
|
||||
);
|
||||
name = "Support Files";
|
||||
path = "../Target Support Files/Alamofire";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
75D98FF52E597A11900E131B6C4E1ADA /* Pods */ = {
|
||||
@ -126,12 +163,12 @@
|
||||
79A9DEDC89FE8336BF5FEDAAF75BF7FC /* Pods.modulemap */,
|
||||
D0405803033A2A777B8E4DFA0C1800ED /* Pods-acknowledgements.markdown */,
|
||||
87B213035BAC5F75386F62D3C75D2342 /* Pods-acknowledgements.plist */,
|
||||
32E45C833AF7E16855BBB75F3725A934 /* Pods-dummy.m */,
|
||||
894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */,
|
||||
E7F21354943D9F42A70697D5A5EF72E9 /* Pods-frameworks.sh */,
|
||||
CBC0F7C552B739C909B650A0F42F7F38 /* Pods-resources.sh */,
|
||||
7B4DE76AFBBDE97856185D579F920FFA /* Pods-umbrella.h */,
|
||||
4057D82490BD357705895A1E889818DC /* Pods.debug.xcconfig */,
|
||||
AD3DFA8DA99A0DD784441E8ACE3379F9 /* Pods.release.xcconfig */,
|
||||
2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */,
|
||||
977577C045EDA9D9D1F46E2598D19FC7 /* Pods.debug.xcconfig */,
|
||||
DA312349A49333542E6F4B36B329960E /* Pods.release.xcconfig */,
|
||||
);
|
||||
name = Pods;
|
||||
path = "Target Support Files/Pods";
|
||||
@ -141,26 +178,13 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
BA6428E9F66FD5A23C0A2E06ED26CD2F /* Podfile */,
|
||||
D648CE86F139C7CCFD55D5B8A03BE74B /* Frameworks */,
|
||||
F0DC4F36A15704389A9297F3020BED99 /* Pods */,
|
||||
CCA510CFBEA2D207524CDA0D73C3B561 /* Products */,
|
||||
39E9EE8210D861DFD82346C1F5EB7218 /* Frameworks */,
|
||||
20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */,
|
||||
FFD86F6DA0ECF0C92889A5B44242D70F /* Products */,
|
||||
B7B80995527643776607AFFA75B91E24 /* Targets Support Files */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
8480DBE9F2782F5C8217930EA726C666 /* SwiftHTTP */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
B8F691D8FF9BB3BC94F769A03D7BF6E9 /* HTTPRequestSerializer.swift */,
|
||||
C533A7E04B2700CB774CD9B10CC75014 /* HTTPResponseSerializer.swift */,
|
||||
57F10E5E0800AB435D50B75E004F0E5E /* HTTPSecurity.swift */,
|
||||
D15F651F060B286D433A13109B37091C /* HTTPTask.swift */,
|
||||
0EF017F3903CAB51D4BF613B96370A46 /* HTTPUpload.swift */,
|
||||
E5F5A69C46B7C6FB4C778FE647A05890 /* Support Files */,
|
||||
);
|
||||
path = SwiftHTTP;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
B7B80995527643776607AFFA75B91E24 /* Targets Support Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@ -169,153 +193,70 @@
|
||||
name = "Targets Support Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
CCA510CFBEA2D207524CDA0D73C3B561 /* Products */ = {
|
||||
FFD86F6DA0ECF0C92889A5B44242D70F /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
097C0D457717655774F1C6B4482469C1 /* Pods.framework */,
|
||||
62384151EBD793096A1AAF3E92D94B8D /* ReachabilitySwift.framework */,
|
||||
1AFB0CBFBAAD243441BFBACC7D2D8DFE /* SwiftHTTP.framework */,
|
||||
DD434AED73B642F39D982866408EDC1A /* Alamofire.framework */,
|
||||
107E36DD8FC301E2139617F854F330D5 /* Pods.framework */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
D344DDEA45FAAA6C5B5B81CB2C028D16 /* OS X */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
F92D703483EAB54823ABF39B5C024CEC /* Cocoa.framework */,
|
||||
4DB25E462135DFC183C89E6E66E596FD /* SystemConfiguration.framework */,
|
||||
);
|
||||
name = "OS X";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
D648CE86F139C7CCFD55D5B8A03BE74B /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
D344DDEA45FAAA6C5B5B81CB2C028D16 /* OS X */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
D8FEE5B31C6CE8B956341F5F06BC1F02 /* Support Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
801610C316E9613869C090D4FB50D508 /* Info.plist */,
|
||||
0FF578386D2320C3DA2C2060D0EBD622 /* ReachabilitySwift.modulemap */,
|
||||
CDDCD49DDDF6C0B9F82260F1AF13A942 /* ReachabilitySwift.xcconfig */,
|
||||
A951EEB50E667EEF07D87DD479DA9433 /* ReachabilitySwift-Private.xcconfig */,
|
||||
40BA696D0257C0C38DB22F4F7C0B3024 /* ReachabilitySwift-dummy.m */,
|
||||
EB4AF5086CB3AC13E75C2E1F7D39F72E /* ReachabilitySwift-prefix.pch */,
|
||||
42443BE4CFDB3686DCE7BD49A7251FBD /* ReachabilitySwift-umbrella.h */,
|
||||
);
|
||||
name = "Support Files";
|
||||
path = "../Target Support Files/ReachabilitySwift";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
E5F5A69C46B7C6FB4C778FE647A05890 /* Support Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
B278AD891AF3B8F6DC8F36A5A6C29417 /* Info.plist */,
|
||||
D9B9FD9DAD14DAAC21B5423D800BBD0C /* SwiftHTTP.modulemap */,
|
||||
095D927AF11FDF42492621C1C67329C0 /* SwiftHTTP.xcconfig */,
|
||||
649885E5C778C58AB64D51F0C20CED29 /* SwiftHTTP-Private.xcconfig */,
|
||||
F67503E72BAEAD05D13DF670F7D88CCD /* SwiftHTTP-dummy.m */,
|
||||
15348E9E02C583262BCE9E2DF83BB390 /* SwiftHTTP-prefix.pch */,
|
||||
3E9E80ACD8021743B20121DDA0D7F457 /* SwiftHTTP-umbrella.h */,
|
||||
);
|
||||
name = "Support Files";
|
||||
path = "../Target Support Files/SwiftHTTP";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
F0DC4F36A15704389A9297F3020BED99 /* Pods */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
4D8D4937101166A85BFF2FBAF40F5516 /* ReachabilitySwift */,
|
||||
8480DBE9F2782F5C8217930EA726C666 /* SwiftHTTP */,
|
||||
);
|
||||
name = Pods;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
0B22B6FADDDAE608553086624BF5AE09 /* Headers */ = {
|
||||
5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = {
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
719D747C7DAF00843C07D2368BD9BB8F /* Pods-umbrella.h in Headers */,
|
||||
2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
20FB5DF95D0E471FCD3431D047B883B8 /* Headers */ = {
|
||||
AB7070EDFAA9F6C9284F97D7C4FD5C5D /* Headers */ = {
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C9D551E664541B6D44F0DDDBC094DE22 /* SwiftHTTP-umbrella.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
AD2F7189DE36DFBFFC16AD43D522D04D /* Headers */ = {
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
6E0B32BB9D7E10891D49EF9D239B20D8 /* ReachabilitySwift-umbrella.h in Headers */,
|
||||
91C36C428505A897B4AED8BC3F27ECAA /* Pods-umbrella.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXHeadersBuildPhase section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
0C66C30381F86C3D642FC983CCADEBB6 /* ReachabilitySwift */ = {
|
||||
432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 882C86C75819C78E7E8EB42E9274C2D2 /* Build configuration list for PBXNativeTarget "ReachabilitySwift" */;
|
||||
buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */;
|
||||
buildPhases = (
|
||||
8CC6D6A78FAF3FC63BD31EF4244EECF0 /* Sources */,
|
||||
10CE6206C906127554A7B0BF49A457CC /* Frameworks */,
|
||||
AD2F7189DE36DFBFFC16AD43D522D04D /* Headers */,
|
||||
EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */,
|
||||
53B0606A91496E4CC56EEA761EF840B9 /* Frameworks */,
|
||||
5F7B61281F714E2A64A51E80A2C9C062 /* Headers */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = ReachabilitySwift;
|
||||
productName = ReachabilitySwift;
|
||||
productReference = 62384151EBD793096A1AAF3E92D94B8D /* ReachabilitySwift.framework */;
|
||||
name = Alamofire;
|
||||
productName = Alamofire;
|
||||
productReference = DD434AED73B642F39D982866408EDC1A /* Alamofire.framework */;
|
||||
productType = "com.apple.product-type.framework";
|
||||
};
|
||||
8A1E0EE23F7DB25CAD85F10192E3946A /* Pods */ = {
|
||||
57CFC4DF5A94826729A3A532FC59EE52 /* Pods */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = E336FAF9DDF77FD2D4B1D814E920DE06 /* Build configuration list for PBXNativeTarget "Pods" */;
|
||||
buildConfigurationList = D96086592099F83F7FCBCEB9423AF9F1 /* Build configuration list for PBXNativeTarget "Pods" */;
|
||||
buildPhases = (
|
||||
68DE87CB2D7394E962BFFE8ED2A9F383 /* Sources */,
|
||||
3B6CEF09D80635B1C1A67720265E1C26 /* Frameworks */,
|
||||
0B22B6FADDDAE608553086624BF5AE09 /* Headers */,
|
||||
27B6CD64D85CDE62D58AFB0C5EC2F44D /* Sources */,
|
||||
909917B11D3F3C55D5CC83D172253A08 /* Frameworks */,
|
||||
AB7070EDFAA9F6C9284F97D7C4FD5C5D /* Headers */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
FA94B6C4DD56FB750B8EB85AAD501F88 /* PBXTargetDependency */,
|
||||
83625E2F06EBB2816D94100B60CA3F8C /* PBXTargetDependency */,
|
||||
22FACAD584CBBAA1AE9A9C8FA17C8395 /* PBXTargetDependency */,
|
||||
);
|
||||
name = Pods;
|
||||
productName = Pods;
|
||||
productReference = 097C0D457717655774F1C6B4482469C1 /* Pods.framework */;
|
||||
productType = "com.apple.product-type.framework";
|
||||
};
|
||||
AB33B84630B10DE253DA6B29E233F61D /* SwiftHTTP */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = D842CE539573B27EEC42F919D3A8E7E9 /* Build configuration list for PBXNativeTarget "SwiftHTTP" */;
|
||||
buildPhases = (
|
||||
AFBA4EC0488F1C9A3F1766426F037C69 /* Sources */,
|
||||
E7AF66B94C382A3D9361923B020E023F /* Frameworks */,
|
||||
20FB5DF95D0E471FCD3431D047B883B8 /* Headers */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = SwiftHTTP;
|
||||
productName = SwiftHTTP;
|
||||
productReference = 1AFB0CBFBAAD243441BFBACC7D2D8DFE /* SwiftHTTP.framework */;
|
||||
productReference = 107E36DD8FC301E2139617F854F330D5 /* Pods.framework */;
|
||||
productType = "com.apple.product-type.framework";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
@ -335,124 +276,59 @@
|
||||
en,
|
||||
);
|
||||
mainGroup = 7DB346D0F39D3F0E887471402A8071AB;
|
||||
productRefGroup = CCA510CFBEA2D207524CDA0D73C3B561 /* Products */;
|
||||
productRefGroup = FFD86F6DA0ECF0C92889A5B44242D70F /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
8A1E0EE23F7DB25CAD85F10192E3946A /* Pods */,
|
||||
0C66C30381F86C3D642FC983CCADEBB6 /* ReachabilitySwift */,
|
||||
AB33B84630B10DE253DA6B29E233F61D /* SwiftHTTP */,
|
||||
432ECC54282C84882B482CCB4CF227FC /* Alamofire */,
|
||||
57CFC4DF5A94826729A3A532FC59EE52 /* Pods */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
68DE87CB2D7394E962BFFE8ED2A9F383 /* Sources */ = {
|
||||
27B6CD64D85CDE62D58AFB0C5EC2F44D /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
0349D3641FA40BDE258EBB89DAB0CE56 /* Pods-dummy.m in Sources */,
|
||||
EA6FDB353E0AE2963BFCD155E100F836 /* Pods-dummy.m in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
8CC6D6A78FAF3FC63BD31EF4244EECF0 /* Sources */ = {
|
||||
EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
82FEFB5F8E2CE9FF43EDE67D41F774D6 /* Reachability.swift in Sources */,
|
||||
50CB3873CE44B09068C6650F7BC1B62E /* ReachabilitySwift-dummy.m in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
AFBA4EC0488F1C9A3F1766426F037C69 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
01259B29E7B75268A2E4639449AE759B /* HTTPRequestSerializer.swift in Sources */,
|
||||
F556360A6CF9AD4B39927790324A61AA /* HTTPResponseSerializer.swift in Sources */,
|
||||
4CB56104486E20F3D1A8F0F048473FD5 /* HTTPSecurity.swift in Sources */,
|
||||
588B0C8E4C2F7849023F60069A7AF094 /* HTTPTask.swift in Sources */,
|
||||
5C601DFC35BD0AA393A1C6B29E45B133 /* HTTPUpload.swift in Sources */,
|
||||
7EACDBE6B531B186A1ECDF5838A92549 /* SwiftHTTP-dummy.m in Sources */,
|
||||
B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */,
|
||||
B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */,
|
||||
A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */,
|
||||
D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */,
|
||||
A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */,
|
||||
8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */,
|
||||
4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */,
|
||||
FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */,
|
||||
03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */,
|
||||
D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */,
|
||||
82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */,
|
||||
80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */,
|
||||
FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */,
|
||||
0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */,
|
||||
C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
83625E2F06EBB2816D94100B60CA3F8C /* PBXTargetDependency */ = {
|
||||
22FACAD584CBBAA1AE9A9C8FA17C8395 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = SwiftHTTP;
|
||||
target = AB33B84630B10DE253DA6B29E233F61D /* SwiftHTTP */;
|
||||
targetProxy = EC3ED57D07B7D0FB9BC30494E35FFDB9 /* PBXContainerItemProxy */;
|
||||
};
|
||||
FA94B6C4DD56FB750B8EB85AAD501F88 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = ReachabilitySwift;
|
||||
target = 0C66C30381F86C3D642FC983CCADEBB6 /* ReachabilitySwift */;
|
||||
targetProxy = 039A210DD9F51E9946D160F7EEDCCA0B /* PBXContainerItemProxy */;
|
||||
name = Alamofire;
|
||||
target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */;
|
||||
targetProxy = 66FB30F40015337B10768205C744F9CB /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
1CEA97719C11C51D66E51817DB9E086F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 4057D82490BD357705895A1E889818DC /* Pods.debug.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
INFOPLIST_FILE = "Target Support Files/Pods/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/Pods/Pods.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
OTHER_LDFLAGS = "";
|
||||
OTHER_LIBTOOLFLAGS = "";
|
||||
PODS_ROOT = "$(SRCROOT)";
|
||||
PRODUCT_NAME = Pods;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
21A6712541CD335AD75433A36DA862A1 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 649885E5C778C58AB64D51F0C20CED29 /* SwiftHTTP-Private.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 0.9.5;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 0.9.5;
|
||||
DYLIB_CURRENT_VERSION = "$(CURRENT_PROJECT_VERSION)";
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
GCC_PREFIX_HEADER = "Target Support Files/SwiftHTTP/SwiftHTTP-prefix.pch";
|
||||
INFOPLIST_FILE = "Target Support Files/SwiftHTTP/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/SwiftHTTP/SwiftHTTP.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
PRODUCT_NAME = SwiftHTTP;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
52D4ECB745D1C035F94BD060EE7F6605 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
@ -492,9 +368,9 @@
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
55EB40FAD13AC43FBC7870F72AECCA72 /* Release */ = {
|
||||
58AE1DCCC93FA62E5206B4F5BBDB7B48 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = AD3DFA8DA99A0DD784441E8ACE3379F9 /* Pods.release.xcconfig */;
|
||||
baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
@ -505,16 +381,14 @@
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
INFOPLIST_FILE = "Target Support Files/Pods/Info.plist";
|
||||
GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch";
|
||||
INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/Pods/Pods.modulemap";
|
||||
MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
OTHER_LDFLAGS = "";
|
||||
OTHER_LIBTOOLFLAGS = "";
|
||||
PODS_ROOT = "$(SRCROOT)";
|
||||
PRODUCT_NAME = Pods;
|
||||
PRODUCT_NAME = Alamofire;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
@ -522,6 +396,65 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
608D4D4057E2A4B08498EE5DFE4EE27D /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 977577C045EDA9D9D1F46E2598D19FC7 /* Pods.debug.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
INFOPLIST_FILE = "Target Support Files/Pods/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACH_O_TYPE = staticlib;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/Pods/Pods.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
OTHER_LDFLAGS = "";
|
||||
OTHER_LIBTOOLFLAGS = "";
|
||||
PODS_ROOT = "$(SRCROOT)";
|
||||
PRODUCT_NAME = Pods;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
73D0F99716A1C5D0F9481F593A431486 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch";
|
||||
INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
PRODUCT_NAME = Alamofire;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A070F153A04DD66F4E492261894B37FF /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
@ -556,83 +489,30 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
A29CAFA0C4CE5C92DD44075B2C08F2C2 /* Debug */ = {
|
||||
E86A0E0DBBBD089208466D1FD0F2BF2F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = A951EEB50E667EEF07D87DD479DA9433 /* ReachabilitySwift-Private.xcconfig */;
|
||||
baseConfigurationReference = DA312349A49333542E6F4B36B329960E /* Pods.release.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1.1.0;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = "$(CURRENT_PROJECT_VERSION)";
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
GCC_PREFIX_HEADER = "Target Support Files/ReachabilitySwift/ReachabilitySwift-prefix.pch";
|
||||
INFOPLIST_FILE = "Target Support Files/ReachabilitySwift/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/ReachabilitySwift/ReachabilitySwift.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
PRODUCT_NAME = ReachabilitySwift;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
B28AC95D7FE099EAFD8FCA215D7488F2 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 649885E5C778C58AB64D51F0C20CED29 /* SwiftHTTP-Private.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 0.9.5;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 0.9.5;
|
||||
DYLIB_CURRENT_VERSION = "$(CURRENT_PROJECT_VERSION)";
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
GCC_PREFIX_HEADER = "Target Support Files/SwiftHTTP/SwiftHTTP-prefix.pch";
|
||||
INFOPLIST_FILE = "Target Support Files/SwiftHTTP/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/SwiftHTTP/SwiftHTTP.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
PRODUCT_NAME = SwiftHTTP;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
VERSION_INFO_PREFIX = "";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
C2F533C4A579F0B9A436CC8C7E79ED91 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = A951EEB50E667EEF07D87DD479DA9433 /* ReachabilitySwift-Private.xcconfig */;
|
||||
buildSettings = {
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1.1.0;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = "$(CURRENT_PROJECT_VERSION)";
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_VERSION = A;
|
||||
GCC_PREFIX_HEADER = "Target Support Files/ReachabilitySwift/ReachabilitySwift-prefix.pch";
|
||||
INFOPLIST_FILE = "Target Support Files/ReachabilitySwift/Info.plist";
|
||||
INFOPLIST_FILE = "Target Support Files/Pods/Info.plist";
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks";
|
||||
MACH_O_TYPE = staticlib;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
MODULEMAP_FILE = "Target Support Files/ReachabilitySwift/ReachabilitySwift.modulemap";
|
||||
MODULEMAP_FILE = "Target Support Files/Pods/Pods.modulemap";
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
PRODUCT_NAME = ReachabilitySwift;
|
||||
OTHER_LDFLAGS = "";
|
||||
OTHER_LIBTOOLFLAGS = "";
|
||||
PODS_ROOT = "$(SRCROOT)";
|
||||
PRODUCT_NAME = Pods;
|
||||
SDKROOT = macosx;
|
||||
SKIP_INSTALL = YES;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
@ -652,29 +532,20 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
882C86C75819C78E7E8EB42E9274C2D2 /* Build configuration list for PBXNativeTarget "ReachabilitySwift" */ = {
|
||||
8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A29CAFA0C4CE5C92DD44075B2C08F2C2 /* Debug */,
|
||||
C2F533C4A579F0B9A436CC8C7E79ED91 /* Release */,
|
||||
73D0F99716A1C5D0F9481F593A431486 /* Debug */,
|
||||
58AE1DCCC93FA62E5206B4F5BBDB7B48 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
D842CE539573B27EEC42F919D3A8E7E9 /* Build configuration list for PBXNativeTarget "SwiftHTTP" */ = {
|
||||
D96086592099F83F7FCBCEB9423AF9F1 /* Build configuration list for PBXNativeTarget "Pods" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
21A6712541CD335AD75433A36DA862A1 /* Debug */,
|
||||
B28AC95D7FE099EAFD8FCA215D7488F2 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
E336FAF9DDF77FD2D4B1D814E920DE06 /* Build configuration list for PBXNativeTarget "Pods" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1CEA97719C11C51D66E51817DB9E086F /* Debug */,
|
||||
55EB40FAD13AC43FBC7870F72AECCA72 /* Release */,
|
||||
608D4D4057E2A4B08498EE5DFE4EE27D /* Debug */,
|
||||
E86A0E0DBBBD089208466D1FD0F2BF2F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
|
||||
@ -7,17 +7,17 @@
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForAnalyzing = "YES"
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "2514840DECCBE0D5C453F231"
|
||||
BuildableName = "SwiftHTTP.framework"
|
||||
BlueprintName = "SwiftHTTP"
|
||||
ReferencedContainer = "container:Pods.xcodeproj">
|
||||
BuildableIdentifier = 'primary'
|
||||
BlueprintIdentifier = '8AD12304DD8FAE48F309E20F'
|
||||
BlueprintName = 'Alamofire'
|
||||
ReferencedContainer = 'container:Pods.xcodeproj'
|
||||
BuildableName = 'Alamofire.framework'>
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@ -29,28 +29,26 @@
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
buildConfiguration = "Debug"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
@ -7,17 +7,17 @@
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForAnalyzing = "YES"
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "218207ACA7371A9334F2B7AE"
|
||||
BuildableName = "Pods.framework"
|
||||
BlueprintName = "Pods"
|
||||
ReferencedContainer = "container:Pods.xcodeproj">
|
||||
BuildableIdentifier = 'primary'
|
||||
BlueprintIdentifier = 'EC0D4C433502670E5C43BA77'
|
||||
BlueprintName = 'Pods'
|
||||
ReferencedContainer = 'container:Pods.xcodeproj'
|
||||
BuildableName = 'Pods.framework'>
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@ -29,28 +29,26 @@
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
buildConfiguration = "Debug"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@ -1,62 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "139B83C851E589090F603794"
|
||||
BuildableName = "ReachabilitySwift.framework"
|
||||
BlueprintName = "ReachabilitySwift"
|
||||
ReferencedContainer = "container:Pods.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -4,35 +4,25 @@
|
||||
<dict>
|
||||
<key>SchemeUserState</key>
|
||||
<dict>
|
||||
<key>Alamofire.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>Pods.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>ReachabilitySwift.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>SwiftHTTP.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>SuppressBuildableAutocreation</key>
|
||||
<dict>
|
||||
<key>0C66C30381F86C3D642FC983CCADEBB6</key>
|
||||
<key>432ECC54282C84882B482CCB4CF227FC</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>8A1E0EE23F7DB25CAD85F10192E3946A</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>AB33B84630B10DE253DA6B29E233F61D</key>
|
||||
<key>57CFC4DF5A94826729A3A532FC59EE52</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
|
||||
21
ipbc-Client/Pods/ReachabilitySwift/LICENSE
generated
21
ipbc-Client/Pods/ReachabilitySwift/LICENSE
generated
@ -1,21 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2014, Ashley Mills
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source, with or without modification, is permitted provided that the following condition is met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
86
ipbc-Client/Pods/ReachabilitySwift/README.md
generated
86
ipbc-Client/Pods/ReachabilitySwift/README.md
generated
@ -1,86 +0,0 @@
|
||||
# Reachability.swift
|
||||
|
||||
Replacement for Apple's Reachability re-written in Swift with closures
|
||||
|
||||
Inspired by https://github.com/tonymillion/Reachability
|
||||
|
||||
**NOTES:**
|
||||
|
||||
- As of Swift 1.2, you cannot convert Swift closures into C-function pointers, meaning we can't set an `SCNetworkReachabilityCallBack`. To get around this, this reachability replacement uses a `dispatch_source` firing at 1/2 second intervals.
|
||||
|
||||
- If an application has the privacy option “Use cellular data” turned off, the Reachability class still reports isReachable() to be true. There is currently no (non-private) API to detect this. If you need this feature, please raise file a [bug report](https://bugreport.apple.com) with Apple to get this fixed. See devforums thread for details: https://devforums.apple.com/message/1059332#1059332
|
||||
|
||||
## Installation
|
||||
### CocoaPods
|
||||
[CocoaPods][] is a dependency manager for Cocoa projects. To install Reachability.swift with CocoaPods:
|
||||
|
||||
1. Make sure CocoaPods is [installed][CocoaPods Installation].
|
||||
|
||||
2. Update your Podfile to include the following:
|
||||
|
||||
``` ruby
|
||||
use_frameworks!
|
||||
pod 'ReachabilitySwift', git: 'https://github.com/ashleymills/Reachability.swift'
|
||||
```
|
||||
|
||||
3. Run `pod install`.
|
||||
|
||||
[CocoaPods]: https://cocoapods.org
|
||||
[CocoaPods Installation]: https://guides.cocoapods.org/using/getting-started.html#getting-started
|
||||
|
||||
### Manual
|
||||
Just drop the **Reachability.swift** file into your project. That's it!
|
||||
|
||||
## Example - closures
|
||||
|
||||
let reachability = Reachability.reachabilityForInternetConnection()
|
||||
|
||||
reachability.whenReachable = { reachability in
|
||||
if reachability.isReachableViaWiFi() {
|
||||
println("Reachable via WiFi")
|
||||
} else {
|
||||
println("Reachable via Cellular")
|
||||
}
|
||||
}
|
||||
reachability.whenUnreachable = { reachability in
|
||||
println("Not reachable")
|
||||
}
|
||||
|
||||
reachability.startNotifier()
|
||||
|
||||
## Example - notifications
|
||||
|
||||
let reachability = Reachability.reachabilityForInternetConnection()
|
||||
|
||||
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
|
||||
|
||||
reachability.startNotifier()
|
||||
|
||||
and
|
||||
|
||||
func reachabilityChanged(note: NSNotification) {
|
||||
|
||||
let reachability = note.object as! Reachability
|
||||
|
||||
if reachability.isReachable() {
|
||||
if reachability.isReachableViaWiFi() {
|
||||
println("Reachable via WiFi")
|
||||
} else {
|
||||
println("Reachable via Cellular")
|
||||
}
|
||||
} else {
|
||||
println("Not reachable")
|
||||
}
|
||||
}
|
||||
|
||||
## Want to help?
|
||||
|
||||
Got a bug fix, or a new feature? Create a pull request and go for it!
|
||||
|
||||
## Let me know!
|
||||
|
||||
If you use **Reachability.swift**, please let me know about your app and I'll put a link [here…](https://github.com/ashleymills/Reachability.swift/wiki/Apps-using-Reachability.swift) and tell your friends!
|
||||
|
||||
Cheers,
|
||||
Ash
|
||||
|
||||
373
ipbc-Client/Pods/ReachabilitySwift/Reachability.swift
generated
373
ipbc-Client/Pods/ReachabilitySwift/Reachability.swift
generated
@ -1,373 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2014, Ashley Mills
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
import SystemConfiguration
|
||||
import Foundation
|
||||
|
||||
public let ReachabilityChangedNotification = "ReachabilityChangedNotification"
|
||||
|
||||
public class Reachability: NSObject, Printable {
|
||||
|
||||
public typealias NetworkReachable = (Reachability) -> ()
|
||||
public typealias NetworkUnreachable = (Reachability) -> ()
|
||||
|
||||
public enum NetworkStatus: Printable {
|
||||
|
||||
case NotReachable, ReachableViaWiFi, ReachableViaWWAN
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .ReachableViaWWAN:
|
||||
return "Cellular"
|
||||
case .ReachableViaWiFi:
|
||||
return "WiFi"
|
||||
case .NotReachable:
|
||||
return "No Connection"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - *** Public properties ***
|
||||
|
||||
public var whenReachable: NetworkReachable?
|
||||
public var whenUnreachable: NetworkUnreachable?
|
||||
public var reachableOnWWAN: Bool
|
||||
public var notificationCenter = NSNotificationCenter.defaultCenter()
|
||||
|
||||
public var currentReachabilityStatus: NetworkStatus {
|
||||
if isReachable() {
|
||||
if isReachableViaWiFi() {
|
||||
return .ReachableViaWiFi
|
||||
}
|
||||
if isRunningOnDevice {
|
||||
return .ReachableViaWWAN
|
||||
}
|
||||
}
|
||||
|
||||
return .NotReachable
|
||||
}
|
||||
|
||||
public var currentReachabilityString: String {
|
||||
return "\(currentReachabilityStatus)"
|
||||
}
|
||||
|
||||
// MARK: - *** Initialisation methods ***
|
||||
|
||||
public required init(reachabilityRef: SCNetworkReachability) {
|
||||
reachableOnWWAN = true
|
||||
self.reachabilityRef = reachabilityRef
|
||||
}
|
||||
|
||||
public convenience init(hostname: String) {
|
||||
let ref = SCNetworkReachabilityCreateWithName(nil, (hostname as NSString).UTF8String).takeRetainedValue()
|
||||
self.init(reachabilityRef: ref)
|
||||
}
|
||||
|
||||
public class func reachabilityForInternetConnection() -> Reachability {
|
||||
|
||||
var zeroAddress = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
|
||||
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
|
||||
zeroAddress.sin_family = sa_family_t(AF_INET)
|
||||
|
||||
let ref = withUnsafePointer(&zeroAddress) {
|
||||
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)).takeRetainedValue()
|
||||
}
|
||||
return Reachability(reachabilityRef: ref)
|
||||
}
|
||||
|
||||
public class func reachabilityForLocalWiFi() -> Reachability {
|
||||
|
||||
var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
|
||||
localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress))
|
||||
localWifiAddress.sin_family = sa_family_t(AF_INET)
|
||||
|
||||
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
|
||||
let address: Int64 = 0xA9FE0000
|
||||
localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian)
|
||||
|
||||
let ref = withUnsafePointer(&localWifiAddress) {
|
||||
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)).takeRetainedValue()
|
||||
}
|
||||
return Reachability(reachabilityRef: ref)
|
||||
}
|
||||
|
||||
// MARK: - *** Notifier methods ***
|
||||
public func startNotifier() -> Bool {
|
||||
|
||||
reachabilityObject = self
|
||||
let reachability = self.reachabilityRef!
|
||||
|
||||
previousReachabilityFlags = reachabilityFlags
|
||||
if let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timer_queue) {
|
||||
dispatch_source_set_timer(timer, dispatch_walltime(nil, 0), 500 * NSEC_PER_MSEC, 100 * NSEC_PER_MSEC)
|
||||
dispatch_source_set_event_handler(timer, { [unowned self] in
|
||||
self.timerFired()
|
||||
})
|
||||
|
||||
dispatch_timer = timer
|
||||
dispatch_resume(timer)
|
||||
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func stopNotifier() {
|
||||
|
||||
reachabilityObject = nil
|
||||
|
||||
if let timer = dispatch_timer {
|
||||
dispatch_source_cancel(timer)
|
||||
dispatch_timer = nil
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - *** Connection test methods ***
|
||||
public func isReachable() -> Bool {
|
||||
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
|
||||
return self.isReachableWithFlags(flags)
|
||||
})
|
||||
}
|
||||
|
||||
public func isReachableViaWWAN() -> Bool {
|
||||
|
||||
if isRunningOnDevice {
|
||||
return isReachableWithTest() { flags -> Bool in
|
||||
// Check we're REACHABLE
|
||||
if self.isReachable(flags) {
|
||||
|
||||
// Now, check we're on WWAN
|
||||
if self.isOnWWAN(flags) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public func isReachableViaWiFi() -> Bool {
|
||||
|
||||
return isReachableWithTest() { flags -> Bool in
|
||||
|
||||
// Check we're reachable
|
||||
if self.isReachable(flags) {
|
||||
|
||||
if self.isRunningOnDevice {
|
||||
// Check we're NOT on WWAN
|
||||
if self.isOnWWAN(flags) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - *** Private methods ***
|
||||
private var isRunningOnDevice: Bool = {
|
||||
#if (arch(i386) || arch(x86_64)) && os(iOS)
|
||||
return false
|
||||
#else
|
||||
return true
|
||||
#endif
|
||||
}()
|
||||
|
||||
private var reachabilityRef: SCNetworkReachability?
|
||||
private var reachabilityObject: AnyObject?
|
||||
private var dispatch_timer: dispatch_source_t?
|
||||
private lazy var timer_queue: dispatch_queue_t = {
|
||||
return dispatch_queue_create("uk.co.joylordsystems.reachability_timer_queue", nil)
|
||||
}()
|
||||
private var previousReachabilityFlags: SCNetworkReachabilityFlags?
|
||||
|
||||
func timerFired() {
|
||||
let currentReachabilityFlags = reachabilityFlags
|
||||
if let _previousReachabilityFlags = previousReachabilityFlags {
|
||||
if currentReachabilityFlags != previousReachabilityFlags {
|
||||
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
|
||||
self.reachabilityChanged(currentReachabilityFlags)
|
||||
self.previousReachabilityFlags = currentReachabilityFlags
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func reachabilityChanged(flags: SCNetworkReachabilityFlags) {
|
||||
if isReachableWithFlags(flags) {
|
||||
if let block = whenReachable {
|
||||
block(self)
|
||||
}
|
||||
} else {
|
||||
if let block = whenUnreachable {
|
||||
block(self)
|
||||
}
|
||||
}
|
||||
|
||||
notificationCenter.postNotificationName(ReachabilityChangedNotification, object:self)
|
||||
}
|
||||
|
||||
private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
|
||||
let reachable = isReachable(flags)
|
||||
|
||||
if !reachable {
|
||||
return false
|
||||
}
|
||||
|
||||
if isConnectionRequiredOrTransient(flags) {
|
||||
return false
|
||||
}
|
||||
|
||||
if isRunningOnDevice {
|
||||
if isOnWWAN(flags) && !reachableOnWWAN {
|
||||
// We don't want to connect when on 3G.
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private func isReachableWithTest(test: (SCNetworkReachabilityFlags) -> (Bool)) -> Bool {
|
||||
var flags: SCNetworkReachabilityFlags = 0
|
||||
let gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) != 0
|
||||
if gotFlags {
|
||||
return test(flags)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// WWAN may be available, but not active until a connection has been established.
|
||||
// WiFi may require a connection for VPN on Demand.
|
||||
private func isConnectionRequired() -> Bool {
|
||||
return connectionRequired()
|
||||
}
|
||||
|
||||
private func connectionRequired() -> Bool {
|
||||
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
|
||||
return self.isConnectionRequired(flags)
|
||||
})
|
||||
}
|
||||
|
||||
// Dynamic, on demand connection?
|
||||
private func isConnectionOnDemand() -> Bool {
|
||||
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
|
||||
return self.isConnectionRequired(flags) && self.isConnectionOnTrafficOrDemand(flags)
|
||||
})
|
||||
}
|
||||
|
||||
// Is user intervention required?
|
||||
private func isInterventionRequired() -> Bool {
|
||||
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
|
||||
return self.isConnectionRequired(flags) && self.isInterventionRequired(flags)
|
||||
})
|
||||
}
|
||||
|
||||
private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
#if os(iOS)
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN) != 0
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable) != 0
|
||||
}
|
||||
private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired) != 0
|
||||
}
|
||||
private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired) != 0
|
||||
}
|
||||
private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
|
||||
}
|
||||
private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand) != 0
|
||||
}
|
||||
func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic | kSCNetworkReachabilityFlagsConnectionOnDemand) != 0
|
||||
}
|
||||
private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection) != 0
|
||||
}
|
||||
private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress) != 0
|
||||
}
|
||||
private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect) != 0
|
||||
}
|
||||
private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool {
|
||||
let testcase = SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired | kSCNetworkReachabilityFlagsTransientConnection)
|
||||
return flags & testcase == testcase
|
||||
}
|
||||
|
||||
private var reachabilityFlags: SCNetworkReachabilityFlags {
|
||||
var flags: SCNetworkReachabilityFlags = 0
|
||||
let gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) != 0
|
||||
if gotFlags {
|
||||
return flags
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
override public var description: String {
|
||||
|
||||
var W: String
|
||||
if isRunningOnDevice {
|
||||
W = isOnWWAN(reachabilityFlags) ? "W" : "-"
|
||||
} else {
|
||||
W = "X"
|
||||
}
|
||||
let R = isReachable(reachabilityFlags) ? "R" : "-"
|
||||
let c = isConnectionRequired(reachabilityFlags) ? "c" : "-"
|
||||
let t = isTransientConnection(reachabilityFlags) ? "t" : "-"
|
||||
let i = isInterventionRequired(reachabilityFlags) ? "i" : "-"
|
||||
let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-"
|
||||
let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-"
|
||||
let l = isLocalAddress(reachabilityFlags) ? "l" : "-"
|
||||
let d = isDirect(reachabilityFlags) ? "d" : "-"
|
||||
|
||||
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
|
||||
}
|
||||
|
||||
deinit {
|
||||
stopNotifier()
|
||||
|
||||
reachabilityRef = nil
|
||||
whenReachable = nil
|
||||
whenUnreachable = nil
|
||||
}
|
||||
}
|
||||
286
ipbc-Client/Pods/SwiftHTTP/HTTPRequestSerializer.swift
generated
286
ipbc-Client/Pods/SwiftHTTP/HTTPRequestSerializer.swift
generated
@ -1,286 +0,0 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// HTTPRequestSerializer.swift
|
||||
//
|
||||
// Created by Dalton Cherry on 6/3/14.
|
||||
// Copyright (c) 2014 Vluxe. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
extension String {
|
||||
/**
|
||||
A simple extension to the String object to encode it for web request.
|
||||
|
||||
:returns: Encoded version of of string it was called as.
|
||||
*/
|
||||
var escaped: String {
|
||||
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,self,"[].",":/?&=;+!@#$()',*",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) as! String
|
||||
}
|
||||
}
|
||||
|
||||
/// Default Serializer for serializing an object to an HTTP request. This applies to form serialization, parameter encoding, etc.
|
||||
public class HTTPRequestSerializer: NSObject {
|
||||
let contentTypeKey = "Content-Type"
|
||||
|
||||
/// headers for the request.
|
||||
public var headers = Dictionary<String,String>()
|
||||
/// encoding for the request.
|
||||
public var stringEncoding: UInt = NSUTF8StringEncoding
|
||||
/// Send request if using cellular network or not. Defaults to true.
|
||||
public var allowsCellularAccess = true
|
||||
/// If the request should handle cookies of not. Defaults to true.
|
||||
public var HTTPShouldHandleCookies = true
|
||||
/// If the request should use piplining or not. Defaults to false.
|
||||
public var HTTPShouldUsePipelining = false
|
||||
/// How long the timeout interval is. Defaults to 60 seconds.
|
||||
public var timeoutInterval: NSTimeInterval = 60
|
||||
/// Set the request cache policy. Defaults to UseProtocolCachePolicy.
|
||||
public var cachePolicy: NSURLRequestCachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy
|
||||
/// Set the network service. Defaults to NetworkServiceTypeDefault.
|
||||
public var networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeDefault
|
||||
|
||||
/// Initializes a new HTTPRequestSerializer Object.
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a new NSMutableURLRequest object with configured options.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: method The HTTP method/verb for the request.
|
||||
|
||||
:returns: A new NSMutableURLRequest with said options.
|
||||
*/
|
||||
public func newRequest(url: NSURL, method: HTTPMethod) -> NSMutableURLRequest {
|
||||
var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
|
||||
request.HTTPMethod = method.rawValue
|
||||
request.cachePolicy = self.cachePolicy
|
||||
request.timeoutInterval = self.timeoutInterval
|
||||
request.allowsCellularAccess = self.allowsCellularAccess
|
||||
request.HTTPShouldHandleCookies = self.HTTPShouldHandleCookies
|
||||
request.HTTPShouldUsePipelining = self.HTTPShouldUsePipelining
|
||||
request.networkServiceType = self.networkServiceType
|
||||
for (key,val) in self.headers {
|
||||
request.addValue(val, forHTTPHeaderField: key)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a new NSMutableURLRequest object with configured options.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: method The HTTP method/verb for the request.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
|
||||
:returns: A new NSMutableURLRequest with said options or an error.
|
||||
*/
|
||||
public func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) {
|
||||
|
||||
var request = newRequest(url, method: method)
|
||||
var isMulti = false
|
||||
//do a check for upload objects to see if we are multi form
|
||||
if let params = parameters {
|
||||
isMulti = isMultiForm(params)
|
||||
}
|
||||
if isMulti {
|
||||
if(method != .POST && method != .PUT && method != .PATCH) {
|
||||
request.HTTPMethod = HTTPMethod.POST.rawValue // you probably wanted a post
|
||||
}
|
||||
var boundary = "Boundary+\(arc4random())\(arc4random())"
|
||||
if parameters != nil {
|
||||
request.HTTPBody = dataFromParameters(parameters!,boundary: boundary)
|
||||
}
|
||||
if request.valueForHTTPHeaderField(contentTypeKey) == nil {
|
||||
request.setValue("multipart/form-data; boundary=\(boundary)",
|
||||
forHTTPHeaderField:contentTypeKey)
|
||||
}
|
||||
return (request,nil)
|
||||
}
|
||||
var queryString = ""
|
||||
if parameters != nil {
|
||||
queryString = self.stringFromParameters(parameters!)
|
||||
}
|
||||
if isURIParam(method) {
|
||||
var para = (request.URL!.query != nil) ? "&" : "?"
|
||||
var newUrl = "\(request.URL!.absoluteString!)"
|
||||
if count(queryString) > 0 {
|
||||
newUrl += "\(para)\(queryString)"
|
||||
}
|
||||
request.URL = NSURL(string: newUrl)
|
||||
} else {
|
||||
var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
|
||||
if request.valueForHTTPHeaderField(contentTypeKey) == nil {
|
||||
request.setValue("application/x-www-form-urlencoded; charset=\(charset)",
|
||||
forHTTPHeaderField:contentTypeKey)
|
||||
}
|
||||
request.HTTPBody = queryString.dataUsingEncoding(self.stringEncoding)
|
||||
}
|
||||
return (request,nil)
|
||||
}
|
||||
|
||||
///check for multi form objects
|
||||
public func isMultiForm(params: Dictionary<String,AnyObject>) -> Bool {
|
||||
for (name,object: AnyObject) in params {
|
||||
if object is HTTPUpload {
|
||||
return true
|
||||
} else if let subParams = object as? Dictionary<String,AnyObject> {
|
||||
if isMultiForm(subParams) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
///check if enum is a HTTPMethod that requires the params in the URL
|
||||
public func isURIParam(method: HTTPMethod) -> Bool {
|
||||
if(method == .GET || method == .HEAD || method == .DELETE) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
///convert the parameter dict to its HTTP string representation
|
||||
func stringFromParameters(parameters: Dictionary<String,AnyObject>) -> String {
|
||||
return join("&", map(serializeObject(parameters, key: nil), {(pair) in
|
||||
return pair.stringValue()
|
||||
}))
|
||||
}
|
||||
|
||||
///the method to serialized all the objects
|
||||
func serializeObject(object: AnyObject,key: String?) -> Array<HTTPPair> {
|
||||
var collect = Array<HTTPPair>()
|
||||
if let array = object as? Array<AnyObject> {
|
||||
for nestedValue : AnyObject in array {
|
||||
collect.extend(self.serializeObject(nestedValue,key: "\(key!)[]"))
|
||||
}
|
||||
} else if let dict = object as? Dictionary<String,AnyObject> {
|
||||
for (nestedKey, nestedObject: AnyObject) in dict {
|
||||
var newKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey
|
||||
collect.extend(self.serializeObject(nestedObject,key: newKey))
|
||||
}
|
||||
} else {
|
||||
collect.append(HTTPPair(value: object, key: key))
|
||||
}
|
||||
return collect
|
||||
}
|
||||
|
||||
//create a multi form data object of the parameters
|
||||
func dataFromParameters(parameters: Dictionary<String,AnyObject>,boundary: String) -> NSData {
|
||||
var mutData = NSMutableData()
|
||||
var multiCRLF = "\r\n"
|
||||
var boundSplit = "\(multiCRLF)--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!
|
||||
var lastBound = "\(multiCRLF)--\(boundary)--\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!
|
||||
mutData.appendData("--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!)
|
||||
|
||||
let pairs = serializeObject(parameters, key: nil)
|
||||
let count = pairs.count-1
|
||||
var i = 0
|
||||
for pair in pairs {
|
||||
var append = true
|
||||
if let upload = pair.getUpload() {
|
||||
if let data = upload.data {
|
||||
mutData.appendData(multiFormHeader(pair.k, fileName: upload.fileName,
|
||||
type: upload.mimeType, multiCRLF: multiCRLF).dataUsingEncoding(self.stringEncoding)!)
|
||||
mutData.appendData(data)
|
||||
} else {
|
||||
append = false
|
||||
}
|
||||
} else {
|
||||
let str = "\(multiFormHeader(pair.k, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.getValue())"
|
||||
mutData.appendData(str.dataUsingEncoding(self.stringEncoding)!)
|
||||
}
|
||||
if append {
|
||||
if i == count {
|
||||
mutData.appendData(lastBound)
|
||||
} else {
|
||||
mutData.appendData(boundSplit)
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
return mutData
|
||||
}
|
||||
|
||||
///helper method to create the multi form headers
|
||||
func multiFormHeader(name: String, fileName: String?, type: String?, multiCRLF: String) -> String {
|
||||
var str = "Content-Disposition: form-data; name=\"\(name.escaped)\""
|
||||
if fileName != nil {
|
||||
str += "; filename=\"\(fileName!)\""
|
||||
}
|
||||
str += multiCRLF
|
||||
if type != nil {
|
||||
str += "Content-Type: \(type!)\(multiCRLF)"
|
||||
}
|
||||
str += multiCRLF
|
||||
return str
|
||||
}
|
||||
|
||||
/// Creates key/pair of the parameters.
|
||||
class HTTPPair: NSObject {
|
||||
var val: AnyObject
|
||||
var k: String!
|
||||
|
||||
init(value: AnyObject, key: String?) {
|
||||
self.val = value
|
||||
self.k = key
|
||||
}
|
||||
|
||||
func getUpload() -> HTTPUpload? {
|
||||
return self.val as? HTTPUpload
|
||||
}
|
||||
|
||||
func getValue() -> String {
|
||||
var val = ""
|
||||
if let str = self.val as? String {
|
||||
val = str
|
||||
} else if self.val.description != nil {
|
||||
val = self.val.description
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
func stringValue() -> String {
|
||||
var v = getValue()
|
||||
if self.k == nil {
|
||||
return v.escaped
|
||||
}
|
||||
return "\(self.k.escaped)=\(v.escaped)"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// JSON Serializer for serializing an object to an HTTP request. Same as HTTPRequestSerializer, expect instead of HTTP form encoding it does JSON.
|
||||
public class JSONRequestSerializer: HTTPRequestSerializer {
|
||||
|
||||
/**
|
||||
Creates a new NSMutableURLRequest object with configured options.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: method The HTTP method/verb for the request.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
|
||||
:returns: A new NSMutableURLRequest with said options or an error.
|
||||
*/
|
||||
public override func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) {
|
||||
if self.isURIParam(method) {
|
||||
return super.createRequest(url, method: method, parameters: parameters)
|
||||
}
|
||||
var request = newRequest(url, method: method)
|
||||
var error: NSError?
|
||||
if parameters != nil {
|
||||
var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
|
||||
request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: self.contentTypeKey)
|
||||
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: NSJSONWritingOptions(), error:&error)
|
||||
}
|
||||
return (request, error)
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// HTTPResponseSerializer.swift
|
||||
//
|
||||
// Created by Dalton Cherry on 6/16/14.
|
||||
// Copyright (c) 2014 Vluxe. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
|
||||
/// This protocol provides a way to implement a custom serializer.
|
||||
public protocol HTTPResponseSerializer {
|
||||
/// This can be used if you want to have your data parsed/serialized into something instead of just a NSData blob.
|
||||
func responseObjectFromResponse(response: NSURLResponse, data: NSData) -> (object: AnyObject?, error: NSError?)
|
||||
}
|
||||
|
||||
/// Serialize the data into a JSON object.
|
||||
public struct JSONResponseSerializer : HTTPResponseSerializer {
|
||||
/// Initializes a new JSONResponseSerializer Object.
|
||||
public init(){}
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation that can be scheduled on a NSOperationQueue. Called by convenience HTTP verb methods below.
|
||||
|
||||
:param: response The NSURLResponse.
|
||||
:param: data The response data to be parsed into JSON.
|
||||
|
||||
:returns: Returns a object from JSON data and an NSError if an error occured while parsing the data.
|
||||
*/
|
||||
public func responseObjectFromResponse(response: NSURLResponse, data: NSData) -> (object: AnyObject?, error: NSError?) {
|
||||
var error: NSError?
|
||||
let response: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &error)
|
||||
return (response,error)
|
||||
}
|
||||
}
|
||||
244
ipbc-Client/Pods/SwiftHTTP/HTTPSecurity.swift
generated
244
ipbc-Client/Pods/SwiftHTTP/HTTPSecurity.swift
generated
@ -1,244 +0,0 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// HTTPSecurity.swift
|
||||
// SwiftHTTP
|
||||
//
|
||||
// Created by Dalton Cherry on 5/13/15.
|
||||
// Copyright (c) 2015 Vluxe. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
public class HTTPSSLCert {
|
||||
var certData: NSData?
|
||||
var key: SecKeyRef?
|
||||
|
||||
/**
|
||||
Designated init for certificates
|
||||
|
||||
:param: data is the binary data of the certificate
|
||||
|
||||
:returns: a representation security object to be used with
|
||||
*/
|
||||
public init(data: NSData) {
|
||||
self.certData = data
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init for public keys
|
||||
|
||||
:param: key is the public key to be used
|
||||
|
||||
:returns: a representation security object to be used with
|
||||
*/
|
||||
public init(key: SecKeyRef) {
|
||||
self.key = key
|
||||
}
|
||||
}
|
||||
|
||||
public class HTTPSecurity {
|
||||
public var validatedDN = true //should the domain name be validated?
|
||||
|
||||
var isReady = false //is the key processing done?
|
||||
var certificates: [NSData]? //the certificates
|
||||
var pubKeys: [SecKeyRef]? //the public keys
|
||||
var usePublicKeys = false //use public keys or certificate validation?
|
||||
|
||||
/**
|
||||
Use certs from main app bundle
|
||||
|
||||
:param: usePublicKeys is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
:returns: a representation security object to be used with
|
||||
*/
|
||||
public convenience init(usePublicKeys: Bool = false) {
|
||||
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
|
||||
var collect = Array<HTTPSSLCert>()
|
||||
for path in paths {
|
||||
if let d = NSData(contentsOfFile: path as! String) {
|
||||
collect.append(HTTPSSLCert(data: d))
|
||||
}
|
||||
}
|
||||
self.init(certs:collect, usePublicKeys: usePublicKeys)
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init
|
||||
|
||||
:param: keys is the certificates or public keys to use
|
||||
:param: usePublicKeys is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
:returns: a representation security object to be used with
|
||||
*/
|
||||
public init(certs: [HTTPSSLCert], usePublicKeys: Bool) {
|
||||
self.usePublicKeys = usePublicKeys
|
||||
|
||||
if self.usePublicKeys {
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
|
||||
var collect = Array<SecKeyRef>()
|
||||
for cert in certs {
|
||||
if let data = cert.certData where cert.key == nil {
|
||||
cert.key = self.extractPublicKey(data)
|
||||
}
|
||||
if let k = cert.key {
|
||||
collect.append(k)
|
||||
}
|
||||
}
|
||||
self.pubKeys = collect
|
||||
self.isReady = true
|
||||
})
|
||||
} else {
|
||||
var collect = Array<NSData>()
|
||||
for cert in certs {
|
||||
if let d = cert.certData {
|
||||
collect.append(d)
|
||||
}
|
||||
}
|
||||
self.certificates = collect
|
||||
self.isReady = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Valid the trust and domain name.
|
||||
|
||||
:param: trust is the serverTrust to validate
|
||||
:param: domain is the CN domain to validate
|
||||
|
||||
:returns: if the key was successfully validated
|
||||
*/
|
||||
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
|
||||
|
||||
var tries = 0
|
||||
while(!self.isReady) {
|
||||
usleep(1000)
|
||||
tries += 1
|
||||
if tries > 5 {
|
||||
return false //doesn't appear it is going to ever be ready...
|
||||
}
|
||||
}
|
||||
var policy: SecPolicyRef
|
||||
if self.validatedDN {
|
||||
policy = SecPolicyCreateSSL(1, domain).takeRetainedValue()
|
||||
} else {
|
||||
policy = SecPolicyCreateBasicX509().takeRetainedValue()
|
||||
}
|
||||
SecTrustSetPolicies(trust,policy)
|
||||
if self.usePublicKeys {
|
||||
if let keys = self.pubKeys {
|
||||
var trustedCount = 0
|
||||
let serverPubKeys = publicKeyChainForTrust(trust)
|
||||
for serverKey in serverPubKeys as [AnyObject] {
|
||||
for key in keys as [AnyObject] {
|
||||
if serverKey.isEqual(key) {
|
||||
trustedCount++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if trustedCount == serverPubKeys.count {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else if let certs = self.certificates {
|
||||
let serverCerts = certificateChainForTrust(trust)
|
||||
var collect = Array<SecCertificate>()
|
||||
for cert in certs {
|
||||
collect.append(SecCertificateCreateWithData(nil,cert).takeRetainedValue())
|
||||
}
|
||||
SecTrustSetAnchorCertificates(trust,collect)
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust,&result)
|
||||
let r = Int(result)
|
||||
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
|
||||
var trustedCount = 0
|
||||
for serverCert in serverCerts {
|
||||
for cert in certs {
|
||||
if cert == serverCert {
|
||||
trustedCount++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if trustedCount == serverCerts.count {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate data
|
||||
|
||||
:param: data is the certificate to pull the public key from
|
||||
|
||||
:returns: a public key
|
||||
*/
|
||||
func extractPublicKey(data: NSData) -> SecKeyRef? {
|
||||
var publicKey: NSData?
|
||||
let possibleCert = SecCertificateCreateWithData(nil,data)
|
||||
if let cert = possibleCert {
|
||||
return extractPublicKeyFromCert(cert.takeRetainedValue(),policy: SecPolicyCreateBasicX509().takeRetainedValue())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate
|
||||
|
||||
:param: data is the certificate to pull the public key from
|
||||
|
||||
:returns: a public key
|
||||
*/
|
||||
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
|
||||
var possibleTrust: Unmanaged<SecTrust>?
|
||||
SecTrustCreateWithCertificates(cert,policy, &possibleTrust)
|
||||
if let trust = possibleTrust {
|
||||
let t = trust.takeRetainedValue()
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(t,&result)
|
||||
return SecTrustCopyPublicKey(t).takeRetainedValue()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/**
|
||||
Get the certificate chain for the trust
|
||||
|
||||
:param: trust is the trust to lookup the certificate chain for
|
||||
|
||||
:returns: the certificate chain for the trust
|
||||
*/
|
||||
func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> {
|
||||
var collect = Array<NSData>()
|
||||
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
|
||||
let cert = SecTrustGetCertificateAtIndex(trust,i)
|
||||
collect.append(SecCertificateCopyData(cert.takeRetainedValue()).takeRetainedValue())
|
||||
}
|
||||
return collect
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key chain for the trust
|
||||
|
||||
:param: trust is the trust to lookup the certificate chain and extract the public keys
|
||||
|
||||
:returns: the public keys from the certifcate chain for the trust
|
||||
*/
|
||||
func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> {
|
||||
var collect = Array<SecKeyRef>()
|
||||
let policy = SecPolicyCreateBasicX509().takeRetainedValue()
|
||||
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
|
||||
let cert = SecTrustGetCertificateAtIndex(trust,i)
|
||||
if let key = extractPublicKeyFromCert(cert.takeRetainedValue(), policy: policy) {
|
||||
collect.append(key)
|
||||
}
|
||||
}
|
||||
return collect
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
554
ipbc-Client/Pods/SwiftHTTP/HTTPTask.swift
generated
554
ipbc-Client/Pods/SwiftHTTP/HTTPTask.swift
generated
@ -1,554 +0,0 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// HTTPTask.swift
|
||||
//
|
||||
// Created by Dalton Cherry on 6/3/14.
|
||||
// Copyright (c) 2014 Vluxe. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
|
||||
/// HTTP Verbs.
|
||||
///
|
||||
/// - GET: For GET requests.
|
||||
/// - POST: For POST requests.
|
||||
/// - PUT: For PUT requests.
|
||||
/// - HEAD: For HEAD requests.
|
||||
/// - DELETE: For DELETE requests.
|
||||
/// - PATCH: For PATCH requests.
|
||||
public enum HTTPMethod: String {
|
||||
case GET = "GET"
|
||||
case POST = "POST"
|
||||
case PUT = "PUT"
|
||||
case HEAD = "HEAD"
|
||||
case DELETE = "DELETE"
|
||||
case PATCH = "PATCH"
|
||||
}
|
||||
|
||||
/// Object representation of a HTTP Response.
|
||||
public class HTTPResponse {
|
||||
/// The header values in HTTP response.
|
||||
public var headers: Dictionary<String,String>?
|
||||
/// The mime type of the HTTP response.
|
||||
public var mimeType: String?
|
||||
/// The suggested filename for a downloaded file.
|
||||
public var suggestedFilename: String?
|
||||
/// The body or response data of the HTTP response.
|
||||
public var responseObject: AnyObject?
|
||||
/// The status code of the HTTP response.
|
||||
public var statusCode: Int?
|
||||
/// The URL of the HTTP response.
|
||||
public var URL: NSURL?
|
||||
/// The Error of the HTTP response (if there was one).
|
||||
public var error: NSError?
|
||||
///Returns the response as a string
|
||||
public var text: String? {
|
||||
if let d = self.responseObject as? NSData {
|
||||
return NSString(data: d, encoding: NSUTF8StringEncoding) as? String
|
||||
} else if let val: AnyObject = self.responseObject {
|
||||
return "\(val)"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
//get the description of the response
|
||||
public var description: String {
|
||||
var buffer = ""
|
||||
if let u = self.URL {
|
||||
buffer += "URL:\n\(u)\n\n"
|
||||
}
|
||||
if let code = self.statusCode {
|
||||
buffer += "Status Code:\n\(code)\n\n"
|
||||
}
|
||||
if let heads = self.headers {
|
||||
buffer += "Headers:\n"
|
||||
for (key, value) in heads {
|
||||
buffer += "\(key): \(value)\n"
|
||||
}
|
||||
buffer += "\n"
|
||||
}
|
||||
if let s = self.text {
|
||||
buffer += "Payload:\n\(s)\n"
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds the blocks of the background task.
|
||||
class BackgroundBlocks {
|
||||
// these 2 only get used for background download/upload since they have to be delegate methods
|
||||
var completionHandler:((HTTPResponse) -> Void)?
|
||||
var progress:((Double) -> Void)?
|
||||
|
||||
/**
|
||||
Initializes a new Background Block
|
||||
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
:param: progress The closure that is run on the progress of a HTTP Upload or Download.
|
||||
*/
|
||||
init(_ completionHandler: ((HTTPResponse) -> Void)?,_ progress: ((Double) -> Void)?) {
|
||||
self.completionHandler = completionHandler
|
||||
self.progress = progress
|
||||
}
|
||||
}
|
||||
|
||||
/// Subclass of NSOperation for handling and scheduling HTTPTask on a NSOperationQueue.
|
||||
public class HTTPOperation : NSOperation {
|
||||
private var task: NSURLSessionDataTask!
|
||||
private var running = false
|
||||
|
||||
/// Controls if the task is finished or not.
|
||||
private var done = false
|
||||
|
||||
//MARK: Subclassed NSOperation Methods
|
||||
|
||||
/// Returns if the task is asynchronous or not. NSURLSessionTask requests are asynchronous.
|
||||
override public var asynchronous: Bool {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Returns if the task is current running.
|
||||
override public var executing: Bool {
|
||||
return running
|
||||
}
|
||||
|
||||
/// Returns if the task is finished.
|
||||
override public var finished: Bool {
|
||||
return done
|
||||
}
|
||||
|
||||
/// Starts the task.
|
||||
override public func start() {
|
||||
if cancelled {
|
||||
self.willChangeValueForKey("isFinished")
|
||||
done = true
|
||||
self.didChangeValueForKey("isFinished")
|
||||
return
|
||||
}
|
||||
|
||||
self.willChangeValueForKey("isExecuting")
|
||||
self.willChangeValueForKey("isFinished")
|
||||
|
||||
running = true
|
||||
done = false
|
||||
|
||||
self.didChangeValueForKey("isExecuting")
|
||||
self.didChangeValueForKey("isFinished")
|
||||
|
||||
task.resume()
|
||||
}
|
||||
|
||||
/// Cancels the running task.
|
||||
override public func cancel() {
|
||||
super.cancel()
|
||||
task.cancel()
|
||||
}
|
||||
|
||||
/// Sets the task to finished.
|
||||
public func finish() {
|
||||
self.willChangeValueForKey("isExecuting")
|
||||
self.willChangeValueForKey("isFinished")
|
||||
|
||||
running = false
|
||||
done = true
|
||||
|
||||
self.didChangeValueForKey("isExecuting")
|
||||
self.didChangeValueForKey("isFinished")
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures NSURLSession Request for HTTPOperation. Also provides convenience methods for easily running HTTP Request.
|
||||
public class HTTPTask : NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {
|
||||
var backgroundTaskMap = Dictionary<String,BackgroundBlocks>()
|
||||
//var sess: NSURLSession?
|
||||
|
||||
public var baseURL: String?
|
||||
public var requestSerializer = HTTPRequestSerializer()
|
||||
public var responseSerializer: HTTPResponseSerializer?
|
||||
//This gets called on auth challenges. If nil, default handling is use.
|
||||
//Returning nil from this method will cause the request to be rejected and cancelled
|
||||
public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
|
||||
|
||||
//This is for doing SSL pinning
|
||||
public var security: HTTPSecurity?
|
||||
|
||||
//MARK: Public Methods
|
||||
|
||||
/// A newly minted HTTPTask for your enjoyment.
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation that can be scheduled on a NSOperationQueue. Called by convenience HTTP verb methods below.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: method The HTTP method/verb for the request.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
|
||||
:returns: A freshly constructed HTTPOperation to add to your NSOperationQueue.
|
||||
*/
|
||||
public func create(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!, completionHandler:((HTTPResponse) -> Void)!) -> HTTPOperation? {
|
||||
|
||||
var serialResponse = HTTPResponse()
|
||||
let serialReq = createRequest(url, method: method, parameters: parameters)
|
||||
if let err = serialReq.error {
|
||||
if let handler = completionHandler {
|
||||
serialResponse.error = err
|
||||
handler(serialResponse)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
let opt = HTTPOperation()
|
||||
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
|
||||
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
|
||||
let task = session.dataTaskWithRequest(serialReq.request,
|
||||
completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
|
||||
if let handler = completionHandler {
|
||||
if let hresponse = response as? NSHTTPURLResponse {
|
||||
serialResponse.headers = hresponse.allHeaderFields as? Dictionary<String,String>
|
||||
serialResponse.mimeType = hresponse.MIMEType
|
||||
serialResponse.suggestedFilename = hresponse.suggestedFilename
|
||||
serialResponse.statusCode = hresponse.statusCode
|
||||
serialResponse.URL = hresponse.URL
|
||||
}
|
||||
serialResponse.error = error
|
||||
if let d = data {
|
||||
serialResponse.responseObject = d
|
||||
if let resSerializer = self.responseSerializer {
|
||||
let resObj = resSerializer.responseObjectFromResponse(response, data: d)
|
||||
serialResponse.responseObject = resObj.object
|
||||
serialResponse.error = resObj.error
|
||||
}
|
||||
if let code = serialResponse.statusCode where serialResponse.statusCode > 299 {
|
||||
serialResponse.error = self.createError(code)
|
||||
}
|
||||
}
|
||||
handler(serialResponse)
|
||||
}
|
||||
opt.finish()
|
||||
})
|
||||
opt.task = task
|
||||
return opt
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation as a HTTP GET request and starts it for you.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
*/
|
||||
public func GET(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) {
|
||||
if let opt = self.create(url, method:.GET, parameters: parameters,completionHandler: completionHandler) {
|
||||
opt.start()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation as a HTTP POST request and starts it for you.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
*/
|
||||
public func POST(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) {
|
||||
if let opt = self.create(url, method:.POST, parameters: parameters,completionHandler: completionHandler) {
|
||||
opt.start()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation as a HTTP PATCH request and starts it for you.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
*/
|
||||
public func PATCH(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) {
|
||||
if let opt = self.create(url, method:.PATCH, parameters: parameters,completionHandler: completionHandler) {
|
||||
opt.start()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation as a HTTP PUT request and starts it for you.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
*/
|
||||
public func PUT(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) {
|
||||
if let opt = self.create(url, method:.PUT, parameters: parameters,completionHandler: completionHandler) {
|
||||
opt.start()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation as a HTTP DELETE request and starts it for you.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
*/
|
||||
public func DELETE(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) {
|
||||
if let opt = self.create(url, method:.DELETE, parameters: parameters,completionHandler: completionHandler) {
|
||||
opt.start()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a HTTPOperation as a HTTP HEAD request and starts it for you.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
*/
|
||||
public func HEAD(url: String, parameters: Dictionary<String,AnyObject>?, completionHandler:((HTTPResponse) -> Void)!) {
|
||||
if let opt = self.create(url, method:.HEAD, parameters: parameters,completionHandler: completionHandler) {
|
||||
opt.start()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates and starts a HTTPOperation to download a file in the background.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: method The HTTP method you want to use. Default is GET.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: progress The progress returned in the progress closure is between 0 and 1.
|
||||
:param: completionHandler The closure that is run when the HTTP Request finishes. The HTTPResponse responseObject object will be a fileURL. You MUST copy the fileURL return in HTTPResponse.responseObject to a new location before using it (e.g. your documents directory).
|
||||
*/
|
||||
public func download(url: String, method: HTTPMethod = .GET, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, completionHandler:((HTTPResponse) -> Void)!) -> NSURLSessionDownloadTask? {
|
||||
let serialReq = createRequest(url,method: method, parameters: parameters)
|
||||
if let err = serialReq.error {
|
||||
if let handler = completionHandler {
|
||||
var res = HTTPResponse()
|
||||
res.error = err
|
||||
handler(res)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
let ident = createBackgroundIdent()
|
||||
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident)
|
||||
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
|
||||
let task = session.downloadTaskWithRequest(serialReq.request)
|
||||
backgroundTaskMap[ident] = BackgroundBlocks(completionHandler,progress)
|
||||
//this does not have to be queueable as Apple's background dameon *should* handle that.
|
||||
task.resume()
|
||||
return task
|
||||
}
|
||||
|
||||
/**
|
||||
Creates and starts a HTTPOperation to upload a file in the background.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: method The HTTP method you want to use. Default is POST.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
:param: progress The progress returned in the progress closure is between 0 and 1.
|
||||
:param: completionHandler The closure that is run when a HTTP Request finished.
|
||||
*/
|
||||
public func upload(url: String, method: HTTPMethod = .POST, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, completionHandler:((HTTPResponse) -> Void)!) -> NSURLSessionTask? {
|
||||
let serialReq = createRequest(url,method: method, parameters: parameters)
|
||||
if let err = serialReq.error {
|
||||
if let handler = completionHandler {
|
||||
var res = HTTPResponse()
|
||||
res.error = err
|
||||
handler(res)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
let ident = createBackgroundIdent()
|
||||
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident)
|
||||
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
|
||||
let task = session.uploadTaskWithStreamedRequest(serialReq.request)
|
||||
backgroundTaskMap[ident] = BackgroundBlocks(completionHandler,progress)
|
||||
task.resume()
|
||||
return task
|
||||
}
|
||||
|
||||
//MARK: Private Helper Methods
|
||||
|
||||
/**
|
||||
Creates and starts a HTTPOperation to download a file in the background.
|
||||
|
||||
:param: url The url you would like to make a request to.
|
||||
:param: method The HTTP method/verb for the request.
|
||||
:param: parameters The parameters are HTTP parameters you would like to send.
|
||||
|
||||
:returns: A NSURLRequest from configured requestSerializer.
|
||||
*/
|
||||
private func createRequest(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!) -> (request: NSURLRequest, error: NSError?) {
|
||||
var urlVal = url
|
||||
//probably should change the 'http' to something more generic
|
||||
if !url.hasPrefix("http") && self.baseURL != nil {
|
||||
var split = url.hasPrefix("/") ? "" : "/"
|
||||
urlVal = "\(self.baseURL!)\(split)\(url)"
|
||||
}
|
||||
if let u = NSURL(string: urlVal) {
|
||||
return self.requestSerializer.createRequest(u, method: method, parameters: parameters)
|
||||
}
|
||||
return (NSURLRequest(),createError(-1001))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a random string to use for the identifier of the background download/upload requests.
|
||||
|
||||
:returns: Identifier String.
|
||||
*/
|
||||
private func createBackgroundIdent() -> String {
|
||||
let letters = "abcdefghijklmnopqurstuvwxyz"
|
||||
var str = ""
|
||||
for var i = 0; i < 14; i++ {
|
||||
let start = Int(arc4random() % 14)
|
||||
str.append(letters[advance(letters.startIndex,start)])
|
||||
}
|
||||
return "com.vluxe.swifthttp.request.\(str)"
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a random string to use for the identifier of the background download/upload requests.
|
||||
|
||||
:param: code Code for error.
|
||||
|
||||
:returns: An NSError.
|
||||
*/
|
||||
private func createError(code: Int) -> NSError {
|
||||
var text = "An error occured"
|
||||
if code == 404 {
|
||||
text = "Page not found"
|
||||
} else if code == 401 {
|
||||
text = "Access denied"
|
||||
} else if code == -1001 {
|
||||
text = "Invalid URL"
|
||||
}
|
||||
return NSError(domain: "HTTPTask", code: code, userInfo: [NSLocalizedDescriptionKey: text])
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
Creates a random string to use for the identifier of the background download/upload requests.
|
||||
|
||||
:param: identifier The identifier string.
|
||||
|
||||
:returns: An NSError.
|
||||
*/
|
||||
private func cleanupBackground(identifier: String) {
|
||||
backgroundTaskMap.removeValueForKey(identifier)
|
||||
}
|
||||
|
||||
//MARK: NSURLSession Delegate Methods
|
||||
|
||||
/// Method for authentication challenge.
|
||||
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
|
||||
if let sec = security where challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
|
||||
let space = challenge.protectionSpace
|
||||
if let trust = space.serverTrust {
|
||||
if sec.isValid(trust, domain: space.host) {
|
||||
completionHandler(.UseCredential, NSURLCredential(trust: trust))
|
||||
return
|
||||
}
|
||||
}
|
||||
completionHandler(.CancelAuthenticationChallenge, nil)
|
||||
return
|
||||
|
||||
} else if let a = auth {
|
||||
let cred = a(challenge)
|
||||
if let c = cred {
|
||||
completionHandler(.UseCredential, c)
|
||||
return
|
||||
}
|
||||
completionHandler(.RejectProtectionSpace, nil)
|
||||
return
|
||||
}
|
||||
completionHandler(.PerformDefaultHandling, nil)
|
||||
}
|
||||
|
||||
//MARK: Methods for background download/upload
|
||||
|
||||
///update the download/upload progress closure
|
||||
func handleProgress(session: NSURLSession, totalBytesExpected: Int64, currentBytes: Int64) {
|
||||
if session.configuration.valueForKey("identifier") != nil { //temp workaround for radar: 21097168
|
||||
let increment = 100.0/Double(totalBytesExpected)
|
||||
var current = (increment*Double(currentBytes))*0.01
|
||||
if current > 1 {
|
||||
current = 1;
|
||||
}
|
||||
if let blocks = backgroundTaskMap[session.configuration.identifier] {
|
||||
if blocks.progress != nil {
|
||||
blocks.progress!(current)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//call the completionHandler closure for upload/download requests
|
||||
func handleFinish(session: NSURLSession, task: NSURLSessionTask, response: AnyObject) {
|
||||
if session.configuration.valueForKey("identifier") != nil { //temp workaround for radar: 21097168
|
||||
if let blocks = backgroundTaskMap[session.configuration.identifier] {
|
||||
if let handler = blocks.completionHandler {
|
||||
var resp = HTTPResponse()
|
||||
if let hresponse = task.response as? NSHTTPURLResponse {
|
||||
resp.headers = hresponse.allHeaderFields as? Dictionary<String,String>
|
||||
resp.mimeType = hresponse.MIMEType
|
||||
resp.suggestedFilename = hresponse.suggestedFilename
|
||||
resp.statusCode = hresponse.statusCode
|
||||
resp.URL = hresponse.URL
|
||||
}
|
||||
resp.responseObject = response
|
||||
if let code = resp.statusCode where resp.statusCode > 299 {
|
||||
resp.error = self.createError(code)
|
||||
}
|
||||
handler(resp)
|
||||
}
|
||||
}
|
||||
cleanupBackground(session.configuration.identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// Called when the background task failed.
|
||||
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let err = error {
|
||||
if session.configuration.valueForKey("identifier") != nil { //temp workaround for radar: 21097168
|
||||
if let blocks = backgroundTaskMap[session.configuration.identifier] {
|
||||
if let handler = blocks.completionHandler {
|
||||
var res = HTTPResponse()
|
||||
res.error = err
|
||||
handler(res)
|
||||
}
|
||||
}
|
||||
cleanupBackground(session.configuration.identifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The background download finished and reports the url the data was saved to.
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL!) {
|
||||
handleFinish(session, task: downloadTask, response: location)
|
||||
}
|
||||
|
||||
/// Will report progress of background download
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
handleProgress(session, totalBytesExpected: totalBytesExpectedToWrite, currentBytes:totalBytesWritten)
|
||||
}
|
||||
|
||||
/// The background download finished, don't have to really do anything.
|
||||
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
|
||||
}
|
||||
|
||||
/// The background upload finished and reports the response.
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData!) {
|
||||
handleFinish(session, task: dataTask, response: data)
|
||||
}
|
||||
|
||||
///Will report progress of background upload
|
||||
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
|
||||
handleProgress(session, totalBytesExpected: totalBytesExpectedToSend, currentBytes:totalBytesSent)
|
||||
}
|
||||
|
||||
//implement if we want to support partial file upload/download
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
|
||||
}
|
||||
}
|
||||
81
ipbc-Client/Pods/SwiftHTTP/HTTPUpload.swift
generated
81
ipbc-Client/Pods/SwiftHTTP/HTTPUpload.swift
generated
@ -1,81 +0,0 @@
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// HTTPUpload.swift
|
||||
//
|
||||
// Created by Dalton Cherry on 6/5/14.
|
||||
// Copyright (c) 2014 Vluxe. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(iOS)
|
||||
import MobileCoreServices
|
||||
#endif
|
||||
|
||||
|
||||
/// Object representation of a HTTP File Upload.
|
||||
public class HTTPUpload: NSObject {
|
||||
var fileUrl: NSURL? {
|
||||
didSet {
|
||||
updateMimeType()
|
||||
loadData()
|
||||
}
|
||||
}
|
||||
var mimeType: String?
|
||||
var data: NSData?
|
||||
var fileName: String?
|
||||
|
||||
/// Tries to determine the mime type from the fileUrl extension.
|
||||
func updateMimeType() {
|
||||
if mimeType == nil && fileUrl != nil {
|
||||
var UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl?.pathExtension as NSString?, nil);
|
||||
var str = UTTypeCopyPreferredTagWithClass(UTI.takeUnretainedValue(), kUTTagClassMIMEType);
|
||||
if (str == nil) {
|
||||
mimeType = "application/octet-stream";
|
||||
} else {
|
||||
mimeType = str.takeUnretainedValue() as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// loads the fileUrl into memory.
|
||||
func loadData() {
|
||||
if let url = fileUrl {
|
||||
self.fileName = url.lastPathComponent
|
||||
self.data = NSData(contentsOfURL: url, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes a new HTTPUpload Object.
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new HTTPUpload Object with a fileUrl. The fileName and mimeType will be infered.
|
||||
|
||||
:param: fileUrl The fileUrl is a standard url path to a file.
|
||||
*/
|
||||
public convenience init(fileUrl: NSURL) {
|
||||
self.init()
|
||||
self.fileUrl = fileUrl
|
||||
updateMimeType()
|
||||
loadData()
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new HTTPUpload Object with a data blob of a file. The fileName and mimeType will be infered if none are provided.
|
||||
|
||||
:param: data The data is a NSData representation of a file's data.
|
||||
:param: fileName The fileName is just that. The file's name.
|
||||
:param: mimeType The mimeType is just that. The mime type you would like the file to uploaded as.
|
||||
*/
|
||||
///upload a file from a a data blob. Must add a filename and mimeType as that can't be infered from the data
|
||||
public convenience init(data: NSData, fileName: String, mimeType: String) {
|
||||
self.init()
|
||||
self.data = data
|
||||
self.fileName = fileName
|
||||
self.mimeType = mimeType
|
||||
}
|
||||
}
|
||||
201
ipbc-Client/Pods/SwiftHTTP/LICENSE
generated
201
ipbc-Client/Pods/SwiftHTTP/LICENSE
generated
@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
481
ipbc-Client/Pods/SwiftHTTP/README.md
generated
481
ipbc-Client/Pods/SwiftHTTP/README.md
generated
@ -1,481 +0,0 @@
|
||||
SwiftHTTP
|
||||
=========
|
||||
|
||||
SwiftHTTP is a thin wrapper around NSURLSession in Swift to simplify HTTP requests.
|
||||
|
||||
## Features
|
||||
|
||||
- Convenient Closure APIs
|
||||
- NSOperationQueue Support
|
||||
- Parameter Encoding
|
||||
- Custom Response Serializer
|
||||
- Builtin JSON Response Serialization
|
||||
- Upload/Download with Progress Closure
|
||||
- Concise Codebase. Under 1000 LOC
|
||||
|
||||
Full article here: [http://vluxe.io/swifthttp.html](http://vluxe.io/swifthttp.html)
|
||||
|
||||
First thing is to import the framework. See the Installation instructions on how to add the framework to your project.
|
||||
|
||||
```swift
|
||||
import SwiftHTTP
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### GET
|
||||
|
||||
The most basic request. By default an NSData object will be returned for the response.
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
request.GET("http://vluxe.io", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let data = response.responseObject as? NSData {
|
||||
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
|
||||
println("response: \(str)") //prints the HTML of the page
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
We can also add parameters as with standard container objects and they will be properly serialized to their respective HTTP equivalent.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
request.GET("http://google.com", parameters: ["param": "param1", "array": ["first array element","second","third"], "num": 23], completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let res: AnyObject = response.responseObject {
|
||||
println("response: \(res)")
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The `HTTPResponse` contains all the common HTTP response data, such as the responseObject of the data and the headers of the response.
|
||||
|
||||
### POST
|
||||
|
||||
A POST request is just as easy as a GET.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
//we have to add the explicit type, else the wrong type is inferred. See the vluxe.io article for more info.
|
||||
let params: Dictionary<String,AnyObject> = ["param": "param1", "array": ["first array element","second","third"], "num": 23, "dict": ["someKey": "someVal"]]
|
||||
request.POST("http://domain.com/create", parameters: params, completionHandler: {(response: HTTPResponse) in
|
||||
//do things...
|
||||
})
|
||||
```
|
||||
|
||||
### PUT
|
||||
|
||||
PUT works the same as post. The example also include a file upload to do a multi form request.
|
||||
|
||||
```swift
|
||||
let fileUrl = NSURL.fileURLWithPath("/Users/dalton/Desktop/file")!
|
||||
var request = HTTPTask()
|
||||
request.PUT("http://domain.com/1", parameters: ["param": "hi", "something": "else", "key": "value","file": HTTPUpload(fileUrl: fileUrl)], completionHandler: {(response: HTTPResponse) in
|
||||
//do stuff
|
||||
})
|
||||
```
|
||||
|
||||
The HTTPUpload object is use to represent files on disk or in memory file as data.
|
||||
|
||||
### DELETE
|
||||
|
||||
DELETE works the same as the GET.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
request.DELETE("http://domain.com/1", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
println("DELETE was successful!")
|
||||
})
|
||||
```
|
||||
|
||||
### HEAD
|
||||
|
||||
HEAD works the same as the GET.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
request.HEAD("http://domain.com/image.png", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
println("The file does exist!")
|
||||
})
|
||||
```
|
||||
|
||||
### Download
|
||||
|
||||
The download method uses the background download functionality of NSURLSession. It also has a progress closure to report the progress of the download.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
let downloadTask = request.download("http://vluxe.io/assets/images/logo.png", parameters: nil, progress: {(complete: Double) in
|
||||
println("percent complete: \(complete)")
|
||||
}, completionHandler: {(response: HTTPResponse) in
|
||||
println("download finished!")
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let url = response.responseObject as? NSURL {
|
||||
//we MUST copy the file from its temp location to a permanent location.
|
||||
if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
|
||||
if let fileName = response.suggestedFilename {
|
||||
if let newPath = NSURL(fileURLWithPath: "\(path)/\(fileName)") {
|
||||
let fileManager = NSFileManager.defaultManager()
|
||||
fileManager.removeItemAtURL(newPath, error: nil)
|
||||
fileManager.moveItemAtURL(url, toURL: newPath, error:nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
```
|
||||
|
||||
Cancel the download.
|
||||
|
||||
```swift
|
||||
if let t = downloadTask {
|
||||
t.cancel()
|
||||
}
|
||||
```
|
||||
|
||||
### Upload
|
||||
|
||||
File uploads can be done using the `HTTPUpload` object. All files to upload should be wrapped in a HTTPUpload object and added as a parameter.
|
||||
|
||||
```swift
|
||||
let task = HTTPTask()
|
||||
var fileUrl = NSURL(fileURLWithPath: "/Users/dalton/Desktop/testfile")!
|
||||
task.upload("http://domain.com/upload", method: .POST, parameters: ["aParam": "aValue", "file": HTTPUpload(fileUrl: fileUrl)], progress: { (value: Double) in
|
||||
println("progress: \(value)")
|
||||
}, completionHandler: { (response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let data = response.responseObject as? NSData {
|
||||
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
|
||||
println("response: \(str!)") //prints the response
|
||||
}
|
||||
})
|
||||
```
|
||||
`HTTPUpload` comes in both a on disk fileUrl version and a NSData version.
|
||||
|
||||
### Custom Headers
|
||||
|
||||
Custom HTTP headers can be add to a request via the requestSerializer.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
request.requestSerializer = HTTPRequestSerializer()
|
||||
request.requestSerializer.headers["someKey"] = "SomeValue" //example of adding a header value
|
||||
```
|
||||
|
||||
### SSL Pinning
|
||||
|
||||
SSL Pinning is also supported in SwiftHTTP.
|
||||
|
||||
```swift
|
||||
let task = HTTPTask()
|
||||
let data = ... //load your certificate from disk
|
||||
task.security = HTTPSecurity(certs: [HTTPSSLCert(data: data)], usePublicKeys: true)
|
||||
//task.security = HTTPSecurity() //uses the .cer files in your app's bundle
|
||||
request.GET("http://yourdomain.com", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
//handle response
|
||||
})
|
||||
```
|
||||
You load either a `NSData` blob of your certificate or you can use a `SecKeyRef` if you have a public key you want to use. The `usePublicKeys` bool is whether to use the certificates for validation or the public keys. The public keys will be extracted from the certificates automatically if `usePublicKeys` is choosen.
|
||||
|
||||
### Authentication
|
||||
|
||||
SwiftHTTP supports authentication through [NSURLCredential](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCredential_Class/Reference/Reference.html). Currently only Basic Auth and Digest Auth have been tested.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
//the auth closures will continually be called until a successful auth or rejection
|
||||
var attempted = false
|
||||
request.auth = {(challenge: NSURLAuthenticationChallenge) in
|
||||
if !attempted {
|
||||
attempted = true
|
||||
return NSURLCredential(user: "user", password: "passwd", persistence: .ForSession)
|
||||
}
|
||||
return nil //auth failed, nil causes the request to be properly cancelled.
|
||||
}
|
||||
request.GET("http://httpbin.org/basic-auth/user/passwd", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
println("winning!")
|
||||
})
|
||||
```
|
||||
|
||||
Allow all certificates example:
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
var attempted = false
|
||||
request.auth = {(challenge: NSURLAuthenticationChallenge) in
|
||||
if !attempted {
|
||||
attempted = true
|
||||
return NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
request.GET("https://somedomain.com", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
println("winning!")
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### BaseURL
|
||||
|
||||
SwiftHTTP also supports use a request object with a baseURL. This is super handy for RESTFul API interaction.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
request.baseURL = "http://api.someserver.com/1"
|
||||
request.GET("/users", parameters: ["key": "value"], completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
println("Got data from http://api.someserver.com/1/users")
|
||||
})
|
||||
|
||||
request.POST("/users", parameters: ["key": "updatedVale"], completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
println("Got data from http://api.someserver.com/1/users")
|
||||
})
|
||||
|
||||
request.GET("/resources", parameters: ["key": "value"], completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
println("Got data from http://api.someserver.com/1/resources")
|
||||
})
|
||||
```
|
||||
|
||||
### Operation Queue
|
||||
|
||||
Operation queues are also supported in SwiftHTTP.
|
||||
|
||||
```swift
|
||||
let operationQueue = NSOperationQueue()
|
||||
operationQueue.maxConcurrentOperationCount = 2
|
||||
var request = HTTPTask()
|
||||
var opt = request.create("http://vluxe.io", method: .GET, parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let data = response.responseObject as? NSData {
|
||||
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
|
||||
println("response: \(str)") //prints the HTML of the page
|
||||
}
|
||||
})
|
||||
if let o = opt {
|
||||
operationQueue.addOperation(o)
|
||||
}
|
||||
```
|
||||
|
||||
### Cancel
|
||||
|
||||
Let's say you want to cancel this request a little later, simple use the operationQueue cancel.
|
||||
|
||||
```swift
|
||||
if let o = opt {
|
||||
o.cancel()
|
||||
}
|
||||
```
|
||||
|
||||
### Serializers
|
||||
|
||||
Request parameters and request responses can also be serialized as needed. By default request are serialized using standard HTTP form encoding. A JSON request and response serializer are provided as well. It is also very simple to create custom serializer by subclass a request or response serializer
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
//The parameters will be encoding as JSON data and sent.
|
||||
request.requestSerializer = JSONRequestSerializer()
|
||||
//The expected response will be JSON and be converted to an object return by NSJSONSerialization instead of a NSData.
|
||||
request.responseSerializer = JSONResponseSerializer()
|
||||
request.GET("http://vluxe.io", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let dict = response.responseObject as? Dictionary<String,AnyObject> {
|
||||
println("example of the JSON key: \(dict["key"])")
|
||||
println("print the whole response: \(response)")
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### UI Changes
|
||||
|
||||
All completionHandler closures return on a background thread. This allows any data parsing to be done without blocking the UI. To make update the UI, call `dispatch_async(dispatch_get_main_queue(),{...}`.
|
||||
|
||||
```swift
|
||||
var request = HTTPTask()
|
||||
request.GET("http://vluxe.io", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let data = response.responseObject as? NSData {
|
||||
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
|
||||
println("response: \(str)") //prints the HTML of the page
|
||||
dispatch_async(dispatch_get_main_queue(),{
|
||||
self.label.text = str //update the label's text with the HTML content
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Client/Server Example
|
||||
|
||||
This is a full example swiftHTTP in action. First here is a quick web server in Go.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
|
||||
log.Println("got a web request")
|
||||
fmt.Println("header: ", r.Header.Get("someKey"))
|
||||
w.Write([]byte("{\"status\": \"ok\"}"))
|
||||
})
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
}
|
||||
```
|
||||
|
||||
Now for the request:
|
||||
|
||||
```swift
|
||||
//The object that will represent our response. More Info in the JSON Parsing section below.
|
||||
struct Status : JSONJoy {
|
||||
var status: String?
|
||||
init() {
|
||||
|
||||
}
|
||||
init(_ decoder: JSONDecoder) {
|
||||
status = decoder["status"].string
|
||||
}
|
||||
}
|
||||
//The request
|
||||
var request = HTTPTask()
|
||||
request.requestSerializer = HTTPRequestSerializer()
|
||||
request.requestSerializer.headers["someKey"] = "SomeValue" //example of adding a header value
|
||||
request.responseSerializer = JSONResponseSerializer()
|
||||
request.GET("http://localhost:8080/bar", parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if let err = response.error {
|
||||
println("error: \(err.localizedDescription)")
|
||||
return //also notify app of failure as needed
|
||||
}
|
||||
if let obj: AnyObject = response.responseObject {
|
||||
let resp = Status(JSONDecoder(obj))
|
||||
println("status is: \(resp.status)")
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## JSON Parsing
|
||||
|
||||
Swift has a lot of great JSON parsing libraries, but I made one specifically designed for JSON to object serialization.
|
||||
|
||||
[JSONJoy-Swift](https://github.com/daltoniam/JSONJoy-Swift)
|
||||
|
||||
## Requirements
|
||||
|
||||
SwiftHTTP works with iOS 7/OSX 10.9 or above. It is recommended to use iOS 8/10.10 or above for Cocoapods/framework support.
|
||||
|
||||
## Installation
|
||||
|
||||
### Cocoapods
|
||||
|
||||
Check out [Get Started](http://cocoapods.org/) tab on [cocoapods.org](http://cocoapods.org/).
|
||||
|
||||
To use SwiftHTTP in your project add the following 'Podfile' to your project
|
||||
|
||||
source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'SwiftHTTP', '~> 0.9.4'
|
||||
|
||||
Then run:
|
||||
|
||||
pod install
|
||||
|
||||
### Carthage
|
||||
|
||||
Check out the [Carthage](https://github.com/Carthage/Carthage) docs on how to add a install. The `SwiftHTTP` framework is already setup with shared schemes.
|
||||
|
||||
[Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)
|
||||
|
||||
### Rogue
|
||||
|
||||
First see the [installation docs](https://github.com/acmacalister/Rogue) for how to install Rogue.
|
||||
|
||||
To install SwiftLog run the command below in the directory you created the rogue file.
|
||||
|
||||
```
|
||||
rogue add https://github.com/daltoniam/SwiftHTTP
|
||||
```
|
||||
|
||||
Next open the `libs` folder and add the `SwiftHTTP.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `SwiftHTTP.framework` to your "Link Binary with Libraries" phase. Make sure to add the `libs` folder to your `.gitignore` file.
|
||||
|
||||
### Other
|
||||
|
||||
Simply grab the framework (either via git submodule or another package manager).
|
||||
|
||||
Add the `SwiftHTTP.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `SwiftHTTP.framework` to your "Link Binary with Libraries" phase.
|
||||
|
||||
### Add Copy Frameworks Phase
|
||||
|
||||
If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the `SwiftHTTP.framework` included in your app bundle. To do this, 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 "Link Binary with Libraries" group, and add `SwiftHTTP.framework`. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `SwiftHTTP.framework`.
|
||||
|
||||
## TODOs
|
||||
|
||||
- [ ] Add more unit tests
|
||||
|
||||
## License
|
||||
|
||||
SwiftHTTP is licensed under the Apache v2 License.
|
||||
|
||||
## Contact
|
||||
|
||||
### Dalton Cherry
|
||||
* https://github.com/daltoniam
|
||||
* http://twitter.com/daltoniam
|
||||
* http://daltoniam.com
|
||||
5
ipbc-Client/Pods/Target Support Files/Alamofire/Alamofire-dummy.m
generated
Normal file
5
ipbc-Client/Pods/Target Support Files/Alamofire/Alamofire-dummy.m
generated
Normal file
@ -0,0 +1,5 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_Alamofire : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_Alamofire
|
||||
@end
|
||||
6
ipbc-Client/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h
generated
Normal file
6
ipbc-Client/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h
generated
Normal file
@ -0,0 +1,6 @@
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
|
||||
FOUNDATION_EXPORT double AlamofireVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char AlamofireVersionString[];
|
||||
|
||||
6
ipbc-Client/Pods/Target Support Files/Alamofire/Alamofire.modulemap
generated
Normal file
6
ipbc-Client/Pods/Target Support Files/Alamofire/Alamofire.modulemap
generated
Normal file
@ -0,0 +1,6 @@
|
||||
framework module Alamofire {
|
||||
umbrella header "Alamofire-umbrella.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
@ -1,7 +1,6 @@
|
||||
#include "SwiftHTTP.xcconfig"
|
||||
CODE_SIGN_IDENTITY =
|
||||
CODE_SIGN_IDENTITY =
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/SwiftHTTP" "${PODS_ROOT}/Headers/Public"
|
||||
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/Alamofire" "${PODS_ROOT}/Headers/Public"
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_ROOT = ${SRCROOT}
|
||||
SKIP_INSTALL = YES
|
||||
@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.1</string>
|
||||
<string>3.1.2</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
@ -1,232 +1,26 @@
|
||||
# Acknowledgements
|
||||
This application makes use of the following third party libraries:
|
||||
|
||||
## ReachabilitySwift
|
||||
## Alamofire
|
||||
|
||||
/*
|
||||
Copyright (c) 2014, Ashley Mills
|
||||
All rights reserved.
|
||||
Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
|
||||
Redistribution and use in source, with or without modification, is permitted provided that the following condition is met:
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
## SwiftHTTP
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Generated by CocoaPods - http://cocoapods.org
|
||||
|
||||
@ -14,238 +14,28 @@
|
||||
</dict>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string>/*
|
||||
Copyright (c) 2014, Ashley Mills
|
||||
All rights reserved.
|
||||
<string>Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
|
||||
|
||||
Redistribution and use in source, with or without modification, is permitted provided that the following condition is met:
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
</string>
|
||||
<key>Title</key>
|
||||
<string>ReachabilitySwift</string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string>Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.</string>
|
||||
<key>Title</key>
|
||||
<string>SwiftHTTP</string>
|
||||
<string>Alamofire</string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
|
||||
@ -10,8 +10,10 @@ install_framework()
|
||||
{
|
||||
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
|
||||
local source="${BUILT_PRODUCTS_DIR}/$1"
|
||||
else
|
||||
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
|
||||
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
|
||||
elif [ -r "$1" ]; then
|
||||
local source="$1"
|
||||
fi
|
||||
|
||||
local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
@ -25,19 +27,31 @@ install_framework()
|
||||
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
|
||||
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
|
||||
|
||||
local basename
|
||||
basename="$(basename -s .framework "$1")"
|
||||
binary="${destination}/${basename}.framework/${basename}"
|
||||
if ! [ -r "$binary" ]; then
|
||||
binary="${destination}/${basename}"
|
||||
fi
|
||||
|
||||
# Strip invalid architectures so "fat" simulator / device frameworks work on device
|
||||
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
|
||||
strip_invalid_archs "$binary"
|
||||
fi
|
||||
|
||||
# Resign the code if required by the build settings to avoid unstable apps
|
||||
code_sign_if_enabled "${destination}/$(basename "$1")"
|
||||
|
||||
# Embed linked Swift runtime libraries
|
||||
local basename
|
||||
basename="$(basename "$1" | sed -E s/\\..+// && exit ${PIPESTATUS[0]})"
|
||||
local swift_runtime_libs
|
||||
swift_runtime_libs=$(xcrun otool -LX "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/${basename}.framework/${basename}" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
|
||||
for lib in $swift_runtime_libs; do
|
||||
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
|
||||
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
|
||||
code_sign_if_enabled "${destination}/${lib}"
|
||||
done
|
||||
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
|
||||
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
|
||||
local swift_runtime_libs
|
||||
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
|
||||
for lib in $swift_runtime_libs; do
|
||||
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
|
||||
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
|
||||
code_sign_if_enabled "${destination}/${lib}"
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
# Signs a framework with the provided identity
|
||||
@ -50,12 +64,28 @@ code_sign_if_enabled() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Strip invalid architectures
|
||||
strip_invalid_archs() {
|
||||
binary="$1"
|
||||
# Get architectures for current file
|
||||
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
|
||||
stripped=""
|
||||
for arch in $archs; do
|
||||
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
|
||||
# Strip non-valid architectures in-place
|
||||
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
|
||||
stripped="$stripped $arch"
|
||||
fi
|
||||
done
|
||||
if [[ "$stripped" ]]; then
|
||||
echo "Stripped $binary of architectures:$stripped"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
if [[ "$CONFIGURATION" == "Debug" ]]; then
|
||||
install_framework 'Pods/ReachabilitySwift.framework'
|
||||
install_framework 'Pods/SwiftHTTP.framework'
|
||||
install_framework "Pods/Alamofire.framework"
|
||||
fi
|
||||
if [[ "$CONFIGURATION" == "Release" ]]; then
|
||||
install_framework 'Pods/ReachabilitySwift.framework'
|
||||
install_framework 'Pods/SwiftHTTP.framework'
|
||||
install_framework "Pods/Alamofire.framework"
|
||||
fi
|
||||
|
||||
@ -60,7 +60,7 @@ install_resource()
|
||||
|
||||
mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
if [[ "${ACTION}" == "install" ]]; then
|
||||
if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then
|
||||
mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
fi
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
CODE_SIGN_IDENTITY =
|
||||
CODE_SIGN_IDENTITY =
|
||||
EMBEDDED_CONTENT_CONTAINS_SWIFT = YES
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/../Frameworks' '@loader_path/Frameworks'
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$CONFIGURATION_BUILD_DIR/ReachabilitySwift.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/SwiftHTTP.framework/Headers"
|
||||
OTHER_LDFLAGS = $(inherited) -framework "ReachabilitySwift" -framework "SwiftHTTP"
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$CONFIGURATION_BUILD_DIR/Alamofire.framework/Headers"
|
||||
OTHER_LDFLAGS = $(inherited) -framework "Alamofire"
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_FRAMEWORK_BUILD_PATH = $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Pods
|
||||
PODS_ROOT = ${SRCROOT}/Pods
|
||||
@ -1,8 +1,9 @@
|
||||
CODE_SIGN_IDENTITY =
|
||||
CODE_SIGN_IDENTITY =
|
||||
EMBEDDED_CONTENT_CONTAINS_SWIFT = YES
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/../Frameworks' '@loader_path/Frameworks'
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$CONFIGURATION_BUILD_DIR/ReachabilitySwift.framework/Headers" -iquote "$CONFIGURATION_BUILD_DIR/SwiftHTTP.framework/Headers"
|
||||
OTHER_LDFLAGS = $(inherited) -framework "ReachabilitySwift" -framework "SwiftHTTP"
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$CONFIGURATION_BUILD_DIR/Alamofire.framework/Headers"
|
||||
OTHER_LDFLAGS = $(inherited) -framework "Alamofire"
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_FRAMEWORK_BUILD_PATH = $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Pods
|
||||
PODS_ROOT = ${SRCROOT}/Pods
|
||||
@ -1,8 +0,0 @@
|
||||
#include "ReachabilitySwift.xcconfig"
|
||||
CODE_SIGN_IDENTITY =
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/ReachabilitySwift" "${PODS_ROOT}/Headers/Public"
|
||||
OTHER_LDFLAGS = ${REACHABILITYSWIFT_OTHER_LDFLAGS}
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_ROOT = ${SRCROOT}
|
||||
SKIP_INSTALL = YES
|
||||
@ -1,5 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_ReachabilitySwift : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_ReachabilitySwift
|
||||
@end
|
||||
@ -1,6 +0,0 @@
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
|
||||
FOUNDATION_EXPORT double ReachabilitySwiftVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char ReachabilitySwiftVersionString[];
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
framework module ReachabilitySwift {
|
||||
umbrella header "ReachabilitySwift-umbrella.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
@ -1 +0,0 @@
|
||||
REACHABILITYSWIFT_OTHER_LDFLAGS = -framework "SystemConfiguration"
|
||||
@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>org.cocoapods.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.9.5</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -1,5 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_SwiftHTTP : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_SwiftHTTP
|
||||
@end
|
||||
@ -1,4 +0,0 @@
|
||||
#ifdef __OBJC__
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#endif
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
|
||||
FOUNDATION_EXPORT double SwiftHTTPVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char SwiftHTTPVersionString[];
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
framework module SwiftHTTP {
|
||||
umbrella header "SwiftHTTP-umbrella.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
@ -7,7 +7,7 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
EC35AC5C1BA21DBA0004A674 /* Pods.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 377F6D84A86891A23192799E /* Pods.framework */; settings = {ATTRIBUTES = (Weak, ); }; };
|
||||
EC35AC5C1BA21DBA0004A674 /* Pods.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 377F6D84A86891A23192799E /* Pods.framework */; };
|
||||
ECEBE1881BA0639500E5B4E3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECEBE1871BA0639500E5B4E3 /* AppDelegate.swift */; };
|
||||
ECEBE18A1BA0639500E5B4E3 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = ECEBE1891BA0639500E5B4E3 /* Images.xcassets */; };
|
||||
ECEBE18D1BA0639500E5B4E3 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = ECEBE18B1BA0639500E5B4E3 /* MainMenu.xib */; };
|
||||
@ -226,6 +226,8 @@
|
||||
ECEBE17A1BA0639500E5B4E3 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftMigration = 0710;
|
||||
LastSwiftUpdateCheck = 0710;
|
||||
LastUpgradeCheck = 0640;
|
||||
ORGANIZATIONNAME = "Adawim UG (haftungsbeschränkt)";
|
||||
TargetAttributes = {
|
||||
|
||||
Binary file not shown.
@ -32,7 +32,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
|
||||
// EventMonitor
|
||||
eventMonitor = EventMonitor(mask: .LeftMouseDownMask | .RightMouseDownMask) { [unowned self] event in
|
||||
eventMonitor = EventMonitor(mask: [.LeftMouseDownMask, .RightMouseDownMask]) { [unowned self] event in
|
||||
if self.popover.shown {
|
||||
self.closePopover(event)
|
||||
}
|
||||
@ -44,9 +44,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
// Insert code here to tear down your application
|
||||
}
|
||||
|
||||
// MARK: Popover
|
||||
|
||||
func showPopover(sender: AnyObject?) {
|
||||
if let button = statusItem.button {
|
||||
popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSMinYEdge)
|
||||
popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSRectEdge.MinY)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -15,7 +15,7 @@ struct Constants {
|
||||
|
||||
struct WebService {
|
||||
static let BASE = "www.ip-bc.org"
|
||||
static let UPDATE = "https://www.ip-bc.org/ws/update/ip"
|
||||
static let UPDATE = "https://update.ip-bc.org"
|
||||
static let GET_USERS_IP = "https://www.ip-bc.org/ws/info/ip"
|
||||
}
|
||||
|
||||
@ -30,5 +30,6 @@ struct Constants {
|
||||
static let NF_NETWORK_AVAILABLE = "NOTIFICATION_NETWORK_AVAILABLE"
|
||||
static let NF_NETWORK_NOT_AVAILABLE = "NOTIFICATION_NETWORK_NOT_AVAILABLE"
|
||||
static let NF_IP_HAS_CHANGED = "NOTIFICATION_IP_HAS_CHANGED"
|
||||
static let NF_DATA_USERDATA_HAS_CHANGED = "NOTIFICATION_DATA_USERDATA_HAS_CHANGED"
|
||||
}
|
||||
}
|
||||
@ -36,7 +36,7 @@ class MainViewController: NSViewController {
|
||||
txtToken.stringValue = udToken
|
||||
}
|
||||
|
||||
if !WebserviceClient.sharedInstance.checkNetwork() {
|
||||
if !WebserviceClient.sharedInstance.getIsNetworkAvailable() {
|
||||
lblCurrentIP.stringValue = "No internet connection!"
|
||||
}
|
||||
}
|
||||
@ -48,7 +48,7 @@ class MainViewController: NSViewController {
|
||||
}
|
||||
|
||||
@IBAction func actionOpenRegister(sender: NSButton) {
|
||||
|
||||
print("Not implemented yet")
|
||||
}
|
||||
|
||||
@IBAction func actionSaveSettings(sender: NSButton) {
|
||||
@ -56,6 +56,8 @@ class MainViewController: NSViewController {
|
||||
|
||||
defaults.setObject(txtName.stringValue, forKey: Constants.UserDefaults.HOST)
|
||||
defaults.setObject(txtToken.stringValue, forKey: Constants.UserDefaults.TOKEN)
|
||||
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.NF_DATA_USERDATA_HAS_CHANGED, object: nil)
|
||||
}
|
||||
|
||||
// MARK: Observer functions
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="7706" systemVersion="14F27" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
|
||||
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="9060" systemVersion="14F1021" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="7706"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="9060"/>
|
||||
</dependencies>
|
||||
<objects>
|
||||
<customObject id="-2" userLabel="File's Owner" customClass="MainViewController" customModule="ipbc_Client" customModuleProvider="target">
|
||||
<connections>
|
||||
<outlet property="btnCancel" destination="jbP-qx-AVu" id="8Kt-SW-cho"/>
|
||||
<outlet property="btnQuit" destination="PD1-7B-cXi" id="nZP-fa-Wgn"/>
|
||||
<outlet property="btnRegister" destination="1iz-w3-phH" id="SJg-gH-Plq"/>
|
||||
<outlet property="btnSave" destination="ypT-pC-8JJ" id="db6-84-UOc"/>
|
||||
@ -103,18 +102,8 @@
|
||||
<action selector="actionQuit:" target="-2" id="Sjv-pX-H2r"/>
|
||||
</connections>
|
||||
</button>
|
||||
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="jbP-qx-AVu">
|
||||
<rect key="frame" x="434" y="13" width="83" height="32"/>
|
||||
<buttonCell key="cell" type="push" title="Cancel" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="noM-tn-LGF">
|
||||
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
|
||||
<font key="font" metaFont="system"/>
|
||||
<string key="keyEquivalent" base64-UTF8="YES">
|
||||
Gw
|
||||
</string>
|
||||
</buttonCell>
|
||||
</button>
|
||||
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="ypT-pC-8JJ">
|
||||
<rect key="frame" x="363" y="13" width="71" height="32"/>
|
||||
<rect key="frame" x="446" y="13" width="71" height="32"/>
|
||||
<buttonCell key="cell" type="push" title="Save" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="aQB-ul-YJ5">
|
||||
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
|
||||
<font key="font" metaFont="system"/>
|
||||
|
||||
@ -7,113 +7,172 @@
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ReachabilitySwift
|
||||
import SwiftHTTP
|
||||
import Alamofire
|
||||
|
||||
|
||||
private let x_SomeManagerSharedInstance = WebserviceClient()
|
||||
|
||||
|
||||
class WebserviceClient {
|
||||
let reachability = Reachability.reachabilityForInternetConnection()
|
||||
|
||||
private var isNetworkAvailable : Bool = false
|
||||
private var isNetworkAvailableFirstCheck : Bool = true
|
||||
|
||||
class var sharedInstance: WebserviceClient {
|
||||
return x_SomeManagerSharedInstance
|
||||
}
|
||||
|
||||
init() {
|
||||
// init Reachability ...
|
||||
|
||||
let reachability = Reachability.reachabilityForInternetConnection()
|
||||
|
||||
self.isNetworkAvailable = reachability.isReachable()
|
||||
|
||||
reachability.whenReachable = { reachability in
|
||||
if reachability.isReachableViaWiFi() {
|
||||
println("WebserviceClient: Network reachable via WiFi")
|
||||
self.isNetworkAvailable = true
|
||||
} else {
|
||||
println("WebserviceClient: Network reachable via Cellular")
|
||||
self.isNetworkAvailable = true
|
||||
}
|
||||
|
||||
self.detectIP()
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.NF_IP_HAS_CHANGED, object: nil)
|
||||
}
|
||||
|
||||
reachability.whenUnreachable = { reachability in
|
||||
println("WebserviceClient: Network not reachable")
|
||||
self.isNetworkAvailable = false
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.NF_NETWORK_NOT_AVAILABLE, object: nil)
|
||||
}
|
||||
|
||||
reachability.startNotifier()
|
||||
|
||||
|
||||
// init IP things ...
|
||||
|
||||
self.detectIP() // initial call
|
||||
|
||||
|
||||
// init timer ...
|
||||
|
||||
//var timerIPCheck = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("click"), userInfo: nil, repeats: true)
|
||||
self.initNetwork()
|
||||
self.initTimer()
|
||||
self.initOnNotification()
|
||||
}
|
||||
|
||||
internal func checkNetwork() -> Bool {
|
||||
return self.isNetworkAvailable
|
||||
// MARK: init-functions
|
||||
|
||||
private func initNetwork() {
|
||||
self.checkNetwork()
|
||||
}
|
||||
|
||||
private func initTimer() {
|
||||
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("checkForNewIPTimerAction:"), userInfo: nil, repeats: true)
|
||||
}
|
||||
|
||||
private func initOnNotification() {
|
||||
NSNotificationCenter.defaultCenter().addObserver(self, selector: "observeUserIPHasChanged", name: Constants.Notification.NF_IP_HAS_CHANGED, object: nil)
|
||||
NSNotificationCenter.defaultCenter().addObserver(self, selector: "observeUserDataHasChanged", name: Constants.Notification.NF_DATA_USERDATA_HAS_CHANGED, object: nil)
|
||||
}
|
||||
|
||||
// MARK: Network
|
||||
|
||||
internal func checkNetwork() {
|
||||
let networkLastState : Bool = false
|
||||
|
||||
Alamofire.request(.GET, Constants.WebService.GET_USERS_IP, parameters: nil)
|
||||
.validate(statusCode: 200..<201)
|
||||
.validate(contentType: ["text/plain"])
|
||||
.responseString { response in
|
||||
/*
|
||||
print(response.request) // original URL request
|
||||
print(response.response) // URL response
|
||||
print(response.data) // server data
|
||||
print(response.result) // result of response serialization
|
||||
*/
|
||||
|
||||
switch response.result {
|
||||
case .Success:
|
||||
self.isNetworkAvailable = true
|
||||
let newIP : String = response.result.value ?? ""
|
||||
print("WebserviceClient: Network available from IP \(newIP)")
|
||||
self.detectIP()
|
||||
case .Failure(let error):
|
||||
self.isNetworkAvailable = false
|
||||
print("WebserviceClient: Error during network-check:")
|
||||
print(error)
|
||||
}
|
||||
|
||||
if self.isNetworkAvailableFirstCheck || self.isNetworkAvailable != networkLastState {
|
||||
if self.isNetworkAvailable {
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.NF_NETWORK_AVAILABLE, object: nil)
|
||||
} else {
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.NF_NETWORK_NOT_AVAILABLE, object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
if self.isNetworkAvailableFirstCheck && self.isNetworkAvailable {
|
||||
self.doUpdate()
|
||||
}
|
||||
|
||||
self.isNetworkAvailableFirstCheck = false
|
||||
}
|
||||
}
|
||||
|
||||
private func detectIP() {
|
||||
if isNetworkAvailable {
|
||||
var request = HTTPTask()
|
||||
// we have to add the explicit type, else the wrong type is inferred. See the vluxe.io article for more info.
|
||||
//let params: Dictionary<String,AnyObject> = ["param": "param1", "array": ["first array element","second","third"], "num": 23, "dict": ["someKey": "someVal"]]
|
||||
request.GET(Constants.WebService.GET_USERS_IP, parameters: nil, completionHandler: {(response: HTTPResponse) in
|
||||
if(response.statusCode == 200) {
|
||||
Alamofire.request(.GET, Constants.WebService.GET_USERS_IP, parameters: nil)
|
||||
.validate(statusCode: 200..<201)
|
||||
.validate(contentType: ["text/plain"])
|
||||
.responseString { response in
|
||||
/*
|
||||
print(response.request) // original URL request
|
||||
print(response.response) // URL response
|
||||
print(response.data) // server data
|
||||
print(response.result) // result of response serialization
|
||||
*/
|
||||
|
||||
switch response.result {
|
||||
case .Success:
|
||||
let defaults = NSUserDefaults.standardUserDefaults()
|
||||
let newIP : String = response.result.value ?? ""
|
||||
let oldIP : String = defaults.stringForKey(Constants.UserDefaults.PERSIST_LAST_USERS_IP) ?? ""
|
||||
|
||||
defaults.setValue(response.text, forKey: Constants.UserDefaults.PERSIST_LAST_USERS_IP)
|
||||
|
||||
if oldIP != defaults.stringForKey(Constants.UserDefaults.PERSIST_LAST_USERS_IP) {
|
||||
|
||||
//print("WebserviceClient: compare old IP \(oldIP) with new IP \(newIP)")
|
||||
if oldIP != newIP {
|
||||
// IP has changed
|
||||
|
||||
let newIP : String = defaults.stringForKey(Constants.UserDefaults.PERSIST_LAST_USERS_IP) ?? "--"
|
||||
println("WebserviceClient: new IP: \(newIP)")
|
||||
|
||||
|
||||
defaults.setValue(newIP, forKey: Constants.UserDefaults.PERSIST_LAST_USERS_IP)
|
||||
print("WebserviceClient: new IP: \(newIP)")
|
||||
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.NF_IP_HAS_CHANGED, object: newIP)
|
||||
}
|
||||
} else {
|
||||
println("WebserviceClient: Error detecting users ip.")
|
||||
if response.statusCode != nil {
|
||||
println("\(response.statusCode): \(response.text)")
|
||||
}
|
||||
case .Failure(let error):
|
||||
print("WebserviceClient: Error during get current IP:")
|
||||
print(error)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/*private func reachabilityChanged(note: NSNotification) {
|
||||
let reachability = note.object as! Reachability
|
||||
// MARK: Timer fire actions
|
||||
|
||||
@objc func checkForNewIPTimerAction(timer : NSTimer) {
|
||||
self.detectIP()
|
||||
}
|
||||
|
||||
// MARK: Observer functions
|
||||
|
||||
@objc func observeUserIPHasChanged() {
|
||||
self.doUpdate()
|
||||
}
|
||||
|
||||
@objc func observeUserDataHasChanged() {
|
||||
self.doUpdate()
|
||||
}
|
||||
|
||||
private func doUpdate() {
|
||||
let domain : String = NSUserDefaults.standardUserDefaults().stringForKey(Constants.UserDefaults.HOST) ?? ""
|
||||
let token : String = NSUserDefaults.standardUserDefaults().stringForKey(Constants.UserDefaults.TOKEN) ?? ""
|
||||
|
||||
if reachability.isReachable() {
|
||||
if reachability.isReachableViaWiFi() {
|
||||
println("WebserviceClient: Reachable via WiFi")
|
||||
} else {
|
||||
println("WebserviceClient: Reachable via Cellular")
|
||||
if !domain.isEmpty && !token.isEmpty {
|
||||
let headers = [
|
||||
"Content-Type": "application/json"
|
||||
]
|
||||
let parameters = [
|
||||
"domain": domain,
|
||||
"token": token
|
||||
]
|
||||
/*let parameters = [
|
||||
"": "{\"domain\":\"\(domain)\", \"token\":\"\(token)\"}"
|
||||
]*/
|
||||
Alamofire.request(.POST, Constants.WebService.UPDATE, headers: headers, parameters: parameters)
|
||||
.validate(statusCode: 200..<201)
|
||||
//.validate(contentType: ["application/json"])
|
||||
.responseString { response in
|
||||
/*
|
||||
print(response.request) // original URL request
|
||||
print(response.response) // URL response
|
||||
print(response.data) // server data
|
||||
print(response.result) // result of response serialization
|
||||
*/
|
||||
|
||||
switch response.result {
|
||||
case .Success:
|
||||
if let responseJSON = response.result.value {
|
||||
print("WebserviceClient: Update response: \(responseJSON)")
|
||||
}
|
||||
case .Failure(let error):
|
||||
print("WebserviceClient: Error during update:")
|
||||
print(error)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println("WebserviceClient: Network not reachable")
|
||||
}
|
||||
}*/
|
||||
|
||||
// MARK: Timer
|
||||
|
||||
func click() {
|
||||
println("click")
|
||||
}
|
||||
|
||||
// MARK: Getter
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user