Search code examples
swiftnsurlnsurlrequest

NSURL found nil while unwraping an Optional value


Anyone knows why am I getting

fatal error: unexpectedly found nil while unwrapping an Optional value

When i use

    let URL = NSURL(string: "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907")!

Solution

  • The | character its not a valid URL character so you must replace it with percent escape character. Encoding whole string will do that automatically for you

    var stringUrl = "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907"
    
    let URL = NSURL(string: stringUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!