Download.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Download.swift
  2. //
  3. // Copyright (c) 2014–2016 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. extension Manager {
  24. private enum Downloadable {
  25. case Request(NSURLRequest)
  26. case ResumeData(NSData)
  27. }
  28. private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
  29. var downloadTask: NSURLSessionDownloadTask!
  30. switch downloadable {
  31. case .Request(let request):
  32. dispatch_sync(queue) {
  33. downloadTask = self.session.downloadTaskWithRequest(request)
  34. }
  35. case .ResumeData(let resumeData):
  36. dispatch_sync(queue) {
  37. downloadTask = self.session.downloadTaskWithResumeData(resumeData)
  38. }
  39. }
  40. let request = Request(session: session, task: downloadTask)
  41. if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
  42. downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
  43. return destination(URL, downloadTask.response as! NSHTTPURLResponse)
  44. }
  45. }
  46. delegate[request.delegate.task] = request.delegate
  47. if startRequestsImmediately {
  48. request.resume()
  49. }
  50. return request
  51. }
  52. // MARK: Request
  53. /**
  54. Creates a download request for the specified method, URL string, parameters, parameter encoding, headers
  55. and destination.
  56. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  57. - parameter method: The HTTP method.
  58. - parameter URLString: The URL string.
  59. - parameter parameters: The parameters. `nil` by default.
  60. - parameter encoding: The parameter encoding. `.URL` by default.
  61. - parameter headers: The HTTP headers. `nil` by default.
  62. - parameter destination: The closure used to determine the destination of the downloaded file.
  63. - returns: The created download request.
  64. */
  65. public func download(
  66. method: Method,
  67. _ URLString: URLStringConvertible,
  68. parameters: [String: AnyObject]? = nil,
  69. encoding: ParameterEncoding = .URL,
  70. headers: [String: String]? = nil,
  71. destination: Request.DownloadFileDestination)
  72. -> Request
  73. {
  74. let mutableURLRequest = URLRequest(method, URLString, headers: headers)
  75. let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
  76. return download(encodedURLRequest, destination: destination)
  77. }
  78. /**
  79. Creates a request for downloading from the specified URL request.
  80. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  81. - parameter URLRequest: The URL request
  82. - parameter destination: The closure used to determine the destination of the downloaded file.
  83. - returns: The created download request.
  84. */
  85. public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
  86. return download(.Request(URLRequest.URLRequest), destination: destination)
  87. }
  88. // MARK: Resume Data
  89. /**
  90. Creates a request for downloading from the resume data produced from a previous request cancellation.
  91. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  92. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
  93. when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
  94. additional information.
  95. - parameter destination: The closure used to determine the destination of the downloaded file.
  96. - returns: The created download request.
  97. */
  98. public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
  99. return download(.ResumeData(resumeData), destination: destination)
  100. }
  101. }
  102. // MARK: -
  103. extension Request {
  104. /**
  105. A closure executed once a request has successfully completed in order to determine where to move the temporary
  106. file written to during the download process. The closure takes two arguments: the temporary file URL and the URL
  107. response, and returns a single argument: the file URL where the temporary file should be moved.
  108. */
  109. public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
  110. /**
  111. Creates a download file destination closure which uses the default file manager to move the temporary file to a
  112. file URL in the first available directory with the specified search path directory and search path domain mask.
  113. - parameter directory: The search path directory. `.DocumentDirectory` by default.
  114. - parameter domain: The search path domain mask. `.UserDomainMask` by default.
  115. - returns: A download file destination closure.
  116. */
  117. public class func suggestedDownloadDestination(
  118. directory directory: NSSearchPathDirectory = .DocumentDirectory,
  119. domain: NSSearchPathDomainMask = .UserDomainMask)
  120. -> DownloadFileDestination
  121. {
  122. return { temporaryURL, response -> NSURL in
  123. let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)
  124. if !directoryURLs.isEmpty {
  125. return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!)
  126. }
  127. return temporaryURL
  128. }
  129. }
  130. /// The resume data of the underlying download task if available after a failure.
  131. public var resumeData: NSData? {
  132. var data: NSData?
  133. if let delegate = delegate as? DownloadTaskDelegate {
  134. data = delegate.resumeData
  135. }
  136. return data
  137. }
  138. // MARK: - DownloadTaskDelegate
  139. class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
  140. var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
  141. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  142. var resumeData: NSData?
  143. override var data: NSData? { return resumeData }
  144. // MARK: - NSURLSessionDownloadDelegate
  145. // MARK: Override Closures
  146. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
  147. var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
  148. var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
  149. // MARK: Delegate Methods
  150. func URLSession(
  151. session: NSURLSession,
  152. downloadTask: NSURLSessionDownloadTask,
  153. didFinishDownloadingToURL location: NSURL)
  154. {
  155. if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
  156. do {
  157. let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
  158. try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination)
  159. } catch {
  160. self.error = error as NSError
  161. }
  162. }
  163. }
  164. func URLSession(
  165. session: NSURLSession,
  166. downloadTask: NSURLSessionDownloadTask,
  167. didWriteData bytesWritten: Int64,
  168. totalBytesWritten: Int64,
  169. totalBytesExpectedToWrite: Int64)
  170. {
  171. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  172. if let downloadTaskDidWriteData = downloadTaskDidWriteData {
  173. downloadTaskDidWriteData(
  174. session,
  175. downloadTask,
  176. bytesWritten,
  177. totalBytesWritten,
  178. totalBytesExpectedToWrite
  179. )
  180. } else {
  181. progress.totalUnitCount = totalBytesExpectedToWrite
  182. progress.completedUnitCount = totalBytesWritten
  183. downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  184. }
  185. }
  186. func URLSession(
  187. session: NSURLSession,
  188. downloadTask: NSURLSessionDownloadTask,
  189. didResumeAtOffset fileOffset: Int64,
  190. expectedTotalBytes: Int64)
  191. {
  192. if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
  193. downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
  194. } else {
  195. progress.totalUnitCount = expectedTotalBytes
  196. progress.completedUnitCount = fileOffset
  197. }
  198. }
  199. }
  200. }