SessionManager.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. //
  2. // SessionManager.swift
  3. //
  4. // Copyright (c) 2014-2016 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. /// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
  26. open class SessionManager {
  27. // MARK: - Helper Types
  28. /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
  29. /// associated values.
  30. ///
  31. /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with
  32. /// streaming information.
  33. /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
  34. /// error.
  35. public enum MultipartFormDataEncodingResult {
  36. case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
  37. case failure(Error)
  38. }
  39. // MARK: - Properties
  40. /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use
  41. /// directly for any ad hoc requests.
  42. open static let `default`: SessionManager = {
  43. let configuration = URLSessionConfiguration.default
  44. configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
  45. return SessionManager(configuration: configuration)
  46. }()
  47. /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
  48. open static let defaultHTTPHeaders: HTTPHeaders = {
  49. // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
  50. let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
  51. // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
  52. let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
  53. let quality = 1.0 - (Double(index) * 0.1)
  54. return "\(languageCode);q=\(quality)"
  55. }.joined(separator: ", ")
  56. // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
  57. // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`
  58. let userAgent: String = {
  59. if let info = Bundle.main.infoDictionary {
  60. let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
  61. let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
  62. let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
  63. let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
  64. let osNameVersion: String = {
  65. let version = ProcessInfo.processInfo.operatingSystemVersion
  66. let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
  67. let osName: String = {
  68. #if os(iOS)
  69. return "iOS"
  70. #elseif os(watchOS)
  71. return "watchOS"
  72. #elseif os(tvOS)
  73. return "tvOS"
  74. #elseif os(macOS)
  75. return "OS X"
  76. #elseif os(Linux)
  77. return "Linux"
  78. #else
  79. return "Unknown"
  80. #endif
  81. }()
  82. return "\(osName) \(versionString)"
  83. }()
  84. let alamofireVersion: String = {
  85. guard
  86. let afInfo = Bundle(for: SessionManager.self).infoDictionary,
  87. let build = afInfo["CFBundleShortVersionString"]
  88. else { return "Unknown" }
  89. return "Alamofire/\(build)"
  90. }()
  91. return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
  92. }
  93. return "Alamofire"
  94. }()
  95. return [
  96. "Accept-Encoding": acceptEncoding,
  97. "Accept-Language": acceptLanguage,
  98. "User-Agent": userAgent
  99. ]
  100. }()
  101. /// Default memory threshold used when encoding `MultipartFormData` in bytes.
  102. open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000
  103. /// The underlying session.
  104. open let session: URLSession
  105. /// The session delegate handling all the task and session delegate callbacks.
  106. open let delegate: SessionDelegate
  107. /// Whether to start requests immediately after being constructed. `true` by default.
  108. open var startRequestsImmediately: Bool = true
  109. /// The request adapter called each time a new request is created.
  110. open var adapter: RequestAdapter?
  111. /// The request retrier called each time a request encounters an error to determine whether to retry the request.
  112. open var retrier: RequestRetrier? {
  113. get { return delegate.retrier }
  114. set { delegate.retrier = newValue }
  115. }
  116. /// The background completion handler closure provided by the UIApplicationDelegate
  117. /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
  118. /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
  119. /// will automatically call the handler.
  120. ///
  121. /// If you need to handle your own events before the handler is called, then you need to override the
  122. /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
  123. ///
  124. /// `nil` by default.
  125. open var backgroundCompletionHandler: (() -> Void)?
  126. let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
  127. // MARK: - Lifecycle
  128. /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`.
  129. ///
  130. /// - parameter configuration: The configuration used to construct the managed session.
  131. /// `URLSessionConfiguration.default` by default.
  132. /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
  133. /// default.
  134. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
  135. /// challenges. `nil` by default.
  136. ///
  137. /// - returns: The new `SessionManager` instance.
  138. public init(
  139. configuration: URLSessionConfiguration = URLSessionConfiguration.default,
  140. delegate: SessionDelegate = SessionDelegate(),
  141. serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
  142. {
  143. self.delegate = delegate
  144. self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
  145. commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
  146. }
  147. /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`.
  148. ///
  149. /// - parameter session: The URL session.
  150. /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
  151. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
  152. /// challenges. `nil` by default.
  153. ///
  154. /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise.
  155. public init?(
  156. session: URLSession,
  157. delegate: SessionDelegate,
  158. serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
  159. {
  160. guard delegate === session.delegate else { return nil }
  161. self.delegate = delegate
  162. self.session = session
  163. commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
  164. }
  165. private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
  166. session.serverTrustPolicyManager = serverTrustPolicyManager
  167. delegate.sessionManager = self
  168. delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
  169. guard let strongSelf = self else { return }
  170. DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
  171. }
  172. }
  173. deinit {
  174. session.invalidateAndCancel()
  175. }
  176. // MARK: - Data Request
  177. /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding`
  178. /// and `headers`.
  179. ///
  180. /// - parameter url: The URL.
  181. /// - parameter method: The HTTP method. `.get` by default.
  182. /// - parameter parameters: The parameters. `nil` by default.
  183. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  184. /// - parameter headers: The HTTP headers. `nil` by default.
  185. ///
  186. /// - returns: The created `DataRequest`.
  187. @discardableResult
  188. open func request(
  189. _ url: URLConvertible,
  190. method: HTTPMethod = .get,
  191. parameters: Parameters? = nil,
  192. encoding: ParameterEncoding = URLEncoding.default,
  193. headers: HTTPHeaders? = nil)
  194. -> DataRequest
  195. {
  196. var originalRequest: URLRequest?
  197. do {
  198. originalRequest = try URLRequest(url: url, method: method, headers: headers)
  199. let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
  200. return request(encodedURLRequest)
  201. } catch {
  202. return request(originalRequest, failedWith: error)
  203. }
  204. }
  205. /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
  206. ///
  207. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  208. ///
  209. /// - parameter urlRequest: The URL request.
  210. ///
  211. /// - returns: The created `DataRequest`.
  212. open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
  213. var originalRequest: URLRequest?
  214. do {
  215. originalRequest = try urlRequest.asURLRequest()
  216. let originalTask = DataRequest.Requestable(urlRequest: originalRequest!)
  217. let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
  218. let request = DataRequest(session: session, requestTask: .data(originalTask, task))
  219. delegate[task] = request
  220. if startRequestsImmediately { request.resume() }
  221. return request
  222. } catch {
  223. return request(originalRequest, failedWith: error)
  224. }
  225. }
  226. // MARK: Private - Request Implementation
  227. private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest {
  228. var requestTask: Request.RequestTask = .data(nil, nil)
  229. if let urlRequest = urlRequest {
  230. let originalTask = DataRequest.Requestable(urlRequest: urlRequest)
  231. requestTask = .data(originalTask, nil)
  232. }
  233. let underlyingError = error.underlyingAdaptError ?? error
  234. let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError)
  235. if let retrier = retrier, error is AdaptError {
  236. allowRetrier(retrier, toRetry: request, with: underlyingError)
  237. } else {
  238. if startRequestsImmediately { request.resume() }
  239. }
  240. return request
  241. }
  242. // MARK: - Download Request
  243. // MARK: URL Request
  244. /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`,
  245. /// `headers` and save them to the `destination`.
  246. ///
  247. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  248. /// underlying URL session.
  249. ///
  250. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  251. ///
  252. /// - parameter url: The URL.
  253. /// - parameter method: The HTTP method. `.get` by default.
  254. /// - parameter parameters: The parameters. `nil` by default.
  255. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  256. /// - parameter headers: The HTTP headers. `nil` by default.
  257. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  258. ///
  259. /// - returns: The created `DownloadRequest`.
  260. @discardableResult
  261. open func download(
  262. _ url: URLConvertible,
  263. method: HTTPMethod = .get,
  264. parameters: Parameters? = nil,
  265. encoding: ParameterEncoding = URLEncoding.default,
  266. headers: HTTPHeaders? = nil,
  267. to destination: DownloadRequest.DownloadFileDestination? = nil)
  268. -> DownloadRequest
  269. {
  270. do {
  271. let urlRequest = try URLRequest(url: url, method: method, headers: headers)
  272. let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
  273. return download(encodedURLRequest, to: destination)
  274. } catch {
  275. return download(nil, to: destination, failedWith: error)
  276. }
  277. }
  278. /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
  279. /// them to the `destination`.
  280. ///
  281. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  282. /// underlying URL session.
  283. ///
  284. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  285. ///
  286. /// - parameter urlRequest: The URL request
  287. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  288. ///
  289. /// - returns: The created `DownloadRequest`.
  290. @discardableResult
  291. open func download(
  292. _ urlRequest: URLRequestConvertible,
  293. to destination: DownloadRequest.DownloadFileDestination? = nil)
  294. -> DownloadRequest
  295. {
  296. do {
  297. let urlRequest = try urlRequest.asURLRequest()
  298. return download(.request(urlRequest), to: destination)
  299. } catch {
  300. return download(nil, to: destination, failedWith: error)
  301. }
  302. }
  303. // MARK: Resume Data
  304. /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
  305. /// the contents of the original request and save them to the `destination`.
  306. ///
  307. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  308. /// underlying URL session.
  309. ///
  310. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  311. ///
  312. /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken
  313. /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the
  314. /// data is written incorrectly and will always fail to resume the download. For more information about the bug and
  315. /// possible workarounds, please refer to the following Stack Overflow post:
  316. ///
  317. /// - http://stackoverflow.com/a/39347461/1342462
  318. ///
  319. /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
  320. /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
  321. /// additional information.
  322. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  323. ///
  324. /// - returns: The created `DownloadRequest`.
  325. @discardableResult
  326. open func download(
  327. resumingWith resumeData: Data,
  328. to destination: DownloadRequest.DownloadFileDestination? = nil)
  329. -> DownloadRequest
  330. {
  331. return download(.resumeData(resumeData), to: destination)
  332. }
  333. // MARK: Private - Download Implementation
  334. private func download(
  335. _ downloadable: DownloadRequest.Downloadable,
  336. to destination: DownloadRequest.DownloadFileDestination?)
  337. -> DownloadRequest
  338. {
  339. do {
  340. let task = try downloadable.task(session: session, adapter: adapter, queue: queue)
  341. let download = DownloadRequest(session: session, requestTask: .download(downloadable, task))
  342. download.downloadDelegate.destination = destination
  343. delegate[task] = download
  344. if startRequestsImmediately { download.resume() }
  345. return download
  346. } catch {
  347. return download(downloadable, to: destination, failedWith: error)
  348. }
  349. }
  350. private func download(
  351. _ downloadable: DownloadRequest.Downloadable?,
  352. to destination: DownloadRequest.DownloadFileDestination?,
  353. failedWith error: Error)
  354. -> DownloadRequest
  355. {
  356. var downloadTask: Request.RequestTask = .download(nil, nil)
  357. if let downloadable = downloadable {
  358. downloadTask = .download(downloadable, nil)
  359. }
  360. let underlyingError = error.underlyingAdaptError ?? error
  361. let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError)
  362. download.downloadDelegate.destination = destination
  363. if let retrier = retrier, error is AdaptError {
  364. allowRetrier(retrier, toRetry: download, with: underlyingError)
  365. } else {
  366. if startRequestsImmediately { download.resume() }
  367. }
  368. return download
  369. }
  370. // MARK: - Upload Request
  371. // MARK: File
  372. /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`.
  373. ///
  374. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  375. ///
  376. /// - parameter file: The file to upload.
  377. /// - parameter url: The URL.
  378. /// - parameter method: The HTTP method. `.post` by default.
  379. /// - parameter headers: The HTTP headers. `nil` by default.
  380. ///
  381. /// - returns: The created `UploadRequest`.
  382. @discardableResult
  383. open func upload(
  384. _ fileURL: URL,
  385. to url: URLConvertible,
  386. method: HTTPMethod = .post,
  387. headers: HTTPHeaders? = nil)
  388. -> UploadRequest
  389. {
  390. do {
  391. let urlRequest = try URLRequest(url: url, method: method, headers: headers)
  392. return upload(fileURL, with: urlRequest)
  393. } catch {
  394. return upload(nil, failedWith: error)
  395. }
  396. }
  397. /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
  398. ///
  399. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  400. ///
  401. /// - parameter file: The file to upload.
  402. /// - parameter urlRequest: The URL request.
  403. ///
  404. /// - returns: The created `UploadRequest`.
  405. @discardableResult
  406. open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
  407. do {
  408. let urlRequest = try urlRequest.asURLRequest()
  409. return upload(.file(fileURL, urlRequest))
  410. } catch {
  411. return upload(nil, failedWith: error)
  412. }
  413. }
  414. // MARK: Data
  415. /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`.
  416. ///
  417. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  418. ///
  419. /// - parameter data: The data to upload.
  420. /// - parameter url: The URL.
  421. /// - parameter method: The HTTP method. `.post` by default.
  422. /// - parameter headers: The HTTP headers. `nil` by default.
  423. ///
  424. /// - returns: The created `UploadRequest`.
  425. @discardableResult
  426. open func upload(
  427. _ data: Data,
  428. to url: URLConvertible,
  429. method: HTTPMethod = .post,
  430. headers: HTTPHeaders? = nil)
  431. -> UploadRequest
  432. {
  433. do {
  434. let urlRequest = try URLRequest(url: url, method: method, headers: headers)
  435. return upload(data, with: urlRequest)
  436. } catch {
  437. return upload(nil, failedWith: error)
  438. }
  439. }
  440. /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
  441. ///
  442. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  443. ///
  444. /// - parameter data: The data to upload.
  445. /// - parameter urlRequest: The URL request.
  446. ///
  447. /// - returns: The created `UploadRequest`.
  448. @discardableResult
  449. open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
  450. do {
  451. let urlRequest = try urlRequest.asURLRequest()
  452. return upload(.data(data, urlRequest))
  453. } catch {
  454. return upload(nil, failedWith: error)
  455. }
  456. }
  457. // MARK: InputStream
  458. /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`.
  459. ///
  460. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  461. ///
  462. /// - parameter stream: The stream to upload.
  463. /// - parameter url: The URL.
  464. /// - parameter method: The HTTP method. `.post` by default.
  465. /// - parameter headers: The HTTP headers. `nil` by default.
  466. ///
  467. /// - returns: The created `UploadRequest`.
  468. @discardableResult
  469. open func upload(
  470. _ stream: InputStream,
  471. to url: URLConvertible,
  472. method: HTTPMethod = .post,
  473. headers: HTTPHeaders? = nil)
  474. -> UploadRequest
  475. {
  476. do {
  477. let urlRequest = try URLRequest(url: url, method: method, headers: headers)
  478. return upload(stream, with: urlRequest)
  479. } catch {
  480. return upload(nil, failedWith: error)
  481. }
  482. }
  483. /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
  484. ///
  485. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  486. ///
  487. /// - parameter stream: The stream to upload.
  488. /// - parameter urlRequest: The URL request.
  489. ///
  490. /// - returns: The created `UploadRequest`.
  491. @discardableResult
  492. open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
  493. do {
  494. let urlRequest = try urlRequest.asURLRequest()
  495. return upload(.stream(stream, urlRequest))
  496. } catch {
  497. return upload(nil, failedWith: error)
  498. }
  499. }
  500. // MARK: MultipartFormData
  501. /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
  502. /// `UploadRequest` using the `url`, `method` and `headers`.
  503. ///
  504. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  505. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  506. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  507. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  508. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  509. /// used for larger payloads such as video content.
  510. ///
  511. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  512. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  513. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  514. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  515. /// technique was used.
  516. ///
  517. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  518. ///
  519. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  520. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  521. /// `multipartFormDataEncodingMemoryThreshold` by default.
  522. /// - parameter url: The URL.
  523. /// - parameter method: The HTTP method. `.post` by default.
  524. /// - parameter headers: The HTTP headers. `nil` by default.
  525. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  526. open func upload(
  527. multipartFormData: @escaping (MultipartFormData) -> Void,
  528. usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  529. to url: URLConvertible,
  530. method: HTTPMethod = .post,
  531. headers: HTTPHeaders? = nil,
  532. encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
  533. {
  534. do {
  535. let urlRequest = try URLRequest(url: url, method: method, headers: headers)
  536. return upload(
  537. multipartFormData: multipartFormData,
  538. usingThreshold: encodingMemoryThreshold,
  539. with: urlRequest,
  540. encodingCompletion: encodingCompletion
  541. )
  542. } catch {
  543. DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
  544. }
  545. }
  546. /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
  547. /// `UploadRequest` using the `urlRequest`.
  548. ///
  549. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  550. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  551. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  552. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  553. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  554. /// used for larger payloads such as video content.
  555. ///
  556. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  557. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  558. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  559. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  560. /// technique was used.
  561. ///
  562. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  563. ///
  564. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  565. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  566. /// `multipartFormDataEncodingMemoryThreshold` by default.
  567. /// - parameter urlRequest: The URL request.
  568. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  569. open func upload(
  570. multipartFormData: @escaping (MultipartFormData) -> Void,
  571. usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  572. with urlRequest: URLRequestConvertible,
  573. encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
  574. {
  575. DispatchQueue.global(qos: .utility).async {
  576. let formData = MultipartFormData()
  577. multipartFormData(formData)
  578. var tempFileURL: URL?
  579. do {
  580. var urlRequestWithContentType = try urlRequest.asURLRequest()
  581. urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
  582. let isBackgroundSession = self.session.configuration.identifier != nil
  583. if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
  584. let data = try formData.encode()
  585. let encodingResult = MultipartFormDataEncodingResult.success(
  586. request: self.upload(data, with: urlRequestWithContentType),
  587. streamingFromDisk: false,
  588. streamFileURL: nil
  589. )
  590. DispatchQueue.main.async { encodingCompletion?(encodingResult) }
  591. } else {
  592. let fileManager = FileManager.default
  593. let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
  594. let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
  595. let fileName = UUID().uuidString
  596. let fileURL = directoryURL.appendingPathComponent(fileName)
  597. tempFileURL = fileURL
  598. var directoryError: Error?
  599. // Create directory inside serial queue to ensure two threads don't do this in parallel
  600. self.queue.sync {
  601. do {
  602. try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
  603. } catch {
  604. directoryError = error
  605. }
  606. }
  607. if let directoryError = directoryError { throw directoryError }
  608. try formData.writeEncodedData(to: fileURL)
  609. let upload = self.upload(fileURL, with: urlRequestWithContentType)
  610. // Cleanup the temp file once the upload is complete
  611. upload.delegate.queue.addOperation {
  612. do {
  613. try FileManager.default.removeItem(at: fileURL)
  614. } catch {
  615. // No-op
  616. }
  617. }
  618. DispatchQueue.main.async {
  619. let encodingResult = MultipartFormDataEncodingResult.success(
  620. request: upload,
  621. streamingFromDisk: true,
  622. streamFileURL: fileURL
  623. )
  624. encodingCompletion?(encodingResult)
  625. }
  626. }
  627. } catch {
  628. // Cleanup the temp file in the event that the multipart form data encoding failed
  629. if let tempFileURL = tempFileURL {
  630. do {
  631. try FileManager.default.removeItem(at: tempFileURL)
  632. } catch {
  633. // No-op
  634. }
  635. }
  636. DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
  637. }
  638. }
  639. }
  640. // MARK: Private - Upload Implementation
  641. private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
  642. do {
  643. let task = try uploadable.task(session: session, adapter: adapter, queue: queue)
  644. let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task))
  645. if case let .stream(inputStream, _) = uploadable {
  646. upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
  647. }
  648. delegate[task] = upload
  649. if startRequestsImmediately { upload.resume() }
  650. return upload
  651. } catch {
  652. return upload(uploadable, failedWith: error)
  653. }
  654. }
  655. private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest {
  656. var uploadTask: Request.RequestTask = .upload(nil, nil)
  657. if let uploadable = uploadable {
  658. uploadTask = .upload(uploadable, nil)
  659. }
  660. let underlyingError = error.underlyingAdaptError ?? error
  661. let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError)
  662. if let retrier = retrier, error is AdaptError {
  663. allowRetrier(retrier, toRetry: upload, with: underlyingError)
  664. } else {
  665. if startRequestsImmediately { upload.resume() }
  666. }
  667. return upload
  668. }
  669. #if !os(watchOS)
  670. // MARK: - Stream Request
  671. // MARK: Hostname and Port
  672. /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
  673. ///
  674. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  675. ///
  676. /// - parameter hostName: The hostname of the server to connect to.
  677. /// - parameter port: The port of the server to connect to.
  678. ///
  679. /// - returns: The created `StreamRequest`.
  680. @discardableResult
  681. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
  682. open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
  683. return stream(.stream(hostName: hostName, port: port))
  684. }
  685. // MARK: NetService
  686. /// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
  687. ///
  688. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  689. ///
  690. /// - parameter netService: The net service used to identify the endpoint.
  691. ///
  692. /// - returns: The created `StreamRequest`.
  693. @discardableResult
  694. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
  695. open func stream(with netService: NetService) -> StreamRequest {
  696. return stream(.netService(netService))
  697. }
  698. // MARK: Private - Stream Implementation
  699. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
  700. private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
  701. do {
  702. let task = try streamable.task(session: session, adapter: adapter, queue: queue)
  703. let request = StreamRequest(session: session, requestTask: .stream(streamable, task))
  704. delegate[task] = request
  705. if startRequestsImmediately { request.resume() }
  706. return request
  707. } catch {
  708. return stream(failedWith: error)
  709. }
  710. }
  711. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
  712. private func stream(failedWith error: Error) -> StreamRequest {
  713. let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error)
  714. if startRequestsImmediately { stream.resume() }
  715. return stream
  716. }
  717. #endif
  718. // MARK: - Internal - Retry Request
  719. func retry(_ request: Request) -> Bool {
  720. guard let originalTask = request.originalTask else { return false }
  721. do {
  722. let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
  723. request.delegate.task = task // resets all task delegate data
  724. request.retryCount += 1
  725. request.startTime = CFAbsoluteTimeGetCurrent()
  726. request.endTime = nil
  727. task.resume()
  728. return true
  729. } catch {
  730. request.delegate.error = error.underlyingAdaptError ?? error
  731. return false
  732. }
  733. }
  734. private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) {
  735. DispatchQueue.utility.async { [weak self] in
  736. guard let strongSelf = self else { return }
  737. retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in
  738. guard let strongSelf = self else { return }
  739. guard shouldRetry else {
  740. if strongSelf.startRequestsImmediately { request.resume() }
  741. return
  742. }
  743. let retrySucceeded = strongSelf.retry(request)
  744. if retrySucceeded, let task = request.task {
  745. strongSelf.delegate[task] = request
  746. } else {
  747. if strongSelf.startRequestsImmediately { request.resume() }
  748. }
  749. }
  750. }
  751. }
  752. }