Search code examples
iosweb-servicesswiftnsurl

While giving a space i am getting 'unexpectedly found nil while unwrapping an Optional value'


i have 3 params in my NSURL object as i am passing in my webservice. I am getting 'unexpectedly found nil while unwrapping an Optional value' while i am passing 'space' in one of my param.

Code Below

     println("viewDidLoad contact name \(contactName)")// i am giving Space here like 'James '
    // println(countryCode)
    // println(townCode)



    var resultPage=false
        let url: NSURL? = NSURL(string: "<URL>/searchContactsJSON?searchString=\(contactName)&towCode=\(townCode)&couCode=\(countryCode)") //I am getting error in this line....

If i am not giving a space in parameter than it is working fine...

Can someone please help me with above issue?

Thanks,


Solution

  • You have to use .stringByAddingPercentEscapesUsingEncoding

    "http://www.domain.com/?z=your string".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!  // "http://www.domain.com/?z=your%20string"