感谢您的帮助。我在我的文档目录中创建了一个名为“MyPhotos”的文件夹。我在文件夹中添加了三个图像文件。没有问题。 接下来,我试图构建一些代码,在需要时删除文件,但无法正确执行。我可以将 MyPhotos 文件夹附加到搜索路径,但在多次尝试后无法随后将文件名附加到路径。 tempPhotoTitle 是一个变量。感谢您的帮助。
let fileManager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
let destinationPath = documentsPath.appendingPathComponent("MyPhotos")
let finalPath = destinationPath.appending(tempPhotoTitle)
do {
try fileManager.removeItem(atPath: finalPath)
}
catch {
print(error)
}
答案 0 :(得分:1)
问题在于您正在使用字符串(路径)而不是添加斜杠。我建议始终以这种方式处理 URL,您无需担心在路径中添加斜杠。
do {
let tempPhotoTitle = "filename.jpg"
let documents = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let photos = documents.appendingPathComponent("MyPhotos")
let fileURL = photos.appendingPathComponent(tempPhotoTitle)
try FileManager.default.removeItem(at: fileURL)
} catch {
print(error)
}
答案 1 :(得分:1)
Leo Dabus 使用 URL 的答案是更好的答案。但是,值得一提的是,在使用 String
时,如果您再次桥接到 NSString
,则 appendingPathComponent
可用:
let finalPath = (destinationPath as NSString).appendingPathComponent(tempPhotoTitle)