微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我想知道使用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)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。