iOS 网络状态监测:Objective-C 实现代码示例
在 iOS 开发中,可以使用 Reachability 库来监测网络情况。以下是使用 Objective-C 代码实现网络监测的示例:
首先,导入 Reachability 库:
#import "Reachability.h"
然后,在需要监测网络情况的地方,添加以下代码:
// 创建 Reachability 对象
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
// 监听网络状态变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStatusChanged:) name:kReachabilityChangedNotification object:nil];
// 定义网络状态变化的处理方法
- (void)networkStatusChanged:(NSNotification *)notification {
Reachability *reachability = (Reachability *)[notification object];
NetworkStatus status = [reachability currentReachabilityStatus];
if (status == NotReachable) {
NSLog('网络连接已断开');
} else if (status == ReachableViaWiFi) {
NSLog('当前使用 WiFi 网络');
} else if (status == ReachableViaWWAN) {
NSLog('当前使用移动网络');
}
}
// 在不需要监测网络状态时,记得移除通知
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}
以上代码会在网络状态发生变化时,分别输出网络连接已断开、当前使用 WiFi 网络、当前使用移动网络的信息。你可以根据实际需求,在 networkStatusChanged 方法中进行相应的处理。
原文地址: https://www.cveoy.top/t/topic/pcEK 著作权归作者所有。请勿转载和采集!