iOS Development-Monitor network changes

Source: Internet
Author: User

Usually in the app some interface, need to get the data update interface through the network. By establishing network status monitoring, the application automatically refreshes the page data when the network becomes connected from disconnect, so it does not require the user to manually refresh the page, which improves the user experience of the product.


First, include the header file

#import "Reachability.h"

Add instance variables in Viewcontorller: reachability *_networkconn;


Second, the establishment of network change monitoring

Network changes include the change from disconnection to connection, connection to disconnection, and any situation where the app receives 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];
Where the Networkstatechange function is called when the network is changed.


Third, get the network status

After receiving the notification of network changes, the notification does not inform the current network status, so we do not know whether the current network is in a disconnected or connected, need to actively detect, 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;}

Four, refresh the interface

-(void) networkstatechange{    if ([self isnetworkenable]) {        //In this refresh interface    }}


iOS Development-Monitor network changes

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.