我知道这是我想要的方法,使用didFinishDownloadingToURL
,但是,我是swift的新手,并且不清楚如何调用此方法。你能告诉我一个例子吗?谢谢。
class DownloadDelegate : NSObject, NSURLSessionDownloadDelegate {
func URLSession(session: NSURLSession,
downloadTask:NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL) {
println("YO")
}
}
答案 0 :(得分:2)
一个简单的例子
class DemoDownloadClass: NSObject,NSURLSessionDelegate,NSURLSessionDownloadDelegate {
var session:NSURLSession?
var downloadUrl:String
var completion:(NSURL)->()
init(url:String,completionBlock:(location:NSURL)->()){
completion = completionBlock
downloadUrl = url
super.init()
session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
}
func start(){
let request = NSURLRequest(URL: NSURL(string: downloadUrl)!);
let downloadTask = session!.downloadTaskWithRequest(request)
downloadTask.resume()
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
completion(location)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
//here get progress
}
}
然后如何使用
class DemoTableController: UIViewController{
var test:DemoDownloadClass?
override func viewDidLoad() {
test = DemoDownloadClass(url: "yoururl", completionBlock: { (location) -> () in
//Use location to get file,I did not handle error here.Just as an exmaple
})
test?.start()
}
}