swift 2中的错误URL

时间:2015-12-09 22:54:49

标签: swift swift2 nsurl

当我想加载网址时,它会一直进入catch区块。我怎么解决这个问题?我认为它与逃脱的网址有关。

如果我在if区块中设置了网址,则会立即转到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")
        }

1 个答案:

答案 0 :(得分:2)

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

例如,在网址http://www.example.com/index.html中,主机组件是www.example.com。

尝试更改

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

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