Converting URL to String and back again
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
There is a nicer way of getting the string version of the path from the NSURL in Swift:
let path:String = url.path
In Swift 5, 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)