gpt4 book ai didi

Swift 联合处理 HTTP 状态码错误

转载 作者:行者123 更新时间:2023-12-04 17:29:39 24 4
gpt4 key购买 nike

我正在阅读这篇文章:https://www.raywenderlich.com/4161005-mvvm-with-combine-tutorial-for-ios关于如何使用 combine 的 Ray Wenderlich。他们有一个示例,它从 API 获取数据但不处理 HTTP 状态代码。我想添加它,但到目前为止我还做不到。

根据这个答案,您可以添加一个 tryMap,但随后 XCode 开始显示如下错误:无法推断通用参数“T”

代码下方:

extension WeatherFetcher: WeatherFetchable {
func weeklyWeatherForecast(
forCity city: String
) -> AnyPublisher<WeeklyForecastResponse, WeatherError> {
return forecast(with: makeWeeklyForecastComponents(withCity: city))
}

private func forecast<T>(
with components: URLComponents
) -> AnyPublisher<T, WeatherError> where T: Decodable {
guard let url = components.url else {
let error = WeatherError.network(description: "Couldn't create URL")
return Fail(error: error).eraseToAnyPublisher()
}
return session.dataTaskPublisher(for: URLRequest(url: url))
.mapError { error in
.network(description: error.localizedDescription)
}
.flatMap(maxPublishers: .max(1)) { pair in
decode(pair.data)
}
.eraseToAnyPublisher()
}
}

我想添加

.tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse,
200..<300 ~= httpResponse.statusCode else {
switch (response as! HTTPURLResponse).statusCode {
case (400...499):
throw ServiceErrors.internalError((response as! HTTPURLResponse).statusCode)
default:
throw ServiceErrors.serverError((response as! HTTPURLResponse).statusCode)
}
}
return data
}

最佳答案

我认为您可以简单地将 flatMap block 替换为 tryMap。而不是从 tryMap 返回数据,它应该解码为 T。所以 return data 行应该是 return try JSONDecoder().decode(T.self, from : 数据)

private func forecast<T>(with components: URLComponents) -> AnyPublisher<T, WeatherError> where T: Decodable {
guard let url = components.url else {
let error = WeatherError.network(description: "Couldn't create URL")
return Fail(error: error).eraseToAnyPublisher()
}
return session.dataTaskPublisher(for: URLRequest(url: url))
.tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse,
200..<300 ~= httpResponse.statusCode else {
switch (response as! HTTPURLResponse).statusCode {
case (400...499):
throw ServiceErrors.internalError((response as! HTTPURLResponse).statusCode)
default:
throw ServiceErrors.serverError((response as! HTTPURLResponse).statusCode)
}
}
return try JSONDecoder().decode(T.self, from: data)
}
.mapError { error in
WeatherError() // some kind of error
}
.eraseToAnyPublisher()

关于Swift 联合处理 HTTP 状态码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60953183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com