使用ubiquitousItemDownloadingStatusKey获取iCloud文件下载状态失效
解决URLResourceValues访问iCloud下载状态属性报错的问题
问题重现
尝试用resourceValues(forKeys:)检查iCloud文件下载状态的代码如下:
if let status = try? url.resourceValues(forKeys: [URLResourceKey.ubiquitousItemDownloadingStatusKey]) { if status.ubiquitousItemDownloadingStatusKey == .current { print("File download complete.") } }
此前可正常运行,但现在Xcode提示Value of type 'URLResourceValues' has no member 'ubiquitousItemDownloadingStatusKey',且仅能从status中获取到thumbnailDictionary。
问题原因
这是一个容易忽略的小错误:URLResourceValues的属性名和对应的URLResourceKey枚举成员名不是完全一致的。你用了带Key后缀的枚举成员名去访问URLResourceValues的属性,这不符合语法规范。正确的属性名是ubiquitousItemDownloadingStatus,不带末尾的Key后缀。
旧版本Swift可能对这类命名有宽松兼容,Xcode更新后类型检查变得严格,所以现在触发了报错。你看到只有thumbnailDictionary,是因为这是URLResourceValues的默认可见属性之一,而你请求的iCloud下载状态属性因访问名称错误无法正常获取。
修正后的代码
if let status = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]) { if status.ubiquitousItemDownloadingStatus == .current { print("File download complete.") } }
内容的提问来源于stack exchange,提问作者FE_Tech
相关产品推荐
相关产品推荐

