【问题标题】:How to use NWPathMonitor with Alamofire?如何将 NWPathMonitor 与 Alamofire 一起使用?
【发布时间】:2021-09-23 07:06:42
【问题描述】:

我目前有一个 NetworkManager 类,它利用 Alamofire 并处理网络请求。此外,我有一个 MonitorManager 类,它返回互联网连接状态。所以我想做一个通用的实现,每个请求都应该建立互联网连接,否则会出现错误弹出。我怎样才能获得这个?

【问题讨论】:

    标签: swift alamofire


    【解决方案1】:

    这不是使用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).
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-12
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      相关资源
      最近更新 更多