面试题答案
一键面试原理
- 延迟检测:网络状态切换时,立即检测可能不准确。引入延迟机制,等待一段时间后确认网络状态,减少虚假报告。比如网络从WiFi切换到蜂窝数据,刚切换瞬间可能存在短暂不稳定,延迟检测可避免误判。
- 多次检测确认:不能仅依赖一次检测结果,进行多次检测并综合判断,增加准确性。例如连续检测三次,若结果一致则确认网络状态。
- 区分网络类型变化:不仅检测网络是否连接,还要区分网络类型变化。如从WiFi切换到蜂窝数据,不同网络类型对应用功能可能有不同影响。
代码实现优化
- 延迟检测实现
// 定义延迟时间
static const NSTimeInterval kReachabilityDelay = 2.0;
@property (nonatomic, strong) NSTimer *delayTimer;
- (void)reachabilityChanged:(NSNotification *)note {
Reachability *reachability = note.object;
// 取消之前的延迟定时器
[self.delayTimer invalidate];
self.delayTimer = nil;
// 启动新的延迟定时器
self.delayTimer = [NSTimer scheduledTimerWithTimeInterval:kReachabilityDelay target:self selector:@selector(checkReachabilityAfterDelay) userInfo:nil repeats:NO];
}
- (void)checkReachabilityAfterDelay {
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus status = [reachability currentReachabilityStatus];
// 处理网络状态
if (status == ReachableViaWiFi) {
// WiFi连接处理
} else if (status == ReachableViaWWAN) {
// 蜂窝数据连接处理
} else {
// 无网络连接处理
}
}
- 多次检测确认实现
@property (nonatomic, assign) NSInteger checkCount;
@property (nonatomic, assign) NetworkStatus lastStatus;
- (void)reachabilityChanged:(NSNotification *)note {
Reachability *reachability = note.object;
NetworkStatus status = [reachability currentReachabilityStatus];
if (self.checkCount == 0) {
self.lastStatus = status;
self.checkCount++;
} else if (self.checkCount < 3) {
if (status == self.lastStatus) {
self.checkCount++;
} else {
self.checkCount = 1;
self.lastStatus = status;
}
} else {
// 三次检测结果一致,确认网络状态
if (status == ReachableViaWiFi) {
// WiFi连接处理
} else if (status == ReachableViaWWAN) {
// 蜂窝数据连接处理
} else {
// 无网络连接处理
}
self.checkCount = 0;
}
}
- 区分网络类型变化实现
@property (nonatomic, assign) NetworkStatus previousStatus;
- (void)reachabilityChanged:(NSNotification *)note {
Reachability *reachability = note.object;
NetworkStatus status = [reachability currentReachabilityStatus];
if (status != self.previousStatus) {
if (status == ReachableViaWiFi && self.previousStatus != ReachableViaWiFi) {
// 从其他网络类型切换到WiFi的处理
} else if (status == ReachableViaWWAN && self.previousStatus != ReachableViaWWAN) {
// 从其他网络类型切换到蜂窝数据的处理
} else if (status == NotReachable && (self.previousStatus == ReachableViaWiFi || self.previousStatus == ReachableViaWWAN)) {
// 从有网络连接切换到无网络连接的处理
}
self.previousStatus = status;
}
}
通过上述原理和代码实现优化,可以更好地处理Reachability在网络状态监测中的边缘情况,提高应用在复杂网络环境下的稳定性和准确性。