Swift監聽網路的變化
阿新 • • 發佈:2018-12-15
使用Alamofire的網路管理監聽網路
1.程式啟動後,若無網則提示,來網後提示,網路變化提示併發出通知
2.程式啟動後,若有網則不提示,網路變化提示併發出通知
import UIKit import Alamofire enum NetworkingStatus { case mobile case wifi case none var description: String { switch self { case .mobile: return "Connected cellular mobile network".localized case .wifi: return "Connected WIFI".localized case .none: return "Network not connected".localized } } } class NetworkingManager { static var showTips = false static var oldStatus: NetworkingStatus = .none static var status: NetworkingStatus = .none class func startListenNetwork() { let manager = NetworkReachabilityManager() manager?.listener = { status in self.oldStatus = self.status switch status { case .unknown: self.status = .none case .notReachable: self.status = .none case .reachable: if manager?.isReachableOnWWAN ?? false { self.status = .mobile } else if manager?.isReachableOnEthernetOrWiFi ?? false { self.status = .wifi } } if showTips { Toast.showMessage(message: self.status.description) if oldStatus == .none, self.status == .mobile || self.status == .wifi { NotificationCenter.default.post(name: NotificationNames.getNetworking, object: nil) } if oldStatus == .mobile || oldStatus == .wifi, self.status == .none { NotificationCenter.default.post(name: NotificationNames.loseNetworking, object: nil) } } else { showTips = true } print("networing == ", self.status.description) } manager?.startListening() _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: { _ in if status == .none { showTips = true Toast.showMessage(message: self.status.description) } }) } }
使用:
NetworkingManager.startListenNetwork()