我试图通过restful API获取数据,但存在问题。当我尝试获取数据时,错误立即出现:
20121-08-24 17:36:44.851463+0200国家[1498:19786]任务<3FF6E673-52AD-47FE-9342-229E2CE99859>.<1>完成错误[-999]错误域=NSURLErrorDomain代码=-999 "cancelled"用户信息= {NSErrorFailingURLStringKey = https://restcountries。eu/rest/v2/all, NSLocalizedDescription=cancelled, NSErrorFailingURLKey=https://restcountries.eu/rest/v2/all}
每次都显示。知道怎么解决吗?
APIService:
final class APIService: APIServiceProtocol {
func fetchAllCountries(url: URL) -> AnyPublisher<[Country], APIError> {
let request = URLRequest(url: url)
return URLSession.DataTaskPublisher.init(request: request, session: .shared)
.tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
throw APIError.unknown
}
return data
}
.decode(type: [Country].self, decoder: JSONDecoder())
.mapError { error in
if let error = error as? APIError {
return error
} else {
return APIError.apiError(reason: error.localizedDescription)
}
}
.eraseToAnyPublisher()
}
}
ListViewModel:
import SwiftUI
import Combine
class ListViewModel: ObservableObject {
private let apiService: APIServiceProtocol
@Published var countries = [Country]()
init(apiService: APIServiceProtocol = APIService()) {
self.apiService = apiService
}
func fetchCountries() {
guard let url = URL(string: "https://restcountries.eu/rest/v2/all") else { return }
let publisher = apiService.fetchAllCountries(url: url)
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let error):
print(error.localizedDescription)
}
}, receiveValue: { data in
self.countries = data
print(data)
})
publisher.cancel()
}
}
你必须给发行商分配一个strong引用,否则它会立即取消自身。
创建属性
var cancellable : AnyCancellable?
分配cancellable = apiService.fetchAllCountries(url: url) ...
并取消finished
范围内的发布者
case .finished:
cancellable?.cancel()
但是,如果发布者是一次性发布者,则cancel
行是冗余的。当发布者发出finished
时,管道终止。