文件名包含不规则字符时创建文档目录文件路径

问题描述

我想知道使用Swift的FileManager下载具有不规则文件名的文件解决方法是什么。例如,下载一个名为“ Hello / Goodbye”的文件,其文件路径如下所示:

let filePath = documentDirectory.appendingPathComponent("\(fileName).m4a")

将导致文件下载到名为“ Hello”的documentDirectory内的文件夹中,因为filePath是“ documentDirectory / Hello / Goodbye.m4a”。相反,我希望在documentDirectory下以“ Hello / Goodbye.m4a”下载文件。无论如何,是否可以对这些特殊字符进行编码,以便文件路径忽略它们?

解决方法

如果需要在文件名中添加斜杠"/",则需要用冒号":"代替:

let desktopDirectory = FileManager.default.urls(for: .desktopDirectory,in: .userDomainMask).first!
let fileName = "Hello/Goodbye.txt".replacingOccurrences(of: "/",with: ":")
let file = desktopDirectory.appendingPathComponent(fileName)
do {
    try "SUCCESS".write(to: file,atomically: true,encoding: .utf8)
} catch {
    print(error)
}

extension URL {
    func appendingFileName(_ fileName: String,withExtension: String) -> URL {
        appendingPathComponent(fileName.replacingOccurrences(of: "/",with: ":")).appendingPathExtension(withExtension)
    }
}

let fileName = "Hello/Goodbye"
let pathExtension = "txt"
let file = desktopDirectory.appendingFileName(fileName,withExtension: pathExtension)
do {
    try "SUCCESS".write(to: file,encoding: .utf8)
} catch {
    print(error)
}