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)
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
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
2020 | SWIFT 5.1:
//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)
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) urlhttps://stackoverflow.com/questions/27062454/converting-url-to-string-and-back-again
so for http(s) urls better to useurl.absoluteString
let url = URL(string: "URLSTRING HERE")
let anyvar = String(describing: url)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With