I am attempting to parse JSON using the new Combine framework. However, every attempt I make comes back with a cancelled error. When I use the exact same url without combine it works fine.
The bottom function works fine, the top one gives me an error no matter what I do.
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()
}
}
I expect to receive my JSON data printed in the terminal but instead I receive the following error:
2019-10-25 14:59:34.452071-0400 Clima[2127:98883] Task <663D6D3A-48B8-49E6-9103-AA1D89513D84>.<1> finished with error [-999] Error Domain=NSURLErrorDomain Code=-999 "cancelled" 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 }
Added.receive(on:) operator and this resolved the issue!
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()
}
Just stop cancelling your subscriber man. Remove publisher.cancel()
. What kind of question is that?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.