版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25639809/article/details/84984587
使用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()