開(kāi)源第三方地址: https://github.com/tonymillion/Reachability
當(dāng)前使用網(wǎng)絡(luò)檢測(cè)
Reachability *reachable = [Reachability reachabilityForInternetConnection];
if ([reachable currentReachabilityStatus] == ReachableViaWiFi) {
NSLog(@"wifi - 已連接");
} else if ([reachable currentReachabilityStatus] == ReachableViaWWAN) {
NSLog(@"數(shù)據(jù) - 已連接");
} else {
NSLog(@"無(wú)網(wǎng)絡(luò)連接");
}
當(dāng)前網(wǎng)絡(luò)變化監(jiān)聽(tīng)
// 添加 監(jiān)聽(tīng)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChange:) name:kReachabilityChangedNotification object:nil];
self.reach = [Reachability reachabilityForInternetConnection];
[self.reach startNotifier];
- (void)netChange:(NSNotification *)notification{
if ([self.reach currentReachabilityStatus] == ReachableViaWiFi) {
NSLog(@"wifi");
} else if ([self.reach currentReachabilityStatus] == ReachableViaWWAN) {
NSLog(@"數(shù)據(jù)");
} else {
NSLog(@"無(wú)網(wǎng)絡(luò)");
}
}
// 注意 需要remove 監(jiān)聽(tīng)
[self.reach stopNotifier];
使用 block 多線程監(jiān)聽(tīng)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChange) name:kReachabilityChangedNotification object:nil];
self.reach = [Reachability reachabilityForInternetConnection];
[self.reach startNotifier];
- (void)netChange{
self.reach.reachableBlock = ^(Reachability *reachable) {
dispatch_async(dispatch_get_main_queue(), ^{
// UI
NSLog(@"當(dāng)前網(wǎng)絡(luò)已連接");
NSLog(@"當(dāng)前狀態(tài)-%@",[reachable currentReachabilityString]);
});
};
self.reach.unreachableBlock = ^(Reachability *reachable) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"當(dāng)前無(wú)網(wǎng)絡(luò)連接");
NSLog(@"當(dāng)前狀態(tài)-%@",[reachable currentReachabilityString]);
});
};
// 這個(gè)比較懸淆游,應(yīng)該是跟本地wifi存在可以連接聯(lián)網(wǎng)
self.reach.reachabilityBlock = ^(Reachability *reachable, SCNetworkConnectionFlags flags) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"有網(wǎng)絡(luò)可用");
NSLog(@"當(dāng)前狀態(tài)-%@",[reachable currentReachabilityString]);
});
};
}
// 注意 需要remove 監(jiān)聽(tīng)
[self.reach stopNotifier];
其他
勇边。