NSProgress使用沙盒文件路径时进度指示器不显示问题
问题结论
这不是系统Bug,是macOS沙盒机制与NSProgress进度发布逻辑的预期行为,不需要为NSProgressFileURLKey配置额外参数,只要传入符合系统规则的文件URL即可正常工作。
原因说明
- Finder的文件图标进度条由系统独立的Finder进程渲染,该进程无权访问其他App沙盒容器内的私有路径。你提到的沙盒容器内路径
/Users/mdbraber/Library/Containers/com.mdbraber.TestApp/Data/Downloads/属于App私有目录,沙盒做的路径透明映射仅对你的App自身生效,对Finder等外部进程完全不可见,因此无法匹配到对应文件展示进度。 - 当你传入真实的用户Downloads目录路径时,Finder本身对该系统标准目录有完整访问权限,系统的进度发布服务可以正确将你发布的
NSProgress对象和Finder中对应位置的文件做关联,因此进度指示器可以正常显示。
适配方案
- 不要使用沙盒容器内的私有Downloads镜像路径操作文件,你已经配置了
com.apple.security.files.downloads.read-write权限,完全可以直接操作用户真实Downloads目录下的文件。 - 代码中不要硬编码
NSProgress相关的字符串常量,优先使用系统框架提供的全局常量,避免系统版本迭代时出现值不匹配的兼容问题。 - 拿到Downloads目录路径后建议做软链接解析,避免因系统路径映射逻辑拿到沙盒内部的私有路径。
修正后的核心代码参考:
// 获取并解析真实的用户Downloads目录路径 NSString *downloadsPath = [NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES).firstObject stringByResolvingSymlinksInPath]; _downloadedPath = [downloadsPath stringByAppendingPathComponent:fileName]; _downloadingPath = [_downloadedPath stringByAppendingString:@".download"]; NSDictionary* progressInfo = @{ NSProgressFileOperationKindKey: NSProgressFileOperationKindDownloading, NSProgressFileURLKey: [NSURL fileURLWithPath:_downloadingPath] }; self.progress = [[NSProgress alloc] initWithParent:nil userInfo:progressInfo]; self.progress.kind = NSProgressKindFile; self.progress.pausable = NO; self.progress.cancellable = YES; self.progress.totalUnitCount = _totalBytes; [self.progress publish];
内容的提问来源于stack exchange,提问作者mdbraber
相关产品推荐
相关产品推荐

