写入iCloud的文件可被列出但提示不存在的问题排查
问题根源及修复方案
核心错误
你在调用FileManager.default.fileExists(atPath:)时,传入的是url.absoluteString——这是带file://前缀的完整URL字符串,但fileExists(atPath:)要求的是本地文件系统的纯路径字符串(不带协议前缀)。这直接导致系统无法匹配到正确的文件路径,所以始终返回文件不存在。
修复步骤
- 修正存在性检测参数:把
url.absoluteString替换为url.path,或者更推荐使用fileExists(at:isDirectory:)直接传入URL,彻底避免路径字符串转换的问题。 - 优化iCloud文件处理:iCloud文件可能处于占位符状态,你已经调用了
startDownloadingUbiquitousItem(at:),但要注意下载是异步操作,若需立即检测存在性,可结合URLSession或通知监听下载完成事件。 - 消除冗余代码:Write按钮内重复定义了
containerUrl计算属性,直接复用顶部的全局定义即可。 - 完善错误捕获:
try? string.write(to:)会忽略写入错误,建议用do-catch捕获异常,方便排查写入失败的情况。
关键修复代码片段
修正getFiles方法中的存在性检测
for url in directoryContents { // 方法1:用path替代absoluteString let found = FileManager.default.fileExists(atPath: url.path) ? ",Found" : ",Not Found" // 更推荐的方法2:直接传入URL(无需路径转换) // let isDir = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1) // let found = FileManager.default.fileExists(at: url, isDirectory: isDir) ? ",Found" : ",Not Found" // isDir.deallocate() print(url.localizedName ?? url.lastPathComponent) fileNames.append((url.localizedName ?? url.lastPathComponent) + found) try filemanager.startDownloadingUbiquitousItem(at: url) }
优化Write按钮代码(消除冗余+完善错误处理)
Button("Write") { guard let url = containerUrl else { print("No such luck") return } if !FileManager.default.fileExists(atPath: url.path, isDirectory: nil) { do { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } catch { print(error.localizedDescription) } } let docURL = url.appendingPathComponent("Text \(Date())").appendingPathExtension("txt") let string = "Mary had a little lamb" do { try string.write(to: docURL, atomically: true, encoding: .utf8) fileNames = getFiles(documentDirectory: url) } catch { print("文件写入失败:\(error.localizedDescription)") } }
内容的提问来源于stack exchange,提问作者Russ
相关产品推荐
相关产品推荐

