[翻译] JTSReachability

时间:2024-04-14 18:22:14

JTSReachabilit

[翻译] JTSReachability

[翻译] JTSReachability

An adaptation of Apple's Reachability with some block-based conveniences.

这是一个苹果的网络检测类的改编版本,提供便利的基于block的方法。

Usage

Usage is straightforward.

使用就如其名一样简单。

Singleton

Access the singleton instance of JTSReachabilityResponder via:

你可以通过以下方法来操作单例:

+ (instancetype)sharedInstance;

Or Non-Singleton, if You're Not Into the Whole Singleton Thing

Instantiate an instance of JTSReachabilityResponder via:

你也可以根据某个具体的hostname来作为网络检测的基准:

- (instancytype)initWithOptionalHostname:(NSString *)hostname;

If you don't specify a hostname, there are some edge cases where Apple's networking frameworks will assume there's a valid connection even when there isn't (e.g. when connected to a local WiFi network without a connection to the Internet proper).

如果你没有指定一个hostname,会有一些极端情况导致出错(比方说,你连上了路由器上的wifi,但是这个路由器没有连上网,这个时候你是不能上网的)

Registering Status Change Handlers

An object in your application registers a block to be executed whenever the network status changes between one of the three known states (none, Wi-fi, or cellular) as follows:

一个block对象会因为网络状态的改变而执行(三种状态:没有网络,wifi,cellular)

- (void)someSetupMethod {

    JTSReachabilityResponder *responder = [JTSReachabilityResponder sharedInstance];

    [responder addHandler:^(JTSNetworkStatus status) {
// Respond to the value of "status"
} forKey:@"MyReachabilityKey"];
}

Your object is responsible for cleaning up after itself, typically in dealloc, as follows:

你也需要在dealloc方法中将这个监听移除掉哦:

- (void)dealloc {

    JTSReachabilityResponder *responder = [JTSReachabilityResponder sharedInstance];

    [responder removeHandlerForKey:@"MyReachabilityKey"];
}

All blocks are called on the main thread, and must be added or removed on the main thread.

所有的block都是在主线程上面执行的,所以,也必须在主线程上面移除掉。