aritroper
aritroper

Reputation: 1709

Creating document directory file paths when file names include irregular characters

I am wondering what the work-around is for downloading files with irregular filenames using Swift's FileManager. For example, downloading a file named "Hello/Goodbye" where the file path looks like:

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

will result in the file downloading to a folder inside documentDirectory named 'Hello' since filePath is "documentDirectory/Hello/Goodbye.m4a". Instead, I want the file to be downloaded under documentDirectory as 'Hello/Goodbye.m4a'. Is there anyway to encode these special characters so that the file path ignores them?

Upvotes: 0

Views: 647

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236315

If you need to add a slash "/" to your filename you need to replace it by a colon ":":

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, atomically: true, encoding: .utf8)
} catch {
    print(error)
}

Upvotes: 1

Related Questions