NSURL found nil while unwraping an Optional value

孤街醉人 提交于 2019-12-17 20:45:15

问题


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

回答1:


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



回答2:


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



回答3:


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"


来源:https://stackoverflow.com/questions/28882954/nsurl-found-nil-while-unwraping-an-optional-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!