|
|
@@ -68,7 +68,7 @@ public enum ParameterEncoding {
|
|
|
|
|
|
/**
|
|
|
Creates a URL request by encoding parameters and applying them onto an existing request.
|
|
|
-
|
|
|
+
|
|
|
:param: URLRequest The request to have parameters applied
|
|
|
:param: parameters The parameters to apply
|
|
|
|
|
|
@@ -79,7 +79,7 @@ public enum ParameterEncoding {
|
|
|
return (URLRequest.URLRequest, nil)
|
|
|
}
|
|
|
|
|
|
- var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
|
|
|
+ var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
|
|
|
var error: NSError? = nil
|
|
|
|
|
|
switch self {
|
|
|
@@ -88,7 +88,7 @@ public enum ParameterEncoding {
|
|
|
var components: [(String, String)] = []
|
|
|
for key in sorted(Array(parameters.keys), <) {
|
|
|
let value: AnyObject! = parameters[key]
|
|
|
- components += queryComponents(key, value)
|
|
|
+ components += self.queryComponents(key, value)
|
|
|
}
|
|
|
|
|
|
return join("&", components.map{"\($0)=\($1)"} as [String])
|
|
|
@@ -187,7 +187,7 @@ extension NSURLComponents: URLStringConvertible {
|
|
|
|
|
|
extension NSURLRequest: URLStringConvertible {
|
|
|
public var URLString: String {
|
|
|
- return URL.URLString
|
|
|
+ return URL!.URLString
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -219,35 +219,26 @@ public class Manager {
|
|
|
/**
|
|
|
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
|
|
|
*/
|
|
|
- public class var sharedInstance: Manager {
|
|
|
- struct Singleton {
|
|
|
- static var configuration: NSURLSessionConfiguration = {
|
|
|
- var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
|
|
- configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders()
|
|
|
-
|
|
|
- return configuration
|
|
|
- }()
|
|
|
-
|
|
|
- static let instance = Manager(configuration: configuration)
|
|
|
- }
|
|
|
+ public static let sharedInstance: Manager = {
|
|
|
+ let configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
|
|
+ configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
|
|
|
|
|
|
- return Singleton.instance
|
|
|
- }
|
|
|
+ return Manager(configuration: configuration)
|
|
|
+ }()
|
|
|
|
|
|
/**
|
|
|
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
|
|
|
|
|
|
:returns: The default header values.
|
|
|
*/
|
|
|
- public class func defaultHTTPHeaders() -> [String: String] {
|
|
|
-
|
|
|
+ public static let defaultHTTPHeaders: [String: String] = {
|
|
|
// Accept-Encoding HTTP Header; see http://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 http://tools.ietf.org/html/rfc7231#section-5.3.5
|
|
|
let acceptLanguage: String = {
|
|
|
var components: [String] = []
|
|
|
- for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
|
|
|
+ for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as! [String]) {
|
|
|
let q = 1.0 - (Double(index) * 0.1)
|
|
|
components.append("\(languageCode);q=\(q)")
|
|
|
if q <= 0.5 {
|
|
|
@@ -269,16 +260,17 @@ public class Manager {
|
|
|
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, nil, transform, 0) == 1 {
|
|
|
- return mutableUserAgent as NSString
|
|
|
+ return mutableUserAgent as NSString as! String
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
return "Alamofire"
|
|
|
}()
|
|
|
|
|
|
return ["Accept-Encoding": acceptEncoding,
|
|
|
"Accept-Language": acceptLanguage,
|
|
|
"User-Agent": userAgent]
|
|
|
- }
|
|
|
+ }()
|
|
|
|
|
|
private let delegate: SessionDelegate
|
|
|
|
|
|
@@ -352,7 +344,7 @@ public class Manager {
|
|
|
|
|
|
return subdelegate
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
set {
|
|
|
dispatch_barrier_async(subdelegateQueue) {
|
|
|
self.subdelegates[task.taskIdentifier] = newValue
|
|
|
@@ -385,11 +377,11 @@ public class Manager {
|
|
|
|
|
|
// MARK: NSURLSessionDelegate
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
|
|
|
+ func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
|
|
|
sessionDidBecomeInvalidWithError?(session, error)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
|
|
|
if sessionDidReceiveChallenge != nil {
|
|
|
completionHandler(sessionDidReceiveChallenge!(session, challenge))
|
|
|
} else {
|
|
|
@@ -397,13 +389,13 @@ public class Manager {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
|
|
|
+ func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
|
|
|
sessionDidFinishEventsForBackgroundURLSession?(session)
|
|
|
}
|
|
|
|
|
|
// MARK: NSURLSessionTaskDelegate
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
|
|
|
var redirectRequest = request
|
|
|
if taskWillPerformHTTPRedirection != nil {
|
|
|
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
|
|
|
@@ -412,7 +404,7 @@ public class Manager {
|
|
|
completionHandler(redirectRequest)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
|
|
|
if let delegate = self[task] {
|
|
|
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
|
|
|
} else {
|
|
|
@@ -420,19 +412,19 @@ public class Manager {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
|
|
|
if let delegate = self[task] {
|
|
|
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
|
|
|
if let delegate = self[task] as? Request.UploadTaskDelegate {
|
|
|
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
|
|
if let delegate = self[task] {
|
|
|
delegate.URLSession(session, task: task, didCompleteWithError: error)
|
|
|
|
|
|
@@ -442,7 +434,7 @@ public class Manager {
|
|
|
|
|
|
// MARK: NSURLSessionDataDelegate
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
|
|
|
var disposition: NSURLSessionResponseDisposition = .Allow
|
|
|
|
|
|
if dataTaskDidReceiveResponse != nil {
|
|
|
@@ -452,12 +444,12 @@ public class Manager {
|
|
|
completionHandler(disposition)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
|
|
|
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
|
|
|
self[downloadTask] = downloadDelegate
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
|
|
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
|
|
|
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
|
|
|
}
|
|
|
@@ -465,7 +457,7 @@ public class Manager {
|
|
|
dataTaskDidReceiveData?(session, dataTask, data)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
|
|
|
var cachedResponse = proposedResponse
|
|
|
|
|
|
if dataTaskWillCacheResponse != nil {
|
|
|
@@ -641,7 +633,7 @@ public class Request {
|
|
|
:returns: The request.
|
|
|
*/
|
|
|
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
|
|
|
- return response(Request.responseDataSerializer(), completionHandler: completionHandler)
|
|
|
+ return response(serializer: Request.responseDataSerializer(), completionHandler: completionHandler)
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -722,7 +714,7 @@ public class Request {
|
|
|
|
|
|
// MARK: NSURLSessionTaskDelegate
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
|
|
|
var redirectRequest = request
|
|
|
if taskWillPerformHTTPRedirection != nil {
|
|
|
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
|
|
|
@@ -731,7 +723,7 @@ public class Request {
|
|
|
completionHandler(redirectRequest)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
|
|
|
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
|
|
var credential: NSURLCredential?
|
|
|
|
|
|
@@ -759,7 +751,7 @@ public class Request {
|
|
|
completionHandler(disposition, credential)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
|
|
|
var bodyStream: NSInputStream?
|
|
|
if taskNeedNewBodyStream != nil {
|
|
|
bodyStream = taskNeedNewBodyStream!(session, task)
|
|
|
@@ -768,7 +760,7 @@ public class Request {
|
|
|
completionHandler(bodyStream)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
|
|
|
+ func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
|
|
if error != nil {
|
|
|
self.error = error
|
|
|
}
|
|
|
@@ -778,7 +770,7 @@ public class Request {
|
|
|
}
|
|
|
|
|
|
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
|
|
|
- var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
|
|
|
+ var dataTask: NSURLSessionDataTask! { return task as! NSURLSessionDataTask }
|
|
|
|
|
|
private var mutableData: NSMutableData
|
|
|
override var data: NSData? {
|
|
|
@@ -800,7 +792,7 @@ public class Request {
|
|
|
|
|
|
// MARK: NSURLSessionDataDelegate
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
|
|
|
var disposition: NSURLSessionResponseDisposition = .Allow
|
|
|
|
|
|
expectedContentLength = response.expectedContentLength
|
|
|
@@ -812,21 +804,21 @@ public class Request {
|
|
|
completionHandler(disposition)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
|
|
|
dataTaskDidBecomeDownloadTask?(session, dataTask)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
|
|
dataTaskDidReceiveData?(session, dataTask, data)
|
|
|
|
|
|
mutableData.appendData(data)
|
|
|
|
|
|
- if let expectedContentLength = dataTask?.response?.expectedContentLength {
|
|
|
+ if let expectedContentLength = dataTask.response?.expectedContentLength {
|
|
|
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
|
|
|
+ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
|
|
|
var cachedResponse = proposedResponse
|
|
|
|
|
|
if dataTaskWillCacheResponse != nil {
|
|
|
@@ -870,10 +862,6 @@ extension Request {
|
|
|
|
|
|
// MARK: Status Code
|
|
|
|
|
|
- private class func response(response: NSHTTPURLResponse, hasAcceptableStatusCode statusCodes: [Int]) -> Bool {
|
|
|
- return contains(statusCodes, response.statusCode)
|
|
|
- }
|
|
|
-
|
|
|
/**
|
|
|
Validates that the response has a status code in the specified range.
|
|
|
|
|
|
@@ -883,24 +871,9 @@ extension Request {
|
|
|
|
|
|
:returns: The request.
|
|
|
*/
|
|
|
- public func validate(statusCode range: Range<Int>) -> Self {
|
|
|
- return validate { (_, response) in
|
|
|
- return Request.response(response, hasAcceptableStatusCode: range.map({$0}))
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- Validates that the response has a status code in the specified array.
|
|
|
-
|
|
|
- If validation fails, subsequent calls to response handlers will have an associated error.
|
|
|
-
|
|
|
- :param: array The acceptable status codes.
|
|
|
-
|
|
|
- :returns: The request.
|
|
|
- */
|
|
|
- public func validate(statusCode array: [Int]) -> Self {
|
|
|
+ public func validate<S : SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
|
|
|
return validate { (_, response) in
|
|
|
- return Request.response(response, hasAcceptableStatusCode: array)
|
|
|
+ return contains(acceptableStatusCode, response.statusCode)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -910,16 +883,22 @@ extension Request {
|
|
|
let type: String
|
|
|
let subtype: String
|
|
|
|
|
|
- init(_ string: String) {
|
|
|
+ init?(_ string: String) {
|
|
|
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
|
|
|
|
|
|
- self.type = components.first!
|
|
|
- self.subtype = components.last!
|
|
|
+ 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.subtype), (MIME.type, "*"), (MIME.type, MIME.subtype):
|
|
|
+ case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
|
|
|
return true
|
|
|
default:
|
|
|
return false
|
|
|
@@ -927,19 +906,6 @@ extension Request {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- private class func response(response: NSHTTPURLResponse, hasAcceptableContentType contentTypes: [String]) -> Bool {
|
|
|
- if response.MIMEType != nil {
|
|
|
- let responseMIMEType = MIMEType(response.MIMEType!)
|
|
|
- for acceptableMIMEType in contentTypes.map({MIMEType($0)}) {
|
|
|
- if acceptableMIMEType.matches(responseMIMEType) {
|
|
|
- return true
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- return false
|
|
|
- }
|
|
|
-
|
|
|
/**
|
|
|
Validates that the response has a content type in the specified array.
|
|
|
|
|
|
@@ -949,9 +915,21 @@ extension Request {
|
|
|
|
|
|
:returns: The request.
|
|
|
*/
|
|
|
- public func validate(contentType array: [String]) -> Self {
|
|
|
+ public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
|
|
|
return validate {(_, response) in
|
|
|
- return Request.response(response, hasAcceptableContentType: array)
|
|
|
+ if let responseContentType = response.MIMEType,
|
|
|
+ responseMIMEType = MIMEType(responseContentType)
|
|
|
+ {
|
|
|
+ for contentType in acceptableContentTypes {
|
|
|
+ if let acceptableMIMEType = MIMEType(contentType)
|
|
|
+ where acceptableMIMEType.matches(responseMIMEType)
|
|
|
+ {
|
|
|
+ return true
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return false
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -973,7 +951,7 @@ extension Request {
|
|
|
|
|
|
return ["*/*"]
|
|
|
}()
|
|
|
-
|
|
|
+
|
|
|
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
|
|
|
}
|
|
|
}
|
|
|
@@ -1031,16 +1009,16 @@ extension Manager {
|
|
|
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.
|
|
|
-
|
|
|
+
|
|
|
:param: method The HTTP method.
|
|
|
:param: URLString The URL string.
|
|
|
:param: file The file to upload
|
|
|
-
|
|
|
+
|
|
|
:returns: The created upload request.
|
|
|
*/
|
|
|
public func upload(method: Method, _ URLString: URLStringConvertible, file: NSURL) -> Request {
|
|
|
@@ -1062,16 +1040,16 @@ extension Manager {
|
|
|
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.
|
|
|
-
|
|
|
+
|
|
|
:param: method The HTTP method.
|
|
|
:param: URLString The URL string.
|
|
|
:param: data The data to upload
|
|
|
-
|
|
|
+
|
|
|
:returns: The created upload request.
|
|
|
*/
|
|
|
public func upload(method: Method, _ URLString: URLStringConvertible, data: NSData) -> Request {
|
|
|
@@ -1093,12 +1071,12 @@ extension Manager {
|
|
|
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.
|
|
|
-
|
|
|
+
|
|
|
:param: method The HTTP method.
|
|
|
:param: URLString The URL string.
|
|
|
:param: stream The stream to upload.
|
|
|
@@ -1112,7 +1090,7 @@ extension Manager {
|
|
|
|
|
|
extension Request {
|
|
|
class UploadTaskDelegate: DataTaskDelegate {
|
|
|
- var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
|
|
|
+ var uploadTask: NSURLSessionUploadTask! { return task as! NSURLSessionUploadTask }
|
|
|
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
|
|
|
|
|
|
// MARK: NSURLSessionTaskDelegate
|
|
|
@@ -1147,7 +1125,7 @@ extension Manager {
|
|
|
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)
|
|
|
+ return destination(URL, downloadTask.response as! NSHTTPURLResponse)
|
|
|
}
|
|
|
}
|
|
|
delegate[request.delegate.task] = request.delegate
|
|
|
@@ -1213,7 +1191,7 @@ extension Request {
|
|
|
|
|
|
/**
|
|
|
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.
|
|
|
-
|
|
|
+
|
|
|
:param: directory The search path directory. `.DocumentDirectory` by default.
|
|
|
:param: domain The search path domain mask. `.UserDomainMask` by default.
|
|
|
|
|
|
@@ -1231,7 +1209,7 @@ extension Request {
|
|
|
}
|
|
|
|
|
|
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
|
|
|
- var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
|
|
|
+ var downloadTask: NSURLSessionDownloadTask! { return task as! NSURLSessionDownloadTask }
|
|
|
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
|
|
|
|
|
|
var resumeData: NSData?
|
|
|
@@ -1255,7 +1233,7 @@ extension Request {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
|
|
+ func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
|
|
progress.totalUnitCount = totalBytesExpectedToWrite
|
|
|
progress.completedUnitCount = totalBytesWritten
|
|
|
|
|
|
@@ -1264,7 +1242,7 @@ extension Request {
|
|
|
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
|
|
}
|
|
|
|
|
|
- func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
|
|
|
+ func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
|
|
|
progress.totalUnitCount = expectedTotalBytes
|
|
|
progress.completedUnitCount = fileOffset
|
|
|
|
|
|
@@ -1283,7 +1261,7 @@ extension Request: Printable {
|
|
|
components.append(request.HTTPMethod!)
|
|
|
}
|
|
|
|
|
|
- components.append(request.URL.absoluteString!)
|
|
|
+ components.append(request.URL!.absoluteString!)
|
|
|
|
|
|
if response != nil {
|
|
|
components.append("(\(response!.statusCode))")
|
|
|
@@ -1304,9 +1282,9 @@ extension Request: DebugPrintable {
|
|
|
}
|
|
|
|
|
|
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)
|
|
|
+ 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.array {
|
|
|
- for credential: NSURLCredential in (credentials as [NSURLCredential]) {
|
|
|
+ for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
|
|
|
components.append("-u \(credential.user!):\(credential.password!)")
|
|
|
}
|
|
|
} else {
|
|
|
@@ -1319,13 +1297,12 @@ extension Request: DebugPrintable {
|
|
|
// Temporarily disabled on OS X due to build failure for CocoaPods
|
|
|
// See https://github.com/CocoaPods/swift/issues/24
|
|
|
#if !os(OSX)
|
|
|
- if let cookieStorage = session.configuration.HTTPCookieStorage {
|
|
|
- if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
|
|
|
- if !cookies.isEmpty {
|
|
|
- let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
|
|
|
- components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
|
|
|
- }
|
|
|
- }
|
|
|
+ if let cookieStorage = session.configuration.HTTPCookieStorage,
|
|
|
+ cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie]
|
|
|
+ where !cookies.isEmpty
|
|
|
+ {
|
|
|
+ let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
|
|
|
+ components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
|
|
|
}
|
|
|
#endif
|
|
|
|
|
|
@@ -1350,14 +1327,14 @@ extension Request: DebugPrintable {
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
-
|
|
|
- if let HTTPBody = request.HTTPBody {
|
|
|
- if let escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") {
|
|
|
- components.append("-d \"\(escapedBody)\"")
|
|
|
- }
|
|
|
+
|
|
|
+ if let HTTPBody = request.HTTPBody,
|
|
|
+ escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
|
|
|
+ {
|
|
|
+ components.append("-d \"\(escapedBody)\"")
|
|
|
}
|
|
|
|
|
|
- components.append("\"\(URL.absoluteString!)\"")
|
|
|
+ components.append("\"\(URL!.absoluteString!)\"")
|
|
|
|
|
|
return join(" \\\n\t", components)
|
|
|
}
|
|
|
@@ -1376,38 +1353,37 @@ extension Request {
|
|
|
/**
|
|
|
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
|
|
|
|
|
|
- :param: encoding The string encoding. `NSUTF8StringEncoding` by default.
|
|
|
+ :param: 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 class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
|
|
|
- return { (_, _, data) in
|
|
|
- let string = NSString(data: data!, encoding: encoding)
|
|
|
-
|
|
|
- return (string, nil)
|
|
|
- }
|
|
|
- }
|
|
|
+ public class func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> Serializer {
|
|
|
+ return { (_, response, data) in
|
|
|
+ if data == nil || data?.length == 0 {
|
|
|
+ return (nil, nil)
|
|
|
+ }
|
|
|
|
|
|
- /**
|
|
|
- Adds a handler to be called once the request has finished.
|
|
|
+ if encoding == nil {
|
|
|
+ if let encodingName = response?.textEncodingName {
|
|
|
+ encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
- :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
|
|
|
+ let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding)
|
|
|
|
|
|
- :returns: The request.
|
|
|
- */
|
|
|
- public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
|
|
|
- return responseString(completionHandler: completionHandler)
|
|
|
+ return (string, nil)
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
Adds a handler to be called once the request has finished.
|
|
|
|
|
|
- :param: encoding The string encoding. `NSUTF8StringEncoding` by default.
|
|
|
+ :param: 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.
|
|
|
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
|
|
|
|
|
|
:returns: The request.
|
|
|
*/
|
|
|
- public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
|
|
|
+ public func responseString(encoding: NSStringEncoding? = nil, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
|
|
|
return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
|
|
|
completionHandler(request, response, string as? String, error)
|
|
|
})
|
|
|
@@ -1437,17 +1413,6 @@ extension Request {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- /**
|
|
|
- Adds a handler to be called once the request has finished.
|
|
|
-
|
|
|
- :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
|
|
|
-
|
|
|
- :returns: The request.
|
|
|
- */
|
|
|
- public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
|
|
|
- return responseJSON(completionHandler: completionHandler)
|
|
|
- }
|
|
|
-
|
|
|
/**
|
|
|
Adds a handler to be called once the request has finished.
|
|
|
|
|
|
@@ -1486,17 +1451,6 @@ extension Request {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- /**
|
|
|
- Adds a handler to be called once the request has finished.
|
|
|
-
|
|
|
- :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
|
|
|
-
|
|
|
- :returns: The request.
|
|
|
- */
|
|
|
- public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
|
|
|
- return responsePropertyList(completionHandler: completionHandler)
|
|
|
- }
|
|
|
-
|
|
|
/**
|
|
|
Adds a handler to be called once the request has finished.
|
|
|
|