IOS development-monitoring network changes

Source: Internet
Author: User

IOS development-monitoring network changes

Generally, you need to obtain the data update interface through the network on some APP interfaces. By setting up a network status listener, an application automatically refreshes page data after the network changes from disconnected to connected. Therefore, you do not need to manually refresh the page to improve the user experience of the product.


1. include header files

#import "Reachability.h"

At the same time, add the instance variable Reachability * _ networkConn in viewcontorroller;


2. Establish a network change listener

Network changes include switching from disconnection to connection and connection to disconnection. In either case, the app will receive a notification of network changes. Add the following code to the viewDidLoad method:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];    _networkConn = [Reachability reachabilityForInternetConnection];    [_networkConn startNotifier];
The networkStateChange function is called when the network changes.


3. Obtain the network status

After the network change notification is received, the notification does not inform you of the current network status. Therefore, we do not know whether the current network is disconnected or connected. We need to actively detect the network. The detection method is as follows:

- (BOOL)isNetworkEnable{    BOOL flag = YES;    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];    switch ([r currentReachabilityStatus]) {        case NotReachable:            flag = NO;            break;        case ReachableViaWWAN:            break;        case ReachableViaWiFi:            break;                    default:            break;    }        return flag;}

4. Refresh the interface

-(Void) networkStateChange {if ([self isNetworkEnable]) {// refresh the interface here }}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.