2016-09-22 56 views
-1

當我嘗試運行下面的代碼片段它的作品!意外地發現零,而展開一個可選值 - 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)!) 

致命錯誤:意外發現零而展開的可選值

注:請提供所有快速回答

回答

1

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)!) 

更多的參考看到蘋果Documents

+1

什麼是'「http://192.168.0.4:3003/manager/all」'那需要轉義特殊字符?我看不出它對* this * URL字符串有什麼影響。 –

+0

NSErrorFailingURLStringKey =%20http://192.168.0.4:3003/manager/all,NSErrorFailingURLKey =%20http://192.168.0.4:3003/manager/all,NSLocalizedDescription =不支持的URL 得到這個錯誤! – Abiranjan

+0

@Abiranjan:在「http」之前你似乎有一個*空格字符*,它不屬於那裏。 –

相關問題