fatal error: unexpectedly found nil while unwrapping an Optional value

0

I have the following function to call a URL that is in a REST from Swift 2, but when I send values with space in the NSURL I get the following error:

  

fatal error: unexpectedly found nil while unwrapping an Optional value

class func getApi(urlWithArgs: String?) -> NSMutableURLRequest {
    let url: NSURL = NSURL(string: urlWithArgs!)!
    let resquest = NSMutableURLRequest(URL: url)

    return resquest
}

What am I wrong with for this error to appear only when I send values with a space? Example, I send a name: "pepito perez". Why does sending "pepitoperez" work?

Thanks

    
asked by Andres Guillermo Castellanos A 09.06.2016 в 18:16
source

1 answer

0

The problem is that URLs with a space are not valid, and NSURL(string: urlWithArgs!) is returning nil .

If your URL has spaces (or other characters that are not valid in a URL), you should also "escape" the String .

The correct way to implement this function would be:

class func getApi(urlWithArgs: String?) -> NSMutableURLRequest? {
    guard urlWithArgs != nil else {
        return nil
    }

    var request: NSMutableURLRequest? = nil
    if let escapedStr = urlWithArgs!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) {
        if let url = NSURL(string: escapedStr) {
            request = NSMutableURLRequest(URL: url)
        }
    }

    return request
}
    
answered by 09.06.2016 / 18:58
source