【发布时间】:2021-09-23 07:06:42
【问题描述】:
我目前有一个 NetworkManager 类,它利用 Alamofire 并处理网络请求。此外,我有一个 MonitorManager 类,它返回互联网连接状态。所以我想做一个通用的实现,每个请求都应该建立互联网连接,否则会出现错误弹出。我怎样才能获得这个?
【问题讨论】:
我目前有一个 NetworkManager 类,它利用 Alamofire 并处理网络请求。此外,我有一个 MonitorManager 类,它返回互联网连接状态。所以我想做一个通用的实现,每个请求都应该建立互联网连接,否则会出现错误弹出。我怎样才能获得这个?
【问题讨论】:
这不是使用NWPathMonitor 的推荐方式。 Apple 建议您像平常一样发出网络请求,如果它们因特定连接错误而失败,请使用路径监视器等待连接返回,然后重新发出请求。不幸的是,Alamofire 没有开箱即用的功能,因此您需要自己集成两者。幸运的是,Alamofire 的RequestRetrier 提供了一个合适的钩子。你可以这样做:
struct PathAwaitingRetrier: RequestRetrier {
// Take a reference to your path monitor.
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
// Check error to see if it's a connectivity error.
// If so, add an observer to the path monitor which will
// call completion(.retry) when connectivity is restored.
// If not, call completion(.doNotRetry).
}
}
【讨论】: