首页 > 解决方案 > 我无法在文件管理器中创建目录

问题描述

错误域 = NSCocoaErrorDomain 代码 = 513 “您无权将文件 “subash” 保存在文件夹 “tmp” 中。UserInfo={NSFilePath=file:///private/var/mobile/Containers/Data/Application/902FE064-C3EC-42B5-A8F8-3D2923947067/tmp/subash, NSUnderlyingError=0x281e5c6f0 {Error Domain=NSPOSIXErrorDomain Code=1 "操作不允许"}}

do {
  var mytmppath:String=FileManager.default.temporaryDirectory.absoluteString+"subash"
  try FileManager.default.createDirectory(atPath: mytmppath, withIntermediateDirectories: true, attributes: nil)

  print( FileManager.default.subpaths(atPath: FileManager.default.temporaryDirectory.absoluteString))
} catch {
  print(error)
}

标签: iosswift

解决方案


您使用了错误的 API。

absoluteString用于远程 URL,因为 API 还将返回 URL 方案(例如http://,在这种情况下file://)。

要从文件系统 URL 获取路径,您必须使用path.

不过,强烈建议您不要将路径与+. 始终使用与 URL 相关的 API 和专用的路径操作方法。

do {
    let defaultManager = FileManager.default
    let temporarySubURL = defaultManager.temporaryDirectory.appendingPathComponent("subash")
    try defaultManager.createDirectory(at: temporarySubURL, withIntermediateDirectories: true, attributes: nil)

    print( defaultManager.subpaths(atPath: FileManager.default.temporaryDirectory.path))
} catch {
    print(error)
}

推荐阅读