美文网首页Swift
Alamofire检测网络变化

Alamofire检测网络变化

作者: _我和你一样 | 来源:发表于2017-09-23 10:55 被阅读1459次

实时检测网络变化

思路分析:

  1. 需要一个监听者
  2. 需要开始监听
  3. 需要有状态变化的回调
  4. 需要停止监听
1. 创建监听者

Alamofire 提供了一个 NetworkReachabilityManager 网络能力管理者

let net = NetworkReachabilityManager()
2. 需要开始监听
net?.startListening();
3. 监听回调

这个根据自己的业务需求进行处理 比如弹窗什么的,如果是全局监听,这些代码都应该放到AppDelegate中

 net?.listener = { status in            
            if self.net?.isReachable ?? false{
                
                switch status{
                case .notReachable:
                    print("the noework is not reachable")
                case .unknown:
                    print("It is unknown whether the network is reachable")
                case .reachable(.ethernetOrWiFi):
                    print("通过WiFi链接")
                case .reachable(.wwan):
                    print("通过移动网络链接")
                }
                
            } else {
                print("网络不可用")
            }
        }
4. 需要停止监听

在合适的位置停止监听

    deinit {
        net?.stopListening()
    }

网络请求前判断网络

思路分析:网络请求前,先判断网络状态,然后再进行请求

  1. 网络状态判断
    NetworkReachabilityManager 有个属性 叫isReachable 就是用来做这个事的
    刚才已经拿到了这么一个对象 用上文中的net
if net?.isReachable ?? false {

}else{
    let hub = MBProgressHUD.showAdded(to: view, animated: true);
            hub.label.text = "网络不可用";
            hub.removeFromSuperViewOnHide = true;
            hub.hide(animated: true, afterDelay: 1);
            return;
}

  1. 逻辑处理
    可以继续写,也可以在if后写,虽然看起来有些乱,但是逻辑清晰
 if net?.isReachable ?? false{
            
            if net?.isReachableOnWWAN ?? false {
            
                let alertCtr = UIAlertController(title: "当前正在使用移动网络", message: "会消耗大量流量", preferredStyle: .alert);
                alertCtr.addAction(UIAlertAction(title: "确定上传", style: .default, handler: { (action) in
                    self.startUpload();
                }))
                
                alertCtr.addAction(UIAlertAction(title: "取消上传", style: .destructive, handler: { (action) in
                    
                    
                }))
                present(alertCtr, animated: true, completion: {
                    
                })
            } else {
                self.startUpload();
            }
            
            
        } else {
            let hub = MBProgressHUD.showAdded(to: view, animated: true);
            hub.label.text = "网络不可用";
            hub.removeFromSuperViewOnHide = true;
            hub.hide(animated: true, afterDelay: 1);
            return;
        }

相关文章

网友评论

    本文标题:Alamofire检测网络变化

    本文链接:https://www.haomeiwen.com/subject/ljqcextx.html