2

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.

Nathan McKaskle
  • 2,926
  • 12
  • 55
  • 93

2 Answers2

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
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • This definitely gets me a step further as it no longer crashes. Unfortunately the API (Strongloop) doesn't like the escapes for the quotes. For some reason it's taking those literally. How come I can't use the @ symbol in front of the string to escape the whole string? – Nathan McKaskle Jun 27 '15 at 00:21
  • You would have to have a look at your API specification and check what format it wants then conform to it. Does it need also quotes around the value you insert? Or does it want the ones around the key to not be there? Etc. This is another topic anyway, your question was about escaping curly braces. – Eric Aya Jun 27 '15 at 00:28
0

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.

Community
  • 1
  • 1