-1

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

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Abiranjan
  • 507
  • 4
  • 18

1 Answers1

1

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

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • 1
    What are the special characters in `"http://192.168.0.4:3003/manager/all"` that need to be escaped? I cannot see that it makes any difference to *this* URL string. – Martin R Sep 22 '16 at 11:57
  • NSErrorFailingURLStringKey=%20http://192.168.0.4:3003/manager/all, NSErrorFailingURLKey=%20http://192.168.0.4:3003/manager/all, NSLocalizedDescription=unsupported URL got this error ! – Abiranjan Sep 22 '16 at 12:02
  • @Abiranjan: You seem to have a *space character* before "http", which does not belong there. – Martin R Sep 22 '16 at 12:05
  • @MartinR oops yeah!! thank you that resolved the problem. It was just a spacing mistake. – Abiranjan Sep 22 '16 at 12:27
  • also thanks to Anbu - this code stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) helped show the space. – Abiranjan Sep 22 '16 at 12:27