swiftnsurl

Converting URL to String and back again


So I have converted an NSURL to a String. So if I println it looks like file:///Users/... etc.

Later I want this back as an NSURL so I try and convert it back as seen below, but I lose two of the forward slashes that appear in the string version above, that in turn breaks the code as the url is invalid.

Why is my conversion back to NSURL removing two forward slashes from the String I give it, and how can I convert back to the NSURL containing three forward slashes?

var urlstring: String = recordingsDictionaryArray[selectedRow]["path"] as String
println("the url string = \(urlstring)")
// looks like file:///Users/........etc
var url = NSURL.fileURLWithPath(urlstring)
println("the url = \(url!)")
// looks like file:/Users/......etc

Solution

  • fileURLWithPath() is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString is a full URL string including the scheme, so you should use

    let url = NSURL(string: urlstring)
    

    to convert it back to NSURL. Example:

    let urlstring = "file:///Users/Me/Desktop/Doc.txt"
    let url = NSURL(string: urlstring)
    println("the url = \(url!)")
    // the url = file:///Users/Me/Desktop/Doc.txt