调用URL字符串时发生致命错误,展开一个Optional值时为nil

时间:2019-04-26 20:55:11

标签: ios swift

我有以下函数,该函数使用URL字符串从URL调用JSON数据。

为什么我在展开此行上的Optional值时不断收到错误Unexpectedly nil:

let url = URL(string: "\(api)/\(key)/\(lat),\(lon)?units=\(unit)")!

以下是整个功能:

  func getForecast(forLatitude lat:Double, lon:Double, completion: @escaping(Forecast?, Error?) -> ()) {
        let unit = UserDefaults.standard.string(forKey: Defaults.units) ?? "us"
        let url = URL(string: "\(api)/\(key)/\(lat),\(lon)?units=\(unit)")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let e = error {
                print("Error fetching data: \(e.localizedDescription)")
                completion(nil, e)
                return
            }
            guard let d = data else {
                print("Error: There was no data available!")
                completion(nil, nil)
                return
            }
            //print("JSON: \(String(describing: self.json(fromData: data)))")
            do {
                let forecast = try self.decoder.decode(Forecast.self, from: d)
                completion(forecast, nil)
            } catch let err {
                print("Error converting data \(err.localizedDescription)")
                completion(nil, err)
            }
        }
        task.resume()
    }

    /// Helper method to print out the raw JSON when necessary
    /// USED FOR DEBUGGING ONLY
    private func json(fromData data:Data?) -> [String:Any]? {
        if let d = data {
            do {
                let serial = try JSONSerialization.jsonObject(with: d, options: []) as? [String:Any]
                return serial
            } catch let e as NSError {
                print(e.localizedDescription)
            }
        }
        return nil
    }
}

0 个答案:

没有答案