Check for internet connection with Swift

前端 未结 21 1821
别跟我提以往
别跟我提以往 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:08

    Apple has introduced Network Framework in iOS12.

    import Foundation
    import Network
    
    class NetworkReachability {
    
       var pathMonitor: NWPathMonitor!
       var path: NWPath?
       lazy var pathUpdateHandler: ((NWPath) -> Void) = { path in
        self.path = path
        if path.status == NWPath.Status.satisfied {
            print("Connected")
        } else if path.status == NWPath.Status.unsatisfied {
            print("unsatisfied")
        } else if path.status == NWPath.Status.requiresConnection {
            print("requiresConnection")
        } 
    }
    
    let backgroudQueue = DispatchQueue.global(qos: .background)
    
    init() {
        pathMonitor = NWPathMonitor()
        pathMonitor.pathUpdateHandler = self.pathUpdateHandler
        pathMonitor.start(queue: backgroudQueue)
       } 
    
     func isNetworkAvailable() -> Bool {
            if let path = self.path {
               if path.status == NWPath.Status.satisfied {
                return true
              }
            }
           return false
       }
     }
    

提交回复
热议问题