How do I include curly braces in NSURL string?

2019-02-27 01:58发布

问题:

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.

回答1:

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
}


回答2:

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.



标签: ios swift url