首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Swift中对NSProgress进行键值观测

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

Stack Overflow用户
提问于 2016-05-03 07:20:21
回答 1查看 2.8K关注 0票数 4

我目前正在使用owncloud iOS SDK将一个文件上传到我的私有云。我试着把关键值观察机制在本例中提供带到Swift。

库强制我在upload方法中传递指向NSProgress对象的指针。然后,我想做一个键值,观察并相应更新我的UI。

代码语言:javascript
复制
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)
        }  
    }
}

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

EN

回答 1

Stack Overflow用户

发布于 2016-05-03 07:38:13

看到这段代码是为了进步..!!

代码语言:javascript
复制
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)

        }

    }
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36998041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档