swift基础判断网络连接

前端之家收集整理的这篇文章主要介绍了swift基础判断网络连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


import Foundation
import SystemConfiguration

public class Reachability {
    
    class func isConnectedToNetwork() -> Bool {
        
        var zeroAddress = sockaddr_in(sin_len: 0,sin_family: 0,sin_port: 0,sin_addr: in_addr(s_addr: 0),sin_zero: (0,0))
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil,UnsafePointer($0))
        }
        
        var flags: SCNetworkReachabilityFlags = []
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!,&flags) == false {
            return false
        }
        
        let isReachable = flags.contains(.Reachable)
        let needsConnection = flags.contains(.Connectionrequired)
        
        return isReachable && !needsConnection
    }
    
}

class ViewController: UIViewController {

    @IBOutlet weak var checkingLabel: UILabel!
    
    override func viewDidAppear(animated: Bool) {
        checkConnectivity()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func checkConnectivity() {
        print(Reachability.isConnectedToNetwork(),terminator: "")
        if Reachability.isConnectedToNetwork() == false {
            let alert = UIAlertController(title: "Alert",message: "Internet is not working",preferredStyle: UIAlertControllerStyle.Alert)
            self.presentViewController(alert,animated: false,completion: nil)
            let okAction = UIAlertAction(title: "Retry",style: UIAlertActionStyle.Default) {
                UIAlertAction in
                alert.dismissViewControllerAnimated(false,completion: nil)
                //self.checkConnectivity()
            }
            alert.addAction(okAction)
            checkingLabel.text = ""
        }
        else {
            checkingLabel.text = "Connected"
        }
    }
}
没网没有网的时候回弹出警告框 原文链接:https://www.f2er.com/swift/323513.html

猜你在找的Swift相关文章