- GitHub: Reachability
- Star: 6.9k
WARNING there have been reports of apps being rejected when Reachability is used in a framework. The only solution to this so far is to rename the class.
警告:該類庫可能使用了與 Apple 源碼相同的類名,因此提交應(yīng)用審核時(shí),可能會(huì)被拒絕。目前為止,唯一的解決方法就是更改類名。
Reachability
Reachability 是 Apple 的 Reachability
類的替代品。 它兼容自動(dòng)引用計(jì)數(shù)(ARC),使用新的 GCD 方法來通知網(wǎng)絡(luò)狀態(tài)的變化。
除了標(biāo)準(zhǔn)的 NSNotification
之外,它還支持使用 Blocks 塊的方式處理網(wǎng)絡(luò)是否可訪問的情況。
最后,你可以指定是否將 WWAN 連接視為“可達(dá)”。
在真實(shí)設(shè)備上測(cè)試之前,請(qǐng)不要開啟 BUGS 模式
在你開啟一個(gè)關(guān)于 iOS6 / iOS5 版本的構(gòu)建錯(cuò)誤之前,請(qǐng)使用標(biāo)簽3.2或3.1,因?yàn)樗鼈冎С址峙漕愋汀?/strong>
Requirements
Once you have added the .h/m
files to your project, simply:
- Go to the
Project->TARGETS->Build Phases->Link Binary With Libraries
. - Press the plus in the lower left of the list.
- Add
SystemConfiguration.framework
.
Boom, you're done.
示例
一、Blocks 方法示例
使用 Blocks 塊來監(jiān)聽網(wǎng)絡(luò)狀態(tài)是否改變。該 Blocks 將會(huì)在后臺(tái)線程中被調(diào)用,因此你需要將UI 更新切換到主線程中。
Objective-C 示例
// 創(chuàng)建 reachability 對(duì)象
Reachability *reach = [Reachability reachabilityWithHostname:@"www.google.com"];
// 設(shè)置網(wǎng)絡(luò)可以訪問的 blocks 回調(diào)
reach.reachableBlock = ^(Reachability*reach)
{
// 記住這里的代碼會(huì)在后臺(tái)線程中被調(diào)用,如果你想要更新 UI,一定到切換到主線程:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"REACHABLE!");
});
};
// 設(shè)置網(wǎng)絡(luò)不可訪問的 blocks 回調(diào)
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"UNREACHABLE!");
};
// 開啟監(jiān)聽
[reach startNotifier];
Swift 3 示例
import Reachability
var reach: Reachability?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Allocate a reachability object
self.reach = Reachability.forInternetConnection()
// Set the blocks
self.reach!.reachableBlock = {
(reach: Reachability?) -> Void in
// keep in mind this is called on a background thread
// and if you are updating the UI it needs to happen
// on the main thread, like this:
DispatchQueue.main.async {
print("REACHABLE!")
}
}
self.reach!.unreachableBlock = {
(reach: Reachability?) -> Void in
print("UNREACHABLE!")
}
self.reach!.startNotifier()
return true
}
二、NSNotification
通知方法示例
此示例將使用 NSNotification
來通知網(wǎng)絡(luò)連接狀態(tài)的變化。 它們將在主線程上被調(diào)用,因此你可以從該函數(shù)內(nèi)部進(jìn)行UI更新。
此外,它要求Reachability
對(duì)象默認(rèn)將 WWAN(3G / EDGE / CDMA)蜂窩網(wǎng)絡(luò)視為不可達(dá)的連接(如果你正在編寫視頻流應(yīng)用程序(例如,用于保存用戶的數(shù)據(jù)計(jì)劃),則可以使用此功能)。
Objective-C 示例
// 通過指定域名的方式創(chuàng)建 reachability 對(duì)象
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
// 不判斷蜂窩網(wǎng)絡(luò)是否可用
reach.reachableOnWWAN = NO;
// Here we set up a NSNotification observer. The Reachability that caused the notification
// is passed in the object parameter
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
[reach startNotifier];
接收通知的方法:
-(void)reachabilityChanged:(NSNotification*)note
{
Reachability * reach = [note object];
if([reach isReachable])
{
NSString * temp = [NSString stringWithFormat:@"GOOGLE Notification Says Reachable(%@)", reach.currentReachabilityString];
NSLog(@"%@", temp);
}
else
{
NSString * temp = [NSString stringWithFormat:@"GOOGLE Notification Says Unreachable(%@)", reach.currentReachabilityString];
NSLog(@"%@", temp);
}
}
Swift 3 示例
import Reachability
var reach: Reachability?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Allocate a reachability object
self.reach = Reachability.forInternetConnection()
// Tell the reachability that we DON'T want to be reachable on 3G/EDGE/CDMA
self.reach!.reachableOnWWAN = false
// Here we set up a NSNotification observer. The Reachability that caused the notification
// is passed in the object parameter
NotificationCenter.default.addObserver(
self,
selector: #selector(reachabilityChanged),
name: NSNotification.Name.reachabilityChanged,
object: nil
)
self.reach!.startNotifier()
return true
}
func reachabilityChanged(notification: NSNotification) {
if self.reach!.isReachableViaWiFi() || self.reach!.isReachableViaWWAN() {
print("Service avalaible!!!")
} else {
print("No service avalaible!!!")
}
}
Tell the world
Head over to Projects using Reachability and add your project for "Maximum Wins!".
總結(jié)
- 創(chuàng)建
Reachability
對(duì)象的方法有以下幾種:
+(instancetype)reachabilityWithHostName:(NSString*)hostname; // 指定域名
+(instancetype)reachabilityForInternetConnection; // 通用網(wǎng)絡(luò)連接
+(instancetype)reachabilityWithAddress:(void *)hostAddress; // 指定地址
+(instancetype)reachabilityForLocalWiFi; // 指定Wi-Fi網(wǎng)絡(luò)
- 可選設(shè)置,是否忽視蜂窩網(wǎng)絡(luò)可達(dá)性
@property (nonatomic, assign) BOOL reachableOnWWAN;
- 監(jiān)聽網(wǎng)絡(luò)可達(dá)性的方法有兩種:
Blocks 方式:
@property (nonatomic, copy) NetworkReachable reachableBlock;
@property (nonatomic, copy) NetworkUnreachable unreachableBlock;
通知方式:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
- 開始、停止監(jiān)聽
-(BOOL)startNotifier;
-(void)stopNotifier;
示例代碼
// 網(wǎng)絡(luò)可達(dá)性檢查
Reachability *reachability = [Reachability reachabilityWithHostName:URL_HOST];
reachability.reachableBlock = ^(Reachability *reachability) {
// 3.0s 后執(zhí)行加載任務(wù)
// 默認(rèn)情況下,切換到主線程更新UI,這里延遲3秒是為了多旋轉(zhuǎn)一會(huì)菊花用的。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 連接服務(wù)器
[self connectToServer];
});
};
reachability.unreachableBlock = ^(Reachability *reachability) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.emptyDescription = @"無法訪問服務(wù)器,請(qǐng)稍后再試。";
self.displayEmptyDataSet = YES;
self.loading = NO;
});
};
[reachability startNotifier];
類似框架
- Apple 官方示例:Reachability
-
AFNetworking 的
AFNetworkReachabilityManager
類