How to detect if the internet connection is over WiFi or Ethernet?

前端 未结 3 1368
旧时难觅i
旧时难觅i 2021-02-09 00:50

Is there a way to open network settings programmatically? Closest thing I know is opening the main settings page:

let settingsURL = NSURL(string: UIApplicationOp         


        
3条回答
  •  旧时难觅i
    2021-02-09 01:21

    For iOS 12.0+, tvOS 12.0+, macOS 10.14+ and watchOS 5.0+ apps you can use NWPathMonitor to solve the problem that you described in your question. Add this code to your application(_:didFinishLaunchingWithOptions:) implementation (Swift 5.1.3/Xcode 11.3.1):

    let pathMonitor = NWPathMonitor()
    pathMonitor.pathUpdateHandler = { path in
        if path.status == .satisfied {
            if path.usesInterfaceType(.wifi) {
                print("wifi")
            } else if path.usesInterfaceType(.cellular) {
                print("cellular")
            } else if path.usesInterfaceType(.wiredEthernet) {
                print("wiredEthernet")
            } else if path.usesInterfaceType(.loopback) {
                print("loopback")
            } else if path.usesInterfaceType(.other) {
                print("other")
            }
        } else {
            print("not connected")
        }
    }
    pathMonitor.start(queue: .global(qos: .background))
    

    And don't forget to add import Network to the top of the file.

提交回复
热议问题