自动检测我的手机是否已连接到互联网

时间:2016-11-30 12:41:39

标签: ios objective-c iphone

-(BOOL)IsConnectionAvailable{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];   
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return !(networkStatus == NotReachable);
}

我正在使用上面的代码,必须定期调用它来检查是否有网络连接。 我正在开发聊天应用程序,我希望在设备连接到网络时立即发送消息。

由于

1 个答案:

答案 0 :(得分:0)

您可以使用 kReachabilityChangedNotification

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkForReachability:) name:kReachabilityChangedNotification object:nil];

}

- (void) checkForReachability:(NSNotification *)notification
{
    if([self IsConnectionAvailable])// use your method here
    {
        // net available
    }
    else
    {
        // no internet
    }

}