How to convert NSURL to String in Swift

萝らか妹 提交于 2019-12-20 10:19:02

问题


How do you convert an NSURL to a String in Swift?

The following:

var directoryURL: NSURL
var urlString: String = nsurlObject as String

Throws the error:

Cannot convert value of type 'NSURL' to type 'String' in coercion


回答1:


It turns out there are properties of NSURL you can access (see Swift Reference):

var directoryURL: NSURL
var urlString: String = directoryURL.absoluteString
// OR
var urlString: String = directoryURL.relativeString
// OR
var urlString: String = directoryURL.relativePath
// OR
var urlString: String = directoryURL.path
// etc.



回答2:


In Swift 3 & 4,

To convert URL to String, you can use:

String(contentsOf: URL)

and to convert String to URL:

URL(string: String)


来源:https://stackoverflow.com/questions/33510541/how-to-convert-nsurl-to-string-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!