How do I include curly braces in NSURL string?

2019-02-27 01:41发布

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!
}

I realize there's another similar thread, but it does not translate to this situation, for one thing this is Swift, not Objective-C.

标签: ios swift url
2条回答
beautiful°
2楼-- · 2019-02-27 02:26

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
}
查看更多
爷的心禁止访问
3楼-- · 2019-02-27 02:38

As the braces are in a URL, you may be able to handle this by treating the braces as an HTML entity. See How do I decode HTML entities in swift? for more information.

查看更多
登录 后发表回答