在给出 space 我得到 'unexpectedly found nil while unwrapping an Optional value'

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

当我传入我的网络服务时,我的 NSURL 对象中有 3 个参数。 当我在我的一个参数中传递 'space' 时,我得到 'unexpectedly found nil while unwrapping an Optional value'。

下面的代码

     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....

如果我没有在参数中给出 space,那么它工作正常...

有人可以帮我解决上述问题吗?

谢谢,

文档说:

Return Value: An NSURL object initialized with URLString. If the URL string was malformed, returns nil. Discussion

This method expects URLString to contain only characters that are allowed in a properly formed URL. All other characters must be properly percent escaped. Any percent-escaped characters are interpreted using UTF-8 encoding.

所以如果你将一个空格传递给 NSURL,它会产生 nil,因为它是一个格式错误的字符串。

您必须使用 .stringByAddingPercentEscapesUsingEncoding

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