Manager.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. /**
  24. Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
  25. */
  26. public class Manager {
  27. // MARK: - Properties
  28. /**
  29. A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
  30. */
  31. public static let sharedInstance: Manager = {
  32. let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  33. configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
  34. return Manager(configuration: configuration)
  35. }()
  36. /**
  37. Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
  38. :returns: The default header values.
  39. */
  40. public static let defaultHTTPHeaders: [String: String] = {
  41. // Accept-Encoding HTTP Header; see http://tools.ietf.org/html/rfc7230#section-4.2.3
  42. let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
  43. // Accept-Language HTTP Header; see http://tools.ietf.org/html/rfc7231#section-5.3.5
  44. let acceptLanguage: String = {
  45. var components: [String] = []
  46. for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as! [String]) {
  47. let q = 1.0 - (Double(index) * 0.1)
  48. components.append("\(languageCode);q=\(q)")
  49. if q <= 0.5 {
  50. break
  51. }
  52. }
  53. return join(",", components)
  54. }()
  55. // User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3
  56. let userAgent: String = {
  57. if let info = NSBundle.mainBundle().infoDictionary {
  58. let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
  59. let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
  60. let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
  61. let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
  62. var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
  63. let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
  64. if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
  65. return mutableUserAgent as NSString as! String
  66. }
  67. }
  68. return "Alamofire"
  69. }()
  70. return [
  71. "Accept-Encoding": acceptEncoding,
  72. "Accept-Language": acceptLanguage,
  73. "User-Agent": userAgent
  74. ]
  75. }()
  76. let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
  77. /// The underlying session.
  78. public let session: NSURLSession
  79. /// The session delegate handling all the task and session delegate callbacks.
  80. public let delegate: SessionDelegate
  81. /// Whether to start requests immediately after being constructed. `true` by default.
  82. public var startRequestsImmediately: Bool = true
  83. /// 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.
  84. public var backgroundCompletionHandler: (() -> Void)?
  85. // MARK: - Lifecycle
  86. /**
  87. Initializes the Manager instance with the given configuration and server trust policy.
  88. :param: configuration The configuration used to construct the managed session. `nil` by default.
  89. :param: serverTrustPolicyManager The server trust policy manager to use for evaluating all server trust challenges. `nil` by default.
  90. */
  91. required public init(configuration: NSURLSessionConfiguration? = nil, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) {
  92. self.delegate = SessionDelegate()
  93. self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
  94. self.session.serverTrustPolicyManager = serverTrustPolicyManager
  95. self.delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
  96. if let strongSelf = self {
  97. strongSelf.backgroundCompletionHandler?()
  98. }
  99. }
  100. }
  101. deinit {
  102. self.session.invalidateAndCancel()
  103. }
  104. // MARK: - Request
  105. /**
  106. Creates a request for the specified method, URL string, parameters, and parameter encoding.
  107. :param: method The HTTP method.
  108. :param: URLString The URL string.
  109. :param: parameters The parameters. `nil` by default.
  110. :param: encoding The parameter encoding. `.URL` by default.
  111. :param: headers The HTTP headers. `nil` by default.
  112. :returns: The created request.
  113. */
  114. public func request(
  115. method: Method,
  116. _ URLString: URLStringConvertible,
  117. parameters: [String: AnyObject]? = nil,
  118. encoding: ParameterEncoding = .URL,
  119. headers: [String: String]? = nil)
  120. -> Request
  121. {
  122. let mutableURLRequest = URLRequest(method, URLString, headers: headers)
  123. let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
  124. return request(encodedURLRequest)
  125. }
  126. /**
  127. Creates a request for the specified URL request.
  128. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  129. :param: URLRequest The URL request
  130. :returns: The created request.
  131. */
  132. public func request(URLRequest: URLRequestConvertible) -> Request {
  133. var dataTask: NSURLSessionDataTask!
  134. dispatch_sync(self.queue) {
  135. dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
  136. }
  137. let request = Request(session: self.session, task: dataTask)
  138. delegate[request.delegate.task] = request.delegate
  139. if self.startRequestsImmediately {
  140. request.resume()
  141. }
  142. return request
  143. }
  144. // MARK: - SessionDelegate
  145. /**
  146. Responsible for handling all delegate callbacks for the underlying session.
  147. */
  148. public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
  149. private var subdelegates: [Int: Request.TaskDelegate] = [:]
  150. private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
  151. subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
  152. get {
  153. var subdelegate: Request.TaskDelegate?
  154. dispatch_sync(self.subdelegateQueue) {
  155. subdelegate = self.subdelegates[task.taskIdentifier]
  156. }
  157. return subdelegate
  158. }
  159. set {
  160. dispatch_barrier_async(self.subdelegateQueue) {
  161. self.subdelegates[task.taskIdentifier] = newValue
  162. }
  163. }
  164. }
  165. // MARK: - NSURLSessionDelegate
  166. // MARK: Override Closures
  167. /// NSURLSessionDelegate override closure for `URLSession:didBecomeInvalidWithError:` method.
  168. public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
  169. /// NSURLSessionDelegate override closure for `URLSession:didReceiveChallenge:completionHandler:` method.
  170. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
  171. /// NSURLSessionDelegate override closure for `URLSessionDidFinishEventsForBackgroundURLSession:` method.
  172. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
  173. // MARK: Delegate Methods
  174. public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
  175. self.sessionDidBecomeInvalidWithError?(session, error)
  176. }
  177. public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
  178. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  179. var credential: NSURLCredential!
  180. if let sessionDidReceiveChallenge = self.sessionDidReceiveChallenge {
  181. (disposition, credential) = sessionDidReceiveChallenge(session, challenge)
  182. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  183. let host = challenge.protectionSpace.host
  184. if let
  185. serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
  186. serverTrust = challenge.protectionSpace.serverTrust
  187. {
  188. if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
  189. disposition = .UseCredential
  190. credential = NSURLCredential(forTrust: serverTrust)
  191. } else {
  192. disposition = .CancelAuthenticationChallenge
  193. }
  194. }
  195. }
  196. completionHandler(disposition, credential)
  197. }
  198. public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
  199. self.sessionDidFinishEventsForBackgroundURLSession?(session)
  200. }
  201. // MARK: - NSURLSessionTaskDelegate
  202. // MARK: Override Closures
  203. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
  204. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
  205. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
  206. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
  207. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
  208. public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
  209. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
  210. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
  211. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
  212. public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
  213. // MARK: Delegate Methods
  214. public func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
  215. var redirectRequest: NSURLRequest? = request
  216. if let taskWillPerformHTTPRedirection = self.taskWillPerformHTTPRedirection {
  217. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  218. }
  219. completionHandler(redirectRequest)
  220. }
  221. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
  222. if let taskDidReceiveChallenge = self.taskDidReceiveChallenge {
  223. completionHandler(taskDidReceiveChallenge(session, task, challenge))
  224. } else if let delegate = self[task] {
  225. delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
  226. } else {
  227. URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
  228. }
  229. }
  230. public func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
  231. if let taskNeedNewBodyStream = self.taskNeedNewBodyStream {
  232. completionHandler(taskNeedNewBodyStream(session, task))
  233. } else if let delegate = self[task] {
  234. delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
  235. }
  236. }
  237. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  238. if let taskDidSendBodyData = self.taskDidSendBodyData {
  239. taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
  240. } else if let delegate = self[task] as? Request.UploadTaskDelegate {
  241. delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
  242. }
  243. }
  244. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  245. if let taskDidComplete = self.taskDidComplete {
  246. taskDidComplete(session, task, error)
  247. } else if let delegate = self[task] {
  248. delegate.URLSession(session, task: task, didCompleteWithError: error)
  249. self[task] = nil
  250. }
  251. }
  252. // MARK: - NSURLSessionDataDelegate
  253. // MARK: Override Closures
  254. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
  255. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
  256. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
  257. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
  258. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
  259. public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
  260. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
  261. public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
  262. // MARK: Delegate Methods
  263. public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
  264. var disposition: NSURLSessionResponseDisposition = .Allow
  265. if let dataTaskDidReceiveResponse = self.dataTaskDidReceiveResponse {
  266. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  267. }
  268. completionHandler(disposition)
  269. }
  270. public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
  271. if let dataTaskDidBecomeDownloadTask = self.dataTaskDidBecomeDownloadTask {
  272. dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
  273. } else {
  274. let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
  275. self[downloadTask] = downloadDelegate
  276. }
  277. }
  278. public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
  279. if let dataTaskDidReceiveData = self.dataTaskDidReceiveData {
  280. dataTaskDidReceiveData(session, dataTask, data)
  281. } else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
  282. delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
  283. }
  284. }
  285. public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
  286. if let dataTaskWillCacheResponse = self.dataTaskWillCacheResponse {
  287. completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
  288. } else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
  289. delegate.URLSession(session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler)
  290. } else {
  291. completionHandler(proposedResponse)
  292. }
  293. }
  294. // MARK: - NSURLSessionDownloadDelegate
  295. // MARK: Override Closures
  296. /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
  297. public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
  298. /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
  299. public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
  300. /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
  301. public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
  302. // MARK: Delegate Methods
  303. public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  304. if let downloadTaskDidFinishDownloadingToURL = self.downloadTaskDidFinishDownloadingToURL {
  305. downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
  306. } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  307. delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
  308. }
  309. }
  310. public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  311. if let downloadTaskDidWriteData = self.downloadTaskDidWriteData {
  312. downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  313. } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  314. delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  315. }
  316. }
  317. public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  318. if let downloadTaskDidResumeAtOffset = self.downloadTaskDidResumeAtOffset {
  319. downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
  320. } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  321. delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
  322. }
  323. }
  324. // MARK: - NSObject
  325. public override func respondsToSelector(selector: Selector) -> Bool {
  326. switch selector {
  327. case "URLSession:didBecomeInvalidWithError:":
  328. return (self.sessionDidBecomeInvalidWithError != nil)
  329. case "URLSession:didReceiveChallenge:completionHandler:":
  330. return (self.sessionDidReceiveChallenge != nil)
  331. case "URLSessionDidFinishEventsForBackgroundURLSession:":
  332. return (self.sessionDidFinishEventsForBackgroundURLSession != nil)
  333. case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
  334. return (self.taskWillPerformHTTPRedirection != nil)
  335. case "URLSession:dataTask:didReceiveResponse:completionHandler:":
  336. return (self.dataTaskDidReceiveResponse != nil)
  337. case "URLSession:dataTask:willCacheResponse:completionHandler:":
  338. return (self.dataTaskWillCacheResponse != nil)
  339. default:
  340. return self.dynamicType.instancesRespondToSelector(selector)
  341. }
  342. }
  343. }
  344. }