一尘不染

iOS9 Swift文件使用NSURL创建NSFileManager.createDirectoryAtPath

swift

在iOS9之前,我们已经创建了一个目录,如下所示

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let logsPath = documentsPath.stringByAppendingPathComponent("logs")
let errorPointer = NSErrorPointer()
NSFileManager.defaultManager().createDirectoryAtPath(logsPath, withIntermediateDirectories: true, attributes: nil, error: errorPointer)

但是在iOS9中,他们删除了String.stringByAppendingPathComponent。自动转换工具将我们对String的使用替换为NSURL。createDirectoryAtPath()需要一个字符串,因此我需要将NSURL转换为字符串。我们像这样使用absolutePath
:(针对iOS9的更新)

let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let logsPath = documentsPath.URLByAppendingPathComponent("logs")
do {
    try NSFileManager.defaultManager().createDirectoryAtPath(logsPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
    NSLog("Unable to create directory \(error.debugDescription)")
}

但是我收到以下错误:

无法创建目录错误域= NSCocoaErrorDomain代码= 513“您无权将文件“日志”保存在“文档”文件夹中。UserInfo =
{NSFilePath = file:/// var / mobile / Containers / Data / Application /
F2EF2D4F-94AF-4BF2-AF9E-D0ECBC8637E7 / Documents / logs /,NSUnderlyingError
= 0x15664d070 {Error Domain = NSPOSIXErrorDomain Code = 1“不允许的操作“}}


阅读 284

收藏
2020-07-07

共1个答案

一尘不染

我想通了。createDirectoryAtPath()无法处理带有“
file://”前缀的路径。要获取不带前缀的路径,必须使用path()或relativePath()。

let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let logsPath = documentsPath.URLByAppendingPathComponent("logs")
do {
    try NSFileManager.defaultManager().createDirectoryAtPath(logsPath.path!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
    NSLog("Unable to create directory \(error.debugDescription)")
}

路径不正确(注意文件://):

文件:/// var / mobile / Containers / Data / Application /
F2EF2D4F-94AF-4BF2-AF9E-D0ECBC8637E7 / Documents / logs /

正确的路径:

/ var / mobile /容器/数据/应用程序/ F2EF2D4F-94AF-4BF2-AF9E-D0ECBC8637E7 / Documents /
logs /

2020-07-07