NSURL在解开Optional值时发现nil

Gui*_*nda 7 nsurl nsurlrequest swift

任何人都知道我为什么会这样

致命错误:在展开Optional值时意外发现nil

当我使用

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

Zel*_* B. 15

|字符不是有效的URL字符,因此您必须将其替换为百分比转义字符.编码整个字符串将自动为您执行此操作

var stringUrl = "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907"

let URL = NSURL(string: stringUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用`stringByAddingPercentEscapesUsingEncoding`.使用`stringUrl .stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())` (3认同)

Álv*_*ero 8

斯威夫特 4

我正在尝试:

https://api.url.com/method?token=abcdfghijklmopqrst&command=>SSSXP10<&otherParam=12345678
Run Code Online (Sandbox Code Playgroud)

' > ' 和 ' < ' 字符给了我错误。

对于解决方案:

let objectUrl = URL(string:url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
Run Code Online (Sandbox Code Playgroud)