2
0

SessionManager.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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: [String: String] = {
  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 (com.alamofire.iOS-Example; build:1; iOS 9.3.0) Alamofire/3.4.2`
  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(OSX)
  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 a URL based on the specified `urlString`, `method`,
  178. /// `parameters`, `encoding` and `headers`.
  179. ///
  180. /// - parameter urlString: The URL string.
  181. /// - parameter method: The HTTP method. `.get` by default.
  182. /// - parameter parameters: The parameters. `nil` by default.
  183. /// - parameter encoding: The parameter encoding. `.url` by default.
  184. /// - parameter headers: The HTTP headers. `nil` by default.
  185. ///
  186. /// - returns: The created `DataRequest`.
  187. @discardableResult
  188. open func request(
  189. _ urlString: URLStringConvertible,
  190. method: HTTPMethod = .get,
  191. parameters: [String: Any]? = nil,
  192. encoding: ParameterEncoding = .url,
  193. headers: [String: String]? = nil)
  194. -> DataRequest
  195. {
  196. let urlRequest = URLRequest(urlString: urlString, method: method, headers: headers)
  197. let encodedURLRequest = encoding.encode(urlRequest, parameters: parameters).0
  198. return request(resource: encodedURLRequest)
  199. }
  200. /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
  201. ///
  202. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  203. ///
  204. /// - parameter urlRequest: The URL request.
  205. ///
  206. /// - returns: The created `DataRequest`.
  207. open func request(resource urlRequest: URLRequestConvertible) -> DataRequest {
  208. let originalRequest = urlRequest.urlRequest
  209. let originalTask = DataRequest.Requestable(urlRequest: originalRequest)
  210. let task = originalTask.task(session: session, adapter: adapter, queue: queue)
  211. let request = DataRequest(session: session, task: task, originalTask: originalTask)
  212. delegate[request.delegate.task] = request
  213. if startRequestsImmediately { request.resume() }
  214. return request
  215. }
  216. // MARK: - Download Request
  217. // MARK: URL Request
  218. /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlString`, `method`,
  219. /// `parameters`, `encoding`, `headers` and save them to the `destination`.
  220. ///
  221. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  222. /// underlying URL session.
  223. ///
  224. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  225. ///
  226. /// - parameter urlString: The URL string.
  227. /// - parameter method: The HTTP method. `.get` by default.
  228. /// - parameter parameters: The parameters. `nil` by default.
  229. /// - parameter encoding: The parameter encoding. `.url` by default.
  230. /// - parameter headers: The HTTP headers. `nil` by default.
  231. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  232. ///
  233. /// - returns: The created `DownloadRequest`.
  234. @discardableResult
  235. open func download(
  236. _ urlString: URLStringConvertible,
  237. method: HTTPMethod = .get,
  238. parameters: [String: Any]? = nil,
  239. encoding: ParameterEncoding = .url,
  240. headers: [String: String]? = nil,
  241. to destination: DownloadRequest.DownloadFileDestination? = nil)
  242. -> DownloadRequest
  243. {
  244. let urlRequest = URLRequest(urlString: urlString, method: method, headers: headers)
  245. let encodedURLRequest = encoding.encode(urlRequest, parameters: parameters).0
  246. return download(resource: encodedURLRequest, to: destination)
  247. }
  248. /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
  249. /// them to the `destination`.
  250. ///
  251. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  252. /// underlying URL session.
  253. ///
  254. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  255. ///
  256. /// - parameter urlRequest: The URL request
  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. resource urlRequest: URLRequestConvertible,
  263. to destination: DownloadRequest.DownloadFileDestination? = nil)
  264. -> DownloadRequest
  265. {
  266. return download(.request(urlRequest.urlRequest), to: destination)
  267. }
  268. // MARK: Resume Data
  269. /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
  270. /// the contents of the original request and save them to the `destination`.
  271. ///
  272. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  273. /// underlying URL session.
  274. ///
  275. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  276. ///
  277. /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
  278. /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
  279. /// additional information.
  280. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  281. ///
  282. /// - returns: The created `DownloadRequest`.
  283. @discardableResult
  284. open func download(
  285. resourceWithin resumeData: Data,
  286. to destination: DownloadRequest.DownloadFileDestination? = nil)
  287. -> DownloadRequest
  288. {
  289. return download(.resumeData(resumeData), to: destination)
  290. }
  291. // MARK: Private - Download Implementation
  292. private func download(
  293. _ downloadable: DownloadRequest.Downloadable,
  294. to destination: DownloadRequest.DownloadFileDestination?)
  295. -> DownloadRequest
  296. {
  297. let task = downloadable.task(session: session, adapter: adapter, queue: queue)
  298. let request = DownloadRequest(session: session, task: task, originalTask: downloadable)
  299. request.downloadDelegate.destination = destination
  300. delegate[request.delegate.task] = request
  301. if startRequestsImmediately { request.resume() }
  302. return request
  303. }
  304. // MARK: - Upload Request
  305. // MARK: File
  306. /// Creates an `UploadRequest` from the specified `method`, `urlString` and `headers` for uploading the `file`.
  307. ///
  308. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  309. ///
  310. /// - parameter file: The file to upload.
  311. /// - parameter urlString: The URL string.
  312. /// - parameter method: The HTTP method. `.post` by default.
  313. /// - parameter headers: The HTTP headers. `nil` by default.
  314. ///
  315. /// - returns: The created `UploadRequest`.
  316. @discardableResult
  317. open func upload(
  318. _ fileURL: URL,
  319. to urlString: URLStringConvertible,
  320. method: HTTPMethod = .post,
  321. headers: [String: String]? = nil)
  322. -> UploadRequest
  323. {
  324. let urlRequest = URLRequest(urlString: urlString, method: method, headers: headers)
  325. return upload(fileURL, with: urlRequest)
  326. }
  327. /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
  328. ///
  329. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  330. ///
  331. /// - parameter file: The file to upload.
  332. /// - parameter urlRequest: The URL request.
  333. ///
  334. /// - returns: The created `UploadRequest`.
  335. @discardableResult
  336. open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
  337. return upload(.file(fileURL, urlRequest.urlRequest))
  338. }
  339. // MARK: Data
  340. /// Creates an `UploadRequest` from the specified `method`, `urlString` and `headers` for uploading the `data`.
  341. ///
  342. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  343. ///
  344. /// - parameter data: The data to upload.
  345. /// - parameter urlString: The URL string.
  346. /// - parameter method: The HTTP method. `.post` by default.
  347. /// - parameter headers: The HTTP headers. `nil` by default.
  348. ///
  349. /// - returns: The created `UploadRequest`.
  350. @discardableResult
  351. open func upload(
  352. _ data: Data,
  353. to urlString: URLStringConvertible,
  354. method: HTTPMethod = .post,
  355. headers: [String: String]? = nil)
  356. -> UploadRequest
  357. {
  358. let urlRequest = URLRequest(urlString: urlString, method: method, headers: headers)
  359. return upload(data, with: urlRequest)
  360. }
  361. /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
  362. ///
  363. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  364. ///
  365. /// - parameter data: The data to upload.
  366. /// - parameter urlRequest: The URL request.
  367. ///
  368. /// - returns: The created `UploadRequest`.
  369. @discardableResult
  370. open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
  371. return upload(.data(data, urlRequest.urlRequest))
  372. }
  373. // MARK: InputStream
  374. /// Creates an `UploadRequest` from the specified `method`, `urlString` and `headers` for uploading the `stream`.
  375. ///
  376. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  377. ///
  378. /// - parameter stream: The stream to upload.
  379. /// - parameter urlString: The URL string.
  380. /// - parameter method: The HTTP method. `.post` by default.
  381. /// - parameter headers: The HTTP headers. `nil` by default.
  382. ///
  383. /// - returns: The created `UploadRequest`.
  384. @discardableResult
  385. open func upload(
  386. _ stream: InputStream,
  387. to urlString: URLStringConvertible,
  388. method: HTTPMethod = .post,
  389. headers: [String: String]? = nil)
  390. -> UploadRequest
  391. {
  392. let urlRequest = URLRequest(urlString: urlString, method: method, headers: headers)
  393. return upload(stream, with: urlRequest)
  394. }
  395. /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
  396. ///
  397. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  398. ///
  399. /// - parameter stream: The stream to upload.
  400. /// - parameter urlRequest: The URL request.
  401. ///
  402. /// - returns: The created `UploadRequest`.
  403. @discardableResult
  404. open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
  405. return upload(.stream(stream, urlRequest.urlRequest))
  406. }
  407. // MARK: MultipartFormData
  408. /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
  409. /// `UploadRequest` using the `method`, `urlString` and `headers`.
  410. ///
  411. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  412. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  413. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  414. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  415. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  416. /// used for larger payloads such as video content.
  417. ///
  418. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  419. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  420. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  421. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  422. /// technique was used.
  423. ///
  424. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  425. ///
  426. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  427. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  428. /// `multipartFormDataEncodingMemoryThreshold` by default.
  429. /// - parameter urlString: The URL string.
  430. /// - parameter method: The HTTP method. `.post` by default.
  431. /// - parameter headers: The HTTP headers. `nil` by default.
  432. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  433. open func upload(
  434. multipartFormData: @escaping (MultipartFormData) -> Void,
  435. usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  436. to urlString: URLStringConvertible,
  437. method: HTTPMethod = .post,
  438. headers: [String: String]? = nil,
  439. encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
  440. {
  441. let urlRequest = URLRequest(urlString: urlString, method: method, headers: headers)
  442. return upload(
  443. multipartFormData: multipartFormData,
  444. usingThreshold: encodingMemoryThreshold,
  445. with: urlRequest,
  446. encodingCompletion: encodingCompletion
  447. )
  448. }
  449. /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
  450. /// `UploadRequest` using the `urlRequest`.
  451. ///
  452. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  453. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  454. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  455. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  456. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  457. /// used for larger payloads such as video content.
  458. ///
  459. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  460. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  461. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  462. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  463. /// technique was used.
  464. ///
  465. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  466. ///
  467. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  468. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  469. /// `multipartFormDataEncodingMemoryThreshold` by default.
  470. /// - parameter urlRequest: The URL request.
  471. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  472. open func upload(
  473. multipartFormData: @escaping (MultipartFormData) -> Void,
  474. usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  475. with urlRequest: URLRequestConvertible,
  476. encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
  477. {
  478. DispatchQueue.global(qos: .utility).async {
  479. let formData = MultipartFormData()
  480. multipartFormData(formData)
  481. var urlRequestWithContentType = urlRequest.urlRequest
  482. urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
  483. let isBackgroundSession = self.session.configuration.identifier != nil
  484. if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
  485. do {
  486. let data = try formData.encode()
  487. let encodingResult = MultipartFormDataEncodingResult.success(
  488. request: self.upload(data, with: urlRequestWithContentType),
  489. streamingFromDisk: false,
  490. streamFileURL: nil
  491. )
  492. DispatchQueue.main.async { encodingCompletion?(encodingResult) }
  493. } catch {
  494. DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
  495. }
  496. } else {
  497. let fileManager = FileManager.default
  498. let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
  499. let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
  500. let fileName = UUID().uuidString
  501. let fileURL = directoryURL.appendingPathComponent(fileName)
  502. do {
  503. try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
  504. try formData.writeEncodedData(to: fileURL)
  505. DispatchQueue.main.async {
  506. let encodingResult = MultipartFormDataEncodingResult.success(
  507. request: self.upload(fileURL, with: urlRequestWithContentType),
  508. streamingFromDisk: true,
  509. streamFileURL: fileURL
  510. )
  511. encodingCompletion?(encodingResult)
  512. }
  513. } catch {
  514. DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
  515. }
  516. }
  517. }
  518. }
  519. // MARK: Private - Upload Implementation
  520. private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
  521. let task = uploadable.task(session: session, adapter: adapter, queue: queue)
  522. let request = UploadRequest(session: session, task: task, originalTask: uploadable)
  523. if case let .stream(inputStream, _) = uploadable {
  524. request.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
  525. }
  526. delegate[request.delegate.task] = request
  527. if startRequestsImmediately { request.resume() }
  528. return request
  529. }
  530. #if !os(watchOS)
  531. // MARK: - Stream Request
  532. // MARK: Hostname and Port
  533. /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
  534. ///
  535. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  536. ///
  537. /// - parameter hostName: The hostname of the server to connect to.
  538. /// - parameter port: The port of the server to connect to.
  539. ///
  540. /// - returns: The created `StreamRequest`.
  541. @discardableResult
  542. open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
  543. return stream(.stream(hostName: hostName, port: port))
  544. }
  545. // MARK: NetService
  546. /// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
  547. ///
  548. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  549. ///
  550. /// - parameter netService: The net service used to identify the endpoint.
  551. ///
  552. /// - returns: The created `StreamRequest`.
  553. @discardableResult
  554. open func stream(with netService: NetService) -> StreamRequest {
  555. return stream(.netService(netService))
  556. }
  557. // MARK: Private - Stream Implementation
  558. private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
  559. let task = streamable.task(session: session, adapter: adapter, queue: queue)
  560. let request = StreamRequest(session: session, task: task, originalTask: streamable)
  561. delegate[request.delegate.task] = request
  562. if startRequestsImmediately { request.resume() }
  563. return request
  564. }
  565. #endif
  566. // MARK: - Internal - Retry Request
  567. func retry(_ request: Request) -> Bool {
  568. guard let originalTask = request.originalTask else { return false }
  569. let task = originalTask.task(session: session, adapter: adapter, queue: queue)
  570. request.delegate.task = task // resets all task delegate data
  571. request.startTime = CFAbsoluteTimeGetCurrent()
  572. request.endTime = nil
  573. task.resume()
  574. return true
  575. }
  576. }