【发布时间】:2016-02-09 13:05:21
【问题描述】:
我是 Swift 和 iOS 开发的新手,所以请原谅我使用的任何/所有陈述和术语...
我正在创建一个新的 Downloader 对象(仅用于下载 PDF 文件),我需要在 ViewController 中调用一个方法,该方法会显示文件已成功下载的消息。除了我在做一些非常愚蠢的事情而且似乎无法让它发挥作用。
我在 this question 上使用 Ahmet Akkök 的答案,当我尝试使用 yourOwnObject.showDownloadCompleted() 时找不到方法。
任何和所有的帮助将不胜感激!
ViewController 中的代码:
override func viewDidLoad(){
super.viewDidLoad();
let pdfURL = "exampleToPFD.com/mypdf.pdf";
let url = NSURL(string: pdfURL);
let d = Downloader(yourOwnObject: self);
d.download(url!);
}
func showDownloadComplete(){
print("done");
}
The Downloader.swift 中的代码:
import Foundation
class Downloader : NSObject, NSURLSessionDownloadDelegate{
var url : NSURL?
// will be used to do whatever is needed once download is complete
var yourOwnObject : NSObject?
var downloaded = false;
var documentDestination = "";
init(yourOwnObject : NSObject){
self.yourOwnObject = yourOwnObject
}
//is called once the download is complete
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
//copy downloaded data to your documents directory with same names as source file
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
let destinationUrl = documentsUrl!.URLByAppendingPathComponent(url!.lastPathComponent!)
let dataFromURL = NSData(contentsOfURL: location)
dataFromURL!.writeToURL(destinationUrl, atomically: true)
//now it is time to do what is needed to be done after the download
print("download done...");
// call to the parent method here
documentDestination = destinationUrl.absoluteString;
print("DestURL" + (destinationUrl.absoluteString));
}
//method to be called to download
func download(url: NSURL){
self.url = url
//download identifier can be customized. I used the "ulr.absoluteString"
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(url.absoluteString)
let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTaskWithURL(url);
task.resume();
}
}
【问题讨论】:
-
请仅发布与您的问题相关的代码