1

代码示例是在 Xcode 8(β3) 中运行的 Swift 3.0。

此 Weather Underground URL(当MyKey被替换为有效键时)返回一个 JSON 字符串,其中包含给定位置的当前天气... http://api.wunderground.com/api/MyKey/conditions/q/51.3276,-1.0022 .json

下面的代码应该做同样的事情,但会引发错误(“在此服务器上找不到请求的 URL。”,底部的详细信息)。

谁能看到我在代码中遗漏了什么?

private let key = "MyKey" // Substitute a valid Weather Underground key here.

@IBAction func fetchWeather() {
    let session = URLSession.shared
    let url     = URL(fileURLWithPath: "http://api.wunderground.com/api/\(key)/conditions/q/51.3276,-1.0022.json")

    let handler = { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
        guard let data = data, let response = response, error == nil else {
            print("\nError: \(error?.description)\n")
            return
        }
        print("\nData: \(data)\n")
        print("\nResponse: \(response)\n")
    }

    let task    = session.dataTask(with: url, completionHandler: handler)
    task.resume()
}

Error: Optional("Error Domain=NSURLErrorDomain Code=-1100 \"The requested URL was not found on this server.\" UserInfo={NSUnderlyingError=0x600000442520 {Error Domain=kCFErrorDomainCFNetwork Code=-1100 \"(null)\"}, NSErrorFailingURLStringKey=file:///http:/api.wunderground.com/api/MyKey/forecast/q/51.3276,-1.0022.json, NSErrorFailingURLKey=file:///http:/api.wunderground.com/api/MyKey/forecast/q/51.3276,-1.0022.json, NSLocalizedDescription=The requested URL was not found on this server.}")

4

0 回答 0