类作为结构的委托占位符

时间:2016-04-27 07:56:18

标签: swift

我有一个简单的结构,我使用NSURLSession从Web获取数据。我想扩展它以提供下载进度。我不能使用struct作为NSURLSession委托,因为它需要是一个NSObject,所以我创建了一个简单的类,我传递给NSURLSession委托。这是我的代码的简短版本:

struct Resource {

    private var progressDelegate: ProgressSessionDelegate?
    private var session: NSURLSession!

    init() {

        self.progressDelegate = ProgressSessionDelegate()
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        session = NSURLSession(configuration: configuration, delegate: self.progressDelegate!, delegateQueue: nil)
    }

    func loadAsynchronous(callback: A? -> ()) {
        session.dataTaskWithURL(resourceURL) {
            data, response, error in
            let json = data.flatMap {
                try? NSJSONSerialization.JSONObjectWithData($0, options: NSJSONReadingOptions())
            }
            callback(mycalback)
            }.resume()
    }
}

那就是我应该处理委托方法的cass:

class ProgressSessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {

    var expectedContentLength = 0
    var currentLength = 0

    override init() {
        super.init()
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

        expectedContentLength = Int(response.expectedContentLength)
        print("0: \(expectedContentLength)")
        completionHandler(NSURLSessionResponseDisposition.Allow)
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {

        self.currentLength += data.length
        let percentageDownloaded = Float(self.currentLength) / Float(self.expectedContentLength)
        print("1: \(percentageDownloaded)")
    }
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        print("Downloaded")
    }
}

问题是没有调用委托方法。

当我将代码从Resource和ProgressSessionDelegate结构移动到我的ViewController并将ViewController设置为NSURLSession委托时,一切正常。我认为问题在于如何存储类是struct。

任何帮助都将非常感激。

0 个答案:

没有答案