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

Ios 在展开可选值-NSMutableURLRequest时意外发现nil,ios,swift,optional,nsmutableurlrequest,Ios,Swift,Optional,Nsmutableurlrequest,当我试着运行下面的代码片段时,它是有效的 let urlWithParams = "http://192.168.0.4:3003/manager/all" let request = NSMutableURLRequest(URL: NSURL(string: urlWithParams)!) 但是当我从Settings.bundle Textfield获取字符串时,以下代码不起作用: let webServer:String = NSUserDefaults().s

当我试着运行下面的代码片段时,它是有效的

    let urlWithParams = "http://192.168.0.4:3003/manager/all"
    let request = NSMutableURLRequest(URL: NSURL(string: urlWithParams)!)
但是当我从Settings.bundle Textfield获取字符串时,以下代码不起作用:

    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提供所有答案

您必须对url进行编码,因为它包含特殊字符

试试这个

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

中的特殊字符是什么http://192.168.0.4:3003/manager/all“哪些需要转义?我看不出这对URL字符串有任何影响。NSErrorFailingURLStringKey=%20http://192.168.0.4:3003/manager/all,NSErrorFailingURLKey=%20http://192.168.0.4:3003/manager/all,NSLocalizedDescription=不受支持的URL收到此错误@阿比兰扬:你似乎在“http”之前有一个空格字符,它不属于那里。@MartinR oops是的!!谢谢你解决了这个问题。这只是一个间距错误。也要感谢Anbu-此代码stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)帮助显示空间。