如何在Swift中对NSProgress进行键值观察

时间:2016-05-03 07:20:21

标签: ios swift key-value-observing owncloud

我目前正在使用owncloud iOS SDK将文件上传到我的私有云。我正在尝试将Key-Value观察机制provided in this example带到Swift。

库强制我在upload方法中传递指向NSProgress对象的指针。然后我想做一个Key Value Observing并相应地更新我的UI。

class OwnCloudManager : NSObject {

    //Key Value observation requires the dynamic keyword
    //NSProgress must also extend from NSObject
    dynamic var progress: NSProgress = NSProgress()
    let apiURL : NSString = "https://cloud.example.com/remote.php/webdav/"
    let ocCommunication = OCCommunication()

    override init() {
      //configure ocCommunication here, set user name, password
      //and adjust ocCommunication.securityPolicy
      //...
    }
    deinit {
        //remove observer when object is destroyed
        progress.removeObserver(self, forKeyPath: "fractionCompleted")
    }

    func uploadFile(folderURL : NSURL, filename: String) -> NSURLSessionUploadTask?{

        let fileURL = apiURL.stringByAppendingPathComponent(filename)
        let progressPointer = AutoreleasingUnsafeMutablePointer<NSProgress?>.init(&progress)


        let uploadTask = ocCommunication.uploadFileSession(folderURL.path, toDestiny: fileURL, onCommunication: ocCommunication,
            withProgress: progressPointer,
            successRequest: ({(response, redirectedServer) in
                //...

            }),
            failureRequest: ({ (response, redirectedServer, error) in
                //request failed while execution
            }),
            failureBeforeRequest: ({ error in
                //failure before request is executed

            })
        )

        progress.addObserver(self, forKeyPath: "fractionCompleted", options: .New, context: nil)

        uploadTask.resume()
        return uploadTask
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        if let observedProgress = object as? NSProgress where keyPath == "fractionCompleted" {
            //call my delegate here that updates the UI
        }
        else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }  
    }
}

我在观察方法中设置了一个断点但不幸的是它从未被调用过。有人能告诉我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:7)

请参阅此代码以了解进度.. !!

override func  observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if keyPath == "fractionCompleted"{
            let progress : NSProgress = object as! NSProgress
            print(progress)

        }

    }