IOS Alamofire判断手机是否有网络

2019-07-08 12:59:55 浏览数 (1)

代码语言:javascript复制
 1 import UIKit
 2 import Alamofire
 3
 4 class MyNetworkReachabilityManager {
 5
 6 private static let sharedInstance =
 MyNetworkReachabilityManager()
 7 var manager =
 NetworkReachabilityManager(host:“www.baidu.com”)
 8
 9 init(){
 10 manager?.listener = { status in
 11 print(“Network Status Changed:(status)”)
 12 }
 13 manager?.startListening()
 14 }
 15 class var sharedManager:
 MyNetworkReachabilityManager {
 16
 17 let instance = self.sharedInstance
 18 return instance
 19 }
 20
 21 func networkReachabilityStatus() ->
 Alamofire.NetworkReachabilityManager.NetworkReachabilityStatus
 {
 22 let status:
 Alamofire.NetworkReachabilityManager.NetworkReachabilityStatus
 = (manager?.networkReachabilityStatus)!
 23 print(“当前网络状态:(status)”)
 24 return status
 25 }
 26}
 27 import UIKit
 28 import Alamofire
 29
 30 class ViewController:UIViewController {
 31 override func viewDidLoad() {
 32 super.viewDidLoad()
 33 // Do any additional setup after loading the view,
 typically from a nib.
 34 }
 35
 36 @IBAction func
 touchupInsideCheckBtnAction(sender:UIButton) {
 37 var message = “当前无网络”
 38 let status:
 NetworkReachabilityManager.NetworkReachabilityStatus =
 MyNetworkReachabilityManager.sharedManager.networkReachabilityStatus()
 39
 40 switch status {
 41 case .notReachable:
 42 message = “当前无网络”
 43 print(“当前无网络”)
 44 break
 45 case
 .reachable(NetworkReachabilityManager.ConnectionType.ethernetOrWiFi):
 46 message = “是WIFI网络”
 47 print(“是WIFI网络”)
 48 break
 49 case
 .reachable(NetworkReachabilityManager.ConnectionType.
 wwan):
 50 message = “是3G或4G网络”
 51 print(“是3G或4G网络”)
 52 break
 53
 54 default:
 55 message = “当前无网络”
 56 break
 57 }
 58
 59 let alert = UIAlertController(title:“Information”,
 message:message, preferredStyle:
 UIAlertControllerStyle.alert)
 60 let OKAction = UIAlertAction(title:“OK”, style:
 UIAlertActionStyle.default, handler:nil)
 61 alert.addAction(OKAction)
 62 self.presentViewController(alert, animated:true,
 completion:nil)
 63 }
 64 }

0 人点赞