Download.swift 9.2 KB

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