The network condition of the Apple device is changeable, may have the network, may also be disconnected, possibly through the WiFi networking, may also through the cellular data networking, many times we need to know the program currently running in the network condition
We can add Reachability.h and reachability.m to our project in the official Apple Download tool class reachability.
Example 1: View the current network environment (test network status by accessing a page)
reachability *reach = [reachability reachabilitywithhostname:@"http://www.cnblogs.com/zanglitao/"]; Switch([reach Currentreachabilitystatus]) { CaseNotreachable:nslog (@"Cannot access"); Break; CaseReachableviawifi:nslog (@"Use WiFi"); CaseReachableviawwan:nslog (@"using cellular data"); }
Example 2: Test if your phone is connected to WiFi (or cellular)
if ([[Reachability Reachabilityforlocalwifi] currentreachabilitystatus]! = notreachable) { NSLog (@ " WiFi network available "); } if ([[Reachability reachabilityforinternetconnection] currentreachabilitystatus]! = notreachable) { NSLog ( @ " cellular network available "); }
Example 3: Listening for network changes
We turn on the notification via the Startnotifier method of the Reachability object, and when the network changes reachability sends a KREACHABILITYCHANGEDNOTIFICATION notification to the default notification center
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions{[[Nsnotificationcenter defaultcenter] addobserver:self selector: @selector (netstatuschange:) Name:kreachabilitychangednotificationObject: nil]; Reachability*reach = [reachability reachabilitywithhostname:@"http://www.cnblogs.com/zanglitao/"]; [Reach Startnotifier];//[reach Stopnotifier]; returnYES;}- (void) Netstatuschange: (Nsnotification *) Note {reachability*reach = [NoteObject]; //get current network statusNetworkStatus *status =[reach Currentreachabilitystatus]; }
Get network status for iOS network access