了解iOS设备是否具有蜂窝数据功能

gca*_*amp 31 iphone objective-c cellular-network uidevice ios

我在我的应用程序中切换了"仅在WiFi上下载".但是,这种切换对于iPod touch或WiFi-iPad来说毫无用处.

有没有办法知道设备是否具有代码中的蜂窝数据功能?将来会发挥作用的东西也会很棒(就像带有3G的iPod touch第五代产品一样).

ben*_*ech 32

您好,您应该能够检查它是否具有pdp_ip0接口

#import <ifaddrs.h>

- (bool) hasCellular {
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    bool found = false;
    if (getifaddrs(&addrs) == 0) {
        cursor = addrs;
        while (cursor != NULL) {
            NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
            if ([name isEqualToString:@"pdp_ip0"]) {
                found = true;
                break;
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return found;
}
Run Code Online (Sandbox Code Playgroud)

这不使用任何私有API.


dar*_*s0n 16

3G本身似乎很难找到.你可以找到一个设备是否可以拨打电话使用[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel://"]].您可以使用可访问代码检查设备是否可以访问互联网,期间(以及当前可能采用的方法):

NetworkStatus currentStatus = [[Reachability reachabilityForInternetConnection] 
                               currentReachabilityStatus];

if(currentStatus == kReachableViaWWAN) // 3G

else if(currentStatus == kReachableViaWifi) // ...wifi

else if(currentStatus == kNotReachable) // no connection currently possible
Run Code Online (Sandbox Code Playgroud)

..除此之外,我认为你不能检查设备中是否存在3G调制解调器.*****如果它无法拨打电话,并且当前没有开启小区数据和wifi 关闭,你将无法找出它是否具有3G功能.

另一种方式(不向前兼容的,所以你可能不希望这样做),是把设备的模型的详尽列表比较,知道哪些在他们的3G调制解调器,如图所示这里.

*****根据bentech的回答,如果你想要挖掘设备名称(如果Apple决定更改3g接口名称,这可能会停止工作而没有提前警告),请致电getifaddrs并检查pdp_ip0接口.

  • 我很清楚,这就是为什么我的答案是"不,没有办法只检查3G". (8认同)
  • 您应该使用第三个选项,默认为"是它有3G",然后在新设备出现时进行更新.如果切换器在没有3G的设备上不会做任何事情,那么未来的设备看到它是无害的(并且你可能还有一些时间可以更新). (2认同)

Mar*_*rke 6

@ bentech答案的Swift 3.0(UIDevice +扩展)

将此行添加到您的BridgingHeader.h:

#import <ifaddrs.h>
Run Code Online (Sandbox Code Playgroud)

别的地方:

extension UIDevice {
    /// A Boolean value indicating whether the device has cellular data capabilities (true) or not (false).
    var hasCellularCapabilites: Bool {
        var addrs: UnsafeMutablePointer<ifaddrs>?
        var cursor: UnsafeMutablePointer<ifaddrs>?

        defer { freeifaddrs(addrs) }

        guard getifaddrs(&addrs) == 0 else { return false }
        cursor = addrs

        while cursor != nil {
            guard
                let utf8String = cursor?.pointee.ifa_name,
                let name = NSString(utf8String: utf8String),
                name == "pdp_ip0"
                else {
                    cursor = cursor?.pointee.ifa_next
                    continue
            }
            return true
        }
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)