Search code examples
iosswiftoption-typensmutableurlrequest

Unexpectedly found nil while unwrapping an Optional value - NSMutableURLRequest


When I try to run the below code snippet it works !

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

But when I get the string from Settings.bundle Textfield the below code doesn't work :

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

When I execute

print(webServer);

the output is http://192.168.0.4:3003 and when I execute

print(serverResponse); 

the output is http://192.168.0.4:3003/manager/all

But still the error appears in the following line:

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

fatal error: unexpectedly found nil while unwrapping an Optional value

Note : Please provide all the answers in swift


Solution

  • You must encode your url as it contains special characters.

    try this

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

    for more reference see the Apple Documents