12

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")!
Guilherme Miranda
  • 1,052
  • 2
  • 10
  • 19

3 Answers3

17

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)!)!
Zell B.
  • 10,266
  • 3
  • 40
  • 49
  • 4
    `stringByAddingPercentEscapesUsingEncoding` is deprecated. Use `stringUrl .stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())` – aytek Jun 30 '16 at 11:47
  • @ayteq I'm trying to use this as well... but it seems it just doesn't want to append – user805981 Jul 08 '16 at 20:32
  • @user805981 Very strange! When you copy the code from my comment, it includes a special character which is not seen in Xcode. So please use auto-complete option in Xcode. Please see the problem [here](https://jsfiddle.net/fxvnyocz/) I can't edit my comment, sorry about that. – aytek Jul 11 '16 at 22:29
  • @zell B . I want to implement snap to roads Can u guide how to achieve this? – Uma Madhavi Apr 01 '17 at 06:22
12

Swift 4

I was trying with :

https://api.url.com/method?token=abcdfghijklmopqrst&command=>SSSXP10<&otherParam=12345678

And the '>' and '<' characters was giving me the error.

For the solution :

let objectUrl = URL(string:url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
Álvaro Agüero
  • 4,494
  • 1
  • 42
  • 39
0

Oh, It's a crazy issue. Because of < and > it was giving an error

let username = searchTextFileld.text!
let urlString: String = "https://api.github.com/search/users?q=\(username)+repos:>100+followers:>100"
Sreekanth G
  • 658
  • 6
  • 13