Converting URL to String and back again

Solution 1:

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)

Solution 2:

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

Solution 3:

There is a nicer way of getting the string version of the path from the NSURL in Swift:

let path:String = url.path

Solution 4:

NOTICE: pay attention to the url, it's optional and it can be nil. You can wrap your url in the quote to convert it to a string. You can test it in the playground.
Update for Swift 5, Xcode 11:

import Foundation

let urlString = "http://ifconfig.me"
// string to url
let url = URL(string: urlString)
//url to string
let string = "\(url)"
// if you want the path without `file` schema
// let string = url.path

Solution 5:

2020 | SWIFT 5.1:

From STRING to URL:

//ver 1 - better to use it for http/https
//BUT DO NOT use for local paths
let url = URL(string:"https://stackoverflow.com/")

//ver 2 -- for local paths
let url = URL(fileURLWithPath: "//Users/Me/Desktop/Doc.txt")

//ver 3 -- for local folders
let url = URL(fileURLWithPath: "//Users/Me/Desktop", isDirectory: true)

From URL to STRING:

let a = String(describing: url)       // "file:////Users/Me/Desktop/Doc.txt"
let b = "\(url)"                      // "file:////Users/Me/Desktop/Doc.txt"
let c = url.absoluteString            // "file:////Users/Me/Desktop/Doc.txt"
let d = url.path                      // "/Users/Me/Desktop/Doc.txt" 

BUT value of d will be invisible due to debug process, so...

THE BEST SOLUTION for local files is:

let e = "\(url.path)"                 // "/Users/Me/Desktop/Doc.txt"

The best solution for network adresses is:

let c = url.absoluteString

.path will return only /questions/27062454/converting-url-to-string-and-back-again for http(s) url https://stackoverflow.com/questions/27062454/converting-url-to-string-and-back-again so for http(s) urls better to use url.absoluteString