FamousMaxy
FamousMaxy

Reputation: 686

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.

Upvotes: 0

Views: 150

Answers (2)

max_tx
max_tx

Reputation: 26

Starting from iOS 7 there is a method stringByAddingPercentEncodingWithAllowedCharacters in NSString class. That method returns a new string made from the receiver by replacing all characters not in the specified set with percent encoded characters.

var originalString = "Unknown Name"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
println("escapedString: \(escapedString)")

URLQueryAllowedCharacterSet contains all allowed characters for URL query string.

Output:

Unknown%20Name

So changing the code to

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

should do the trick

Upvotes: 1

Max Chuquimia
Max Chuquimia

Reputation: 7844

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

Upvotes: 2

Related Questions