展开可选值时意外发现 nil - NSMutableURLRequest

Unexpectedly found nil while unwrapping an Optional value - NSMutableURLRequest

当我尝试 运行 下面的代码片段时,它起作用了!

    let urlWithParams = "http://192.168.0.4:3003/manager/all"
    let request = NSMutableURLRequest(URL: NSURL(string: urlWithParams)!)

但是当我从 Settings.bundle 文本字段中获取字符串时,以下代码不起作用:

    let webServer:String = NSUserDefaults().stringForKey("priceWeb")!
    serverResponse.appendContentsOf(webServer)
    serverResponse.appendContentsOf("/manager/all")
    let request = NSMutableURLRequest(URL: NSURL(string: serverResponse)!)

当我执行

print(webServer);

输出是http://192.168.0.4:3003,当我执行

print(serverResponse); 

输出为http://192.168.0.4:3003/manager/all

但是错误仍然出现在下面一行:

let request = NSMutableURLRequest(URL: NSURL(string: serverResponse)!)

致命错误:在展开可选值时意外发现 nil

注意:请提供swift

中的所有答案

You must encode your url as it contains special characters.

试试这个

let urlWithParams = "http://192.168.0.4:3003/manager/all"
let urlStr  = urlWithParams.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!  // or use let urlStr = urlWithParams.stringByAddingPercentEncodingWithAllowedCharacters(.URLQ‌​ueryAllowedCharacter‌​Set())
let request = NSMutableURLRequest(URL: NSURL(string: urlStr)!)

有关更多参考,请参阅 Apple Documents