【问题标题】:Bad URL in swift 2swift 2中的错误网址
【发布时间】:2015-12-09 22:54:48
【问题描述】:

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

如果我在 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")
        }

【问题讨论】:

  • 向我们展示完整的 URL。
  • 您的catch 块可以让您了解有关错误的更多信息。现在,您忽略了提供给您的错误对象中的所有信息。请参阅 Using Swift with Cocoa and Objective-C 中的Error Handling,了解可用于检查错误并找出问题所在的模式。

标签: swift swift2 nsurl


【解决方案1】:

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

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

尝试改变

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

进入

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-14
    • 2016-04-11
    • 2016-01-07
    • 2015-12-08
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多