IOS使用 KVO 方式更新上传进度条
KVO 的基本使用请看这里
使用 AFNetworking 网络框架的 uploadTaskWithRequest:request 函数进行文件上传操作,以下是进一步封装,添加对progress的监听。
fromFile:progress:completionHandler:
NSProgress *progress = nil;
[HTTPHelper uploadAsFile:dstPath
fromFile:srcPath
progress:&progress
success:^(File *theFile) {
} error:^(NSError *error) {
}];
// observer change of progress value
[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
实现观察者方法,当progress对象的fractionCompleted属性值发生变化时回调此方法,在主线程中更新 UI
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *,id> *)change
context:(void *)context {
NSProgress *progress = nil;
if ([object isKindOfClass:[NSProgress class]]) {
progress = (NSProgress *)object;
}
if (progress) {
dispatch_async(dispatch_get_main_queue(), ^{
// 在主线程中更新 UI
self.progressHUD.progress = progress.fractionCompleted;
});
}
}
本文介绍如何在iOS开发中利用KVO(Key-Value Observing)监控文件上传进度,并通过NSProgress更新UI进度条,确保用户能实时了解上传状态。

6802

被折叠的 条评论
为什么被折叠?



