Check for internet connection with Swift

前端 未结 21 2065
别跟我提以往
别跟我提以往 2020-11-22 05:59

When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?

The code:

import Foundation
impo         


        
21条回答
  •  我在风中等你
    2020-11-22 06:13

    With the help of below code you can check for internet Connection for both cellular network as well as for wifi. language - Swift 3.0

    import UIKit
    import Foundation
    import SystemConfiguration
    
    class NetworkConnection: UIViewController {
    
      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, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
    
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
          $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
          }
        }) else {
          return false
        }
    
        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
          return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
      }
    
      class func checkConnection(sender:UIViewController){
        if NetworkConnection.isConnectedToNetwork() == true {
          print("Connected to the internet")
          //  Do something
        } else {
          print("No internet connection")
          let alertController = UIAlertController(title: "No Internet Available", message: "", preferredStyle: UIAlertControllerStyle.alert)
          let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default){(result:UIAlertAction) -> Void in
            return
          }
          alertController.addAction(okAction)
          sender.present(alertController, animated: true, completion: nil)
          //  Do something
        }
      }
    
    }
    

提交回复
热议问题