簡體   English   中英

如何在Swift中對NSProgress進行鍵值觀察

[英]How to do Key-Value Observing for NSProgress in Swift

我目前正在使用owncloud iOS SDK將文件上傳到我的私有雲。 我正在嘗試將此示例中提供的Key-Value觀察機制引入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)
        }  
    }
}

我在觀察方法中設置了斷點但不幸的是它從未被調用過。 誰能告訴我如何解決這個問題?

請參閱此代碼以了解進度.. !!

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)

        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM