Search code examples
swiftmacosurl-encoding

Swift 3.1 macos: Cant convert String to URL, Umlaute-Encoding


I read a lot about converting and encoding now, tho im struggling to make things work: I want to convert a String containing Umlaute (such as ü,ä,ö) to URL, to execute removeItem(at: URL). Working perfectly fine without Umlaute.

pfadraus = "/Users/mdoe/Downloads/Test3 üKopie" 
let uhk = "file://\(pfadraus.replacingOccurrences(of: " ", with: "%20"))"
let uhk2 = URL(string: uhk)!

Always returns nil, I suspect some encoding should be done, tho I struggle to set that up as well. As said, in the end

let löschen = try FileManager.default.removeItem(at: uhk2)

Solution

  • There is no need to escape any special characters if you use the dedicated method to convert a file path to an URL:

    let url = URL(fileURLWithPath: path)
    

    But note that there is a removeItem(atPath:) method as well, so you don't need a conversion to an URL just for this purpose.