Download.swift 9.3 KB

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