swift 中的错误 URL 2

Bad URL in swift 2

当我想加载一个 url 时,它总是进入 catch 块。我该如何解决这个问题?我认为这是转义的 url.

如果我在 if 块中设置 url,它会立即转到 else 块。

let urls : String = Baseurl+"lat="+latitude+"&lon="+longitude+"&APPID={"+apiKey+"}"
let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url: NSURL = NSURL(string: escapedurl!)!


        if let url = NSURL(string: escapedurl!) {
            do {
                let contents = try NSString(contentsOfURL: url, usedEncoding: nil)
                print(contents)
            } catch {
                // contents could not be loaded
                print("bad")
            }
        } else {
            // the URL was bad!
            print("bads")
        }

URLHostAllowedCharacterSet() returns 主机 URL 子组件中允许的字符集。

例如,在URLhttp://www.example.com/index.html中,宿主组件是www.example.com。

尝试改变

let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

进入

let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())