我有2个视图控制器。在父视图中,我有一个进度视图。在子级VC中,我使用POST请求将带有参数的图像上传到服务器,然后关闭该VC,因此在返回父级VC时,我希望进度视图在上载时进行更新。我尝试了protocol-delegate方法,但是看起来它只能工作一次并且不能动态返回值。我尝试在两个视图控制器中实现以下方法,但未成功。
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
self.progressView.hidden = false
self.uploadProgress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
print(self.uploadProgress)
self.progressView.setProgress(self.uploadProgress, animated: true)
if (uploadProgress == 1.0) {
self.progressView.hidden = true
// uploadProgress = 0.0
}
}
最佳答案
看一下KVO(键值观察)并观察您的self.uploadProgress
。每次更改self.uploadProgress
时,都会调用一个函数,然后您可以执行所需的任何操作。确保在要显示进度条的VC上添加观察者(函数)。
例如在ParentVC中:
[childVC addObserver:self forKeyPath:@"uploadProgress" options: NSKeyValueObservingOptionNew context:NULL];
接着:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"uploadProgress"]) {
NSLog(@"Updated Value:%@",[change objectForKey:NSKeyValueChangeNewKey]);
//Do something
}
}
每次uploadProgress属性更改时,都会调用observeForValue。
当您不需要观察者或将销毁ChildVC时,请不要忘记删除它。
-(void)dealloc {
[self removeObserver:parentVC forKeyPath:@"uploadProgress"];
}