保存至documentDirectory遇权限错误,如何获取iOS真机写入权限?
问题原因与解决方案
你的问题并非Documents目录缺少写入权限,而是路径构造错误导致的权限报错。
核心错误点
代码中使用了appendingPathExtension("LikedDepartments")来拼接路径:
let savePath = FileManager.documentsDirectory.appendingPathExtension("LikedDepartments")
这个方法的作用是给当前URL添加文件扩展名,而非在目录下创建子文件。原本的Documents目录URL是类似/var/mobile/Containers/Data/Application/.../Documents,调用该方法后会变成/var/mobile/Containers/Data/Application/.../Documents.LikedDepartments——这相当于尝试修改系统默认的Documents文件夹本身,自然会触发权限拦截。
而.cachesDirectory只是因路径结构或系统权限策略的细微差异暂时绕过了错误,但本质上这也是不正确的路径构造方式。
修复方案
将appendingPathExtension替换为appendingPathComponent,这个方法用于在当前目录下添加子文件/目录路径:
修改后的路径代码:
let savePath = FileManager.documentsDirectory.appendingPathComponent("LikedDepartments")
完整修复后的保存逻辑:
// 正确构造文件路径 let savePath = FileManager.documentsDirectory.appendingPathComponent("LikedDepartments") func save() { let favourites = calculateFavourites() do { let data = try JSONEncoder().encode(favourites) try data.write(to: savePath, options: [.atomic, .completeFileProtection]) } catch { print("\(error)") } }
补充说明
iOS中,App的Documents目录默认拥有完全的读写权限,无需额外在Info.plist中配置权限。只要路径构造正确,就能正常写入文件。
内容的提问来源于stack exchange,提问作者James Gifford
相关产品推荐
相关产品推荐

