Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何检测internet连接是否通过WiFi或以太网?_Swift_Tvos - Fatal编程技术网

Swift 如何检测internet连接是否通过WiFi或以太网?

Swift 如何检测internet连接是否通过WiFi或以太网?,swift,tvos,Swift,Tvos,有没有办法以编程方式打开网络设置?我所知道的最接近的事情是打开主设置页面: let settingsURL = NSURL(string: UIApplicationOpenSettingsURLString)! UIApplication.sharedApplication().openURL(settingsURL) 我希望能够检测internet连接是否通过WiFi或以太网。您可以使用 检测这种情况的方法是查看网络接口的名称。对于Mac和Apple TV,en0和en1分别指有线和无线接

有没有办法以编程方式打开网络设置?我所知道的最接近的事情是打开主设置页面:

let settingsURL = NSURL(string: UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(settingsURL)
我希望能够检测internet连接是否通过WiFi或以太网。

您可以使用


检测这种情况的方法是查看网络接口的名称。对于Mac和Apple TV,
en0
en1
分别指有线和无线接口

将此添加到桥接标头(或根据需要创建一个):

或:


对于iOS 12.0+、tvOS 12.0+、macOS 10.14+和watchOS 5.0+应用程序,您可以使用
NWPathMonitor
解决问题中描述的问题。将此代码添加到您的
应用程序中(uquot:didFinishLaunchingWithOptions:)
实现(Swift 5.1.3/Xcode 11.3.1):


不要忘了在文件的顶部添加
导入网络

可达性对以太网没有任何价值。它返回可通过WiFi访问的信息。我认为在这种情况下,ReachableViaWiFi应该改名为ReachableViaLAN或其他什么。我同意@saucewipe。可达性并不是检测WiFi和以太网之间的区别。在Swift中使用可达性需要导入哪些模块?您必须从苹果下载并设置可达性以供使用,或者自己编写实现(这不是非常棘手——GitHub上有很多)。我同意上面的评论——可达性不能将以太网与wlan分开,它只是告诉您是否使用wwan连接。您能提供swift 3更新吗?非安全指针部分存在一些问题
let reachability: Reachability = Reachability.reachabilityForInternetConnection()
(reachability.currentReachabilityStatus().value == ReachableViaWiFi.value) // For WiFi
(reachability.currentReachabilityStatus().value == ReachableViaWWAN.value) // For WWAN
(reachability.currentReachabilityStatus().value == NotReachable.value) // For No Internet
#include <ifaddrs.h>
#include <net/if_dl.h>
struct Networking {

    enum NetworkInterfaceType: String, CustomStringConvertible {
        case Ethernet = "en0"
        case Wifi = "en1"
        case Unknown = ""

        var description: String {
            switch self {
            case .Ethernet:
                return "Ethernet"
            case .Wifi:
                return "Wifi"
            case .Unknown:
                return "Unknown"
            }
        }
    }

    static var networkInterfaceType: NetworkInterfaceType {
        if let name = Networking().getInterfaces().first?.name, let type = NetworkInterfaceType(rawValue: name) {
            return type
        }

        return .Unknown
    }

    static var isConnectedByEthernet: Bool {
        let networking = Networking()
        for addr in networking.getInterfaces() {
            if addr.name == NetworkInterfaceType.Ethernet.rawValue {
                return true
            }
        }
        return false
    }

    static var isConnectedByWiFi: Bool {
        let networking = Networking()
        for addr in networking.getInterfaces() {
            if addr.name == NetworkInterfaceType.Wifi.rawValue {
                return true
            }
        }
        return false
    }

    // Credit to Martin R http://stackoverflow.com/a/34016247/600753 for this lovely code
    // New Swift 3 implementation needed upated to replace unsafepointer calls with .withMemoryRebound
    func getInterfaces() -> [(name : String, addr: String, mac : String)] {

        var addresses = [(name : String, addr: String, mac : String)]()
        var nameToMac = [ String: String ]()

        // Get list of all interfaces on the local machine:
        var ifaddr : UnsafeMutablePointer<ifaddrs>?
        guard getifaddrs(&ifaddr) == 0 else { return [] }
        guard let firstAddr = ifaddr else { return [] }

        // For each interface ...
        for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            let flags = Int32(ptr.pointee.ifa_flags)
            if var addr = ptr.pointee.ifa_addr {
                let name = String(cString: ptr.pointee.ifa_name)

                // Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
                if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                    switch Int32(addr.pointee.sa_family) {
                    case AF_LINK:
                        nameToMac[name] = withUnsafePointer(to: &addr) { unsafeAddr in
                            unsafeAddr.withMemoryRebound(to: sockaddr_dl.self, capacity: 1) { dl in
                                dl.withMemoryRebound(to: Int8.self, capacity: 1) { dll in
                                    let lladdr = UnsafeRawBufferPointer(start: dll + 8 + Int(dl.pointee.sdl_nlen), count: Int(dl.pointee.sdl_alen))

                                    if lladdr.count == 6 {
                                        return lladdr.map { String(format:"%02hhx", $0)}.joined(separator: ":")
                                    } else {
                                        return nil
                                    }
                                }
                            }
                        }

                    case AF_INET, AF_INET6:
                        // Convert interface address to a human readable string:
                        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                        if (getnameinfo(addr, socklen_t(addr.pointee.sa_len),
                                        &hostname, socklen_t(hostname.count),
                                        nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            let address = String(cString: hostname)
                            addresses.append( (name: name, addr: address, mac : "") )
                        }
                    default:
                        break
                    }
                }
            }
        }

        freeifaddrs(ifaddr)

        // Now add the mac address to the tuples:
        for (i, addr) in addresses.enumerated() {
            if let mac = nameToMac[addr.name] {
                addresses[i] = (name: addr.name, addr: addr.addr, mac : mac)
            }
        }

        return addresses
    }
}
debugPrint(Networking.networkInterfaceType)
switch Networking.networkInterfaceType {
case .Ethernet:
    // do something
    break

case .Wifi:
    // do something else
    break

default:
    break
}
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))