SessionManager.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. //
  2. // SessionManager.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. open class SessionManager {
  26. open static let `default` = SessionManager()
  27. let configuration: URLSessionConfiguration
  28. let delegate: SessionDelegate
  29. let rootQueue: DispatchQueue
  30. let requestQueue: DispatchQueue
  31. open let adapter: RequestAdapter?
  32. open let retrier: RequestRetrier?
  33. open let trustManager: ServerTrustManager?
  34. let session: URLSession
  35. let eventMonitor: CompositeEventMonitor
  36. let defaultEventMonitors: [EventMonitor] = [] // TODO: Create notification event monitor, make default
  37. public init(configuration: URLSessionConfiguration = .default,
  38. delegate: SessionDelegate = SessionDelegate(),
  39. rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.sessionManager.rootQueue"),
  40. adapter: RequestAdapter? = nil,
  41. trustManager: ServerTrustManager? = nil,
  42. retrier: RequestRetrier? = nil,
  43. eventMonitors: [EventMonitor] = []) {
  44. self.configuration = configuration
  45. self.delegate = delegate
  46. self.rootQueue = rootQueue
  47. self.adapter = adapter
  48. self.retrier = retrier
  49. self.trustManager = trustManager
  50. requestQueue = DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue)
  51. let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.sessionManager.sessionDelegateQueue")
  52. session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
  53. eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors)
  54. delegate.didCreateSessionManager(self, withEventMonitor: eventMonitor)
  55. }
  56. deinit {
  57. session.invalidateAndCancel()
  58. }
  59. // MARK: - Request
  60. struct RequestConvertible: URLRequestConvertible {
  61. let url: URLConvertible
  62. let method: HTTPMethod
  63. let parameters: Parameters?
  64. let encoding: ParameterEncoding
  65. let headers: HTTPHeaders?
  66. func asURLRequest() throws -> URLRequest {
  67. let request = try URLRequest(url: url, method: method, headers: headers)
  68. return try encoding.encode(request, with: parameters)
  69. }
  70. }
  71. // TODO: Serialization Queue support?
  72. open func request(_ url: URLConvertible,
  73. method: HTTPMethod = .get,
  74. parameters: Parameters? = nil,
  75. encoding: ParameterEncoding = URLEncoding.default,
  76. headers: HTTPHeaders? = nil) -> DataRequest {
  77. let convertible = RequestConvertible(url: url,
  78. method: method,
  79. parameters: parameters,
  80. encoding: encoding,
  81. headers: headers)
  82. return request(convertible)
  83. }
  84. open func request(_ convertible: URLRequestConvertible) -> DataRequest {
  85. let request = DataRequest(convertible: convertible,
  86. underlyingQueue: rootQueue,
  87. eventMonitor: eventMonitor,
  88. delegate: delegate)
  89. perform(request)
  90. return request
  91. }
  92. // MARK: - Download
  93. open func download(_ convertible: URLConvertible,
  94. method: HTTPMethod = .get,
  95. parameters: Parameters? = nil,
  96. encoding: ParameterEncoding = URLEncoding.default,
  97. headers: HTTPHeaders? = nil,
  98. to destination: @escaping DownloadRequest.Destination = DownloadRequest.suggestedDownloadDestination()) -> DownloadRequest {
  99. let convertible = RequestConvertible(url: convertible,
  100. method: method,
  101. parameters: parameters,
  102. encoding: encoding,
  103. headers: headers)
  104. return download(convertible, to: destination)
  105. }
  106. func download(_ convertible: URLRequestConvertible,
  107. to destination: @escaping DownloadRequest.Destination = DownloadRequest.suggestedDownloadDestination()) -> DownloadRequest {
  108. let request = DownloadRequest(convertible: convertible,
  109. underlyingQueue: rootQueue,
  110. eventMonitor: eventMonitor,
  111. delegate: delegate,
  112. destination: destination)
  113. perform(request)
  114. return request
  115. }
  116. // MARK: - Upload
  117. struct UploadConvertible: URLRequestConvertible {
  118. let url: URLConvertible
  119. let method: HTTPMethod
  120. let headers: HTTPHeaders?
  121. func asURLRequest() throws -> URLRequest {
  122. return try URLRequest(url: url, method: method, headers: headers)
  123. }
  124. }
  125. func upload(_ data: Data,
  126. to convertible: URLConvertible,
  127. method: HTTPMethod = .post,
  128. headers: HTTPHeaders? = nil) -> UploadRequest {
  129. let convertible = UploadConvertible(url: convertible, method: method, headers: headers)
  130. return upload(data: data, to: convertible)
  131. }
  132. func upload(data: Data, to convertible: URLRequestConvertible) -> UploadRequest {
  133. return upload(.data(data), to: convertible)
  134. }
  135. func upload(_ fileURL: URL,
  136. to convertible: URLConvertible,
  137. method: HTTPMethod = .post,
  138. headers: HTTPHeaders? = nil) -> UploadRequest {
  139. let convertible = UploadConvertible(url: convertible, method: method, headers: headers)
  140. return upload(fileURL, to: convertible)
  141. }
  142. func upload(_ fileURL: URL, to convertible: URLRequestConvertible) -> UploadRequest {
  143. return upload(.file(fileURL), to: convertible)
  144. }
  145. func upload(_ stream: InputStream,
  146. to convertible: URLConvertible,
  147. method: HTTPMethod = .post,
  148. headers: HTTPHeaders? = nil) -> UploadRequest {
  149. let convertible = UploadConvertible(url: convertible, method: method, headers: headers)
  150. return upload(stream, to: convertible)
  151. }
  152. func upload(_ stream: InputStream, to convertible: URLRequestConvertible) -> UploadRequest {
  153. return upload(.stream(stream), to: convertible)
  154. }
  155. // MARK: - Internal API
  156. // MARK: Uploadable
  157. func upload(_ uploadable: UploadRequest.Uploadable, to convertible: URLRequestConvertible) -> UploadRequest {
  158. let request = UploadRequest(convertible: convertible,
  159. underlyingQueue: rootQueue,
  160. eventMonitor: eventMonitor,
  161. delegate: delegate,
  162. uploadable: uploadable)
  163. perform(request)
  164. return request
  165. }
  166. // MARK: Perform
  167. func perform(_ request: Request) {
  168. // TODO: Threadsafe adapter access?
  169. requestQueue.async { [adapter = adapter] in
  170. guard !request.isCancelled else { return }
  171. do {
  172. let initialRequest = try request.convertible.asURLRequest()
  173. self.rootQueue.async { request.didCreateURLRequest(initialRequest) }
  174. guard !request.isCancelled else { return }
  175. if let adapter = adapter {
  176. do {
  177. let adaptedRequest = try adapter.adapt(initialRequest)
  178. self.rootQueue.async {
  179. request.didAdaptInitialRequest(initialRequest, to: adaptedRequest)
  180. self.delegate.didCreateURLRequest(adaptedRequest, for: request)
  181. }
  182. } catch {
  183. self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: error) }
  184. }
  185. } else {
  186. self.rootQueue.async { self.delegate.didCreateURLRequest(initialRequest, for: request) }
  187. }
  188. } catch {
  189. self.rootQueue.async { request.didFailToCreateURLRequest(with: error) }
  190. }
  191. }
  192. }
  193. }