Reputation: 15986
I know that this is the method that I want, with the didFinishDownloadingToURL
, however, I am a newbie at swift and it is not clear how to call this method. Can you show me an example? Thank you.
class DownloadDelegate : NSObject, NSURLSessionDownloadDelegate {
func URLSession(session: NSURLSession,
downloadTask:NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL) {
println("YO")
}
}
Upvotes: 1
Views: 63
Reputation: 24714
A simple example
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
}
}
Then how to use it
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()
}
}
Upvotes: 2