123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695 |
- import Foundation
- public class Manager {
-
-
- public static let sharedInstance: Manager = {
- let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
- configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
- return Manager(configuration: configuration)
- }()
-
- public static let defaultHTTPHeaders: [String: String] = {
-
- let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
-
- let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
- let quality = 1.0 - (Double(index) * 0.1)
- return "\(languageCode);q=\(quality)"
- }.joinWithSeparator(", ")
-
- 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)
-
- public let session: NSURLSession
-
- public let delegate: SessionDelegate
-
- public var startRequestsImmediately: Bool = true
-
- public var backgroundCompletionHandler: (() -> Void)?
-
-
- 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)
- }
-
- 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()
- }
-
-
- 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)
- }
-
- 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
- }
-
-
- 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 }
- }
- }
-
- public override init() {
- super.init()
- }
-
-
-
- public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
-
- public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
-
- public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
-
-
- public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
- sessionDidBecomeInvalidWithError?(session, error)
- }
-
- 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)
- }
-
- public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
- sessionDidFinishEventsForBackgroundURLSession?(session)
- }
-
-
-
- public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
-
- public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
-
- public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
-
- public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
-
- public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
-
-
- 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)
- }
-
- 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)
- }
- }
-
- 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)
- }
- }
-
- 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
- )
- }
- }
-
- 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)
- }
- NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
- self[task] = nil
- }
-
-
-
- public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
-
- public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
-
- public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
-
- public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
-
-
- 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)
- }
-
- 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
- }
- }
-
- 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)
- }
- }
-
- 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)
- }
- }
-
-
-
- public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
-
- public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
-
- public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
-
-
- 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)
- }
- }
-
- 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
- )
- }
- }
-
- 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
- )
- }
- }
-
- var _streamTaskReadClosed: Any?
- var _streamTaskWriteClosed: Any?
- var _streamTaskBetterRouteDiscovered: Any?
- var _streamTaskDidBecomeInputStream: Any?
-
- 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)
- }
- }
- }
- }
|