實(shí)時檢測網(wǎng)絡(luò)變化
思路分析:
- 需要一個監(jiān)聽者
- 需要開始監(jiān)聽
- 需要有狀態(tài)變化的回調(diào)
- 需要停止監(jiān)聽
1. 創(chuàng)建監(jiān)聽者
Alamofire 提供了一個 NetworkReachabilityManager 網(wǎng)絡(luò)能力管理者
let net = NetworkReachabilityManager()
2. 需要開始監(jiān)聽
net?.startListening();
3. 監(jiān)聽回調(diào)
這個根據(jù)自己的業(yè)務(wù)需求進(jìn)行處理 比如彈窗什么的,如果是全局監(jiān)聽砚哗,這些代碼都應(yīng)該放到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("通過移動網(wǎng)絡(luò)鏈接")
}
} else {
print("網(wǎng)絡(luò)不可用")
}
}
4. 需要停止監(jiān)聽
在合適的位置停止監(jiān)聽
deinit {
net?.stopListening()
}
網(wǎng)絡(luò)請求前判斷網(wǎng)絡(luò)
思路分析:網(wǎng)絡(luò)請求前怔揩,先判斷網(wǎng)絡(luò)狀態(tài),然后再進(jìn)行請求
- 網(wǎng)絡(luò)狀態(tài)判斷
NetworkReachabilityManager 有個屬性 叫isReachable 就是用來做這個事的
剛才已經(jīng)拿到了這么一個對象 用上文中的net
if net?.isReachable ?? false {
}else{
let hub = MBProgressHUD.showAdded(to: view, animated: true);
hub.label.text = "網(wǎng)絡(luò)不可用";
hub.removeFromSuperViewOnHide = true;
hub.hide(animated: true, afterDelay: 1);
return;
}
- 邏輯處理
可以繼續(xù)寫琼稻,也可以在if后寫吮螺,雖然看起來有些亂,但是邏輯清晰
if net?.isReachable ?? false{
if net?.isReachableOnWWAN ?? false {
let alertCtr = UIAlertController(title: "當(dāng)前正在使用移動網(wǎng)絡(luò)", 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 = "網(wǎng)絡(luò)不可用";
hub.removeFromSuperViewOnHide = true;
hub.hide(animated: true, afterDelay: 1);
return;
}