0

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.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
FamousMaxy
  • 686
  • 5
  • 21

2 Answers2

2

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

Max Chuquimia
  • 7,494
  • 2
  • 40
  • 59
  • That solved my problem bro. And I don't know that there is something like that what will easy my work. Thanks. – FamousMaxy May 26 '16 at 06:43
  • No worries @FamousMaxy - if you command-click on `URLQueryAllowedCharacterSet` in Xcode you will see some other options for encoding different parts of a URL – Max Chuquimia May 26 '16 at 06:48
1

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

max_tx
  • 26
  • 2