【发布时间】:2020-02-22 03:48:52
【问题描述】:
我正在尝试使用新的 Combine 框架解析 JSON。但是,我所做的每一次尝试都会返回一个取消的错误。当我使用完全相同的网址而不使用组合时,它可以正常工作。
底部的功能正常,顶部的无论我做什么都会出错。
static func performNetworkRequestUsingCombine(url urlWithQuery:URL){
//let decoder = JSONDecoder()
let publisher = URLSession.shared.dataTaskPublisher(for: urlWithQuery)
.map({$0.data})
.eraseToAnyPublisher()
.sink(receiveCompletion: { (status) in
switch status {
case .failure(let incomingError):
print(incomingError.localizedDescription)
case .finished:
break
}
}) { (data) in
let dataString = String(data: data, encoding: .utf8)
print(dataString!)
}
publisher.cancel()
}
static func performNetworkRequest(url urlWithQuery: URL, dataValue : @escaping (WeatherObject)->Void){
let decoder = JSONDecoder()
let task = URLSession.shared.dataTask(with: urlWithQuery) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
return
}
if let data = data {
do {
let weatherData = try decoder.decode(WeatherObject.self, from: data)
dataValue(weatherData)
} catch let localError {
print(localError.localizedDescription)
}
}
}
task.resume()
}
}
我希望收到打印在终端中的 JSON 数据,但我收到以下错误:
2019-10-25 14:59:34.452071-0400 Clima[2127:98883] 任务 . 完成错误 [-999] 错误域 = NSURLErrorDomain 代码 = -999 “取消” UserInfo={NSErrorFailingURLStringKey=https://api.openweathermap.org/data/2.5/weather?lon=-122.4&APPID=29ecd35ff6b9e63498cb8fb479ba6ca0&units=imperial&lat=37.8, NSLocalizedDescription=cancelled, NSErrorFailingURLKey=https://api.openweathermap.org/data/2.5/weather?lon=-122.4&APPID=29ecd35ff6b9e63498cb8fb479ba6ca0&units=imperial&lat=37.8}
【问题讨论】:
标签: ios swift xcode urlsession combine