当我想加载网址时,它会一直进入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")
}
答案 0 :(得分:2)
URLHostAllowedCharacterSet()返回主机URL子组件中允许的字符的字符集。
例如,在网址http://www.example.com/index.html中,主机组件是www.example.com。
尝试更改
let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
到
let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())