iOS 开发:判断 Wi-Fi 和蜂窝网络是否可用 (Objective-C 代码)
以下是使用 Objective-C 代码判断 Wi-Fi 和蜂窝网络是否可用的示例:
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
// 判断 Wi-Fi 网络是否可用
- (BOOL)isWiFiEnabled {
NSArray *interfaces = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
for (NSString *interfaceName in interfaces) {
NSDictionary *networkInfo = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName);
if (networkInfo && [networkInfo[@'SSID'] length] > 0) {
return YES;
}
}
return NO;
}
// 判断蜂窝网络是否可用
- (BOOL)isCellularEnabled {
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (carrier && [carrier carrierName]) {
return YES;
}
return NO;
}
// 使用示例
if ([self isWiFiEnabled]) {
NSLog('Wi-Fi 网络可用');
} else {
NSLog('Wi-Fi 网络不可用');
}
if ([self isCellularEnabled]) {
NSLog('蜂窝网络可用');
} else {
NSLog('蜂窝网络不可用');
}
请注意,在使用以上代码之前,需要在项目中导入 SystemConfiguration.framework 和 CoreTelephony.framework。
原文地址: https://www.cveoy.top/t/topic/fbEF 著作权归作者所有。请勿转载和采集!