1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
|
import UIKit
class NSURLSessionDownloadViewController: UIViewController,NSURLSessionDownloadDelegate { @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var image: UIImageView! let imageStringURL = "http://carolinehjq.com/images/avatar.jpg" var task: NSURLSessionDownloadTask? = nil var partialData: NSData? = nil let fileManager = NSFileManager.defaultManager() var session: NSURLSession! var request: NSURLRequest! override func viewDidLoad() { super.viewDidLoad() self.session = getSession() self.request = getRequest(imageStringURL) self.progressBar.progress = 0 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func getSession() -> NSURLSession { let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil) return session } return a request by url of image - parameter imageStringURL: imageStringURL - returns: NSURLRequest */ func getRequest(imageStringURL: String) -> NSURLRequest { let url = NSURL(string: imageStringURL) return NSURLRequest(URL: url!) } @IBAction func start(sender: UIButton) { self.task = self.session.downloadTaskWithRequest(self.request) self.task?.resume() } @IBAction func pause(sender: UIButton) { print("pause download task") if self.task != nil { self.task?.cancelByProducingResumeData({ (resumeData: NSData?) -> Void in self.partialData = resumeData self.task = nil }) } } @IBAction func resume(sender: UIButton) { print("resume download task") if self.task == nil { if self.partialData != nil { self.task = self.session.downloadTaskWithResumeData(self.partialData!) } else { self.task = self.session.downloadTaskWithRequest(self.request) } } self.task?.resume() } 创建文件本地保存目录 - parameter location: download location url - returns: NSURL */ func createDirectoryForDownloadItemFromURL(location: NSURL!) -> NSURL{ let documentURL: NSURL = (fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask))[0] return documentURL.URLByAppendingPathComponent(location.lastPathComponent!) } 把文件拷贝到指定路径 - parameter location: original location - parameter destination: destinate location - returns: success is true, else false */ func copyTempFileAtURL(fromLocation location: NSURL, toDestination destination: NSURL) -> Bool { do { try fileManager.copyItemAtURL(location, toURL: destination) } catch { print("file copy error") return false } return true } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { let destination = createDirectoryForDownloadItemFromURL(location) print("download success for url: \(destination)") if copyTempFileAtURL(fromLocation: location, toDestination: destination) { dispatch_async(dispatch_get_main_queue(), { () -> Void in let image1 = UIImage(contentsOfFile: destination.path!) self.image.image = image1 self.image.contentMode = .ScaleAspectFill self.image.hidden = false }) } else { print("copy file error") } self.task = nil } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let currentProgress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) print("下载了\(currentProgress)") dispatch_async(dispatch_get_main_queue()) { () -> Void in self.progressBar.progress = Float(currentProgress) self.progressBar.hidden = false } } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { print("resume...") }
}
|