如何在NSURL字符串中包含花括号? [英] How do I include curly braces in NSURL string?
本文介绍了如何在NSURL字符串中包含花括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,但NSURL不喜欢花括号。它崩溃了。如果我在格式:后面的字符串前加一个@符号,它什么都不做。如果我尝试使用\来逃避括号,它就不起作用。如何使这项工作?
I have the following code, but NSURL does not like the curly braces. It crashes. If I put an @ symbol before the string after "format:" it does nothing. If I try to use \ to escape the braces, it doesn't work. How do I make this work?
func getUrlWithUpdateText(updateText: String!) -> NSURL {
let escapedUpdateText = updateText.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let urlString = String(format: "http://localhost:3000/api/Tests/update?where={ \"name\": %@ }", escapedUpdateText)
let url = NSURL(string: urlString)
return url!
}
我意识到还有另一个类似的线程,但它没有转化为这种情况,一方面,这是Swift,而不是Objective-C。
I realize there's another similar thread, but it does not translate to this situation, for one thing this is Swift, not Objective-C.
推荐答案
一旦构造完毕就逃脱:
func getUrlWithUpdateText(updateText: String) -> NSURL? {
let toEscape = "http://localhost:3000/api/Tests/update?where={ \"name\": \(updateText) }"
if let escapedUpdateText = toEscape.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLHostAllowedCharacterSet()),
url = NSURL(string: escapedUpdateText) {
return url
}
return nil
}
用法:
if let res = getUrlWithUpdateText("some text #%$") {
print(res)
} else {
// oops, something went wrong with the URL
}
这篇关于如何在NSURL字符串中包含花括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文