IOS programming-Network Monitoring
In network applications, You need to monitor the network status of your devices in real time for two purposes:
(1) let users know their network status and prevent misunderstandings (for example, the application is incompetent)
(2) Smart processing based on the user's network status, saving user traffic and improving user experience
WIFIG Network: Automatically downloads HD Images
Low-speed network: only downloading thumbnails
No network: Only offline cached data is displayed.
Apple officially provides an example program called Reachability to help developers detect the network status.
Www.bkjia.com
2. Monitoring Network Status
Reachability usage steps
Add framework SystemConfiguration. framework
Add source code
Include header files
# Import Reachability. h
# Import QYViewController. h
# Import Reachability. h
@ Interface QYViewController ()
@ Property (nonatomic, strong) Reachability * conn;
@ End
@ Implementation QYViewController
-(Void) viewDidLoad
{
[Super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[Nsicationcenter center defacenter center] addObserver: self selector: @ selector (networkStateChange) name: kReachabilityChangedNotification object: nil];
Self. conn = [Reachability reachabilityForInternetConnection];
[Self. conn startNotifier];
}
-(Void) dealloc
{
[Self. conn stopNotifier];
[[Nsicationcenter center defacenter center] removeObserver: self];
}
-(Void) networkStateChange
{
[Self checkNetworkState];
}
-(Void) checkNetworkState
{
// 1. Check the wifi status
Reachability * wifi = [Reachability reachabilityForLocalWiFi];
// 2. Check whether the mobile phone can be connected to the network (wifig.5 g)
Reachability * conn = [Reachability reachabilityForInternetConnection];
// 3. Determine the network status
If ([wifi currentReachabilityStatus]! = NotReachable) {// wifi available
NSLog (@ wifi available );
} Else if ([conn currentReachabilityStatus]! = NotReachable) {// no wifi is used. Use the network provided by your mobile phone to access the Internet.
NSLog (@ use your mobile phone to access the Internet );
} Else {// No network
NSLog (@ No network );
}
}