简体   繁体   English

如何在 NSURL 字符串中包含花括号?

[英]How do I include curly braces in NSURL string?

I have the following code, but NSURL does not like the curly braces.我有以下代码,但 NSURL 不喜欢花括号。 It crashes.它崩溃了。 If I put an @ symbol before the string after "format:" it does nothing.如果我在 "format:" 之后的字符串前面放一个 @ 符号,它什么都不做。 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!
}

I realize there's another similar thread, but it does not translate to this situation, for one thing this is Swift, not Objective-C.我意识到还有另一个类似的线程,但它并没有转化为这种情况,一方面这是 Swift,而不是 Objective-C。

Escape everything once it's constructed:一旦它被构建,就逃脱一切:

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
}

Usage:用法:

if let res = getUrlWithUpdateText("some text #%$") {
    print(res)
} else {
    // oops, something went wrong with the URL
}

As the braces are in a URL, you may be able to handle this by treating the braces as an HTML entity.由于大括号位于 URL 中,您可以通过将大括号视为 HTML 实体来处理此问题。 See How do I decode HTML entities in swift?请参阅如何快速解码 HTML 实体? for more information.想要查询更多的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM