Converting URL to String and back again

Gary Simpson picture Gary Simpson · Nov 21, 2014 · Viewed 213.3k times · Source

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

Answer

Naishta picture Naishta · Oct 11, 2016

In Swift 4 and Swift 3, To convert String to URL:

URL(string: String)

or,

URL.init(string: "yourURLString")

And to convert URL to String:

URL.absoluteString

The one below converts the 'contents' of the url to string

String(contentsOf: URL)