我正在尝试使用新的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]任务<663D6D3A-48B8-49E6-9103-AA1D89513D84>。<1>完成,错误为[-999]错误域= NSURLErrorDomain代码= -999“已取消” UserInfo = {NSErrorFailingURLStringKey = https://api.openweathermap.org/data/2.5/weather?lon=-122.4&APPID=29ecd35ff6b9e63498cb8fb479ba6ca0&units=imperial&lat=37.8,NSLocalizedDescription =已取消,NSErrorFailingURLKey = https://api.openweathermap.org/data/2.5/weather?lon=-122.4&APPID=29ecd35ff6b9e63498cb8fb479ba6ca0&units=imperial&lat=37.8}
答案 0 :(得分:2)
添加了.receive(on :)运算符,从而解决了该问题!
static func performNetworkRequestUsingCombine(url urlWithQuery:URL){
//let decoder = JSONDecoder()
let publisher = URLSession.shared.dataTaskPublisher(for: urlWithQuery)
.map({$0.data})
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { (completionError) in
switch completionError {
case .failure(let error):
print(error.localizedDescription)
case .finished:
break
}
}) { (data) in
guard let stringData = String(data: data, encoding: .utf8) else {return}
print(stringData)
}
publisher.cancel()
}
答案 1 :(得分:-1)
只是停止取消您的订户人。删除publisher.cancel()
。这是什么问题?