stringByRemovingPercentEncoding resulting in null string

261 Views Asked by At

I've got a file path /Users/alexandra/Downloads/folder%20with%20spaces/ and I want to remove the percent encoding and make it a file URL. Using the method stringByRemovingPercentEncoding makes the string null.

The documentation says "A new string with the percent-encoded sequences removed, or nil if the receiver contains an invalid percent-encoding sequence.", but I don't see %20 for a space being wrong?

1

There are 1 best solutions below

1
matt On BEST ANSWER

You didn't show us your non-working code in Objective-C, but this works fine on my machine (in Swift):

if let path = "/Users/alexandra/Downloads/folder%20with%20spaces/".removingPercentEncoding {
    let url = URL(fileURLWithPath: path)
    print(url) // file:///Users/alexandra/Downloads/folder%20with%20spaces/
}

On the other hand, since you've already wrongly acquired percent encoding in a string pathname, why not just stick file:// in front of it and be done with it?

let path = "/Users/alexandra/Downloads/folder%20with%20spaces/"
if let url = URL(string: "file://" + path) {
    print(url)
}