FamousMaxy FamousMaxy - 6 months ago 13
Swift Question

Swift Weird Strings

I am trying to use

NSURL
with string in this way:

var name = "Unknown Name"
let SearchString = "http://xxx?name=\(name)"
let SearchURL = NSURL(string: SearchString)


However,
SearchURL
become nil and throws an exception because there is a space between "Unknown" and "Name"

I Want to Add single quotes in the beginning and end of
name
variable but I can't because I did the following:

let SearchString = "http://xxx?name='\(name)'"


And when I track SearchString in the debugger I found it contains the following:

http://xxx?name=\'Unknown Name\'


and it throws the exception again.

How to remove these weird backslashes and use the single quotes only so I can use the
URL
.

Answer

Sounds like you need to encode the space in name. You can do this (and encode other special characters) by using stringByAddingPercentEncodingWithAllowedCharacters with the URLQueryAllowedCharacterSet

var name = "Unknown Name".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
...


Note the unsafeness of the ! - if stringByAddingPercentEncodingWithAllowedCharacters returns nil there will be a crash