NSURL *scriptUrl = [NSURLURLWithString:@"https://www.baidu.com"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];if (data)NSLog(@"Device is connected to the Internet");
elseNSLog(@"Device is not connected to the Internet");
-(void) viewWillAppear:(BOOL)animated
{
// check for internet connection
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachableFoo = [Reachability reachabilityForInternetConnection];
[internetReachableFoo startNotifier];
// check if a pathway to a random host exists
hostReachable = [ReachabilityreachabilityWithHostName:@"www.apple.com"];
[hostReachable startNotifier];
// now patiently wait for the notification
}
完成通知方法,可以检测目前的网络是什么状态,是否有网络,wifi,以及wwan
-(void) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachableFoo currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(@"A gateway to the host server is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"A gateway to the host server is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"A gateway to the host server is working via WWAN.");
break;
}
}
}