IOS-----Detect Network Status

Source: Internet
Author: User
Tags notification center

iOS not only built rich network communication APIs to develop network communication applications, but also supported a large number of third-party network communication APIs, fully support TCP, UDP network communication,

You can refer to Apple's official documentation for information on using Cfnetwork for UDP protocol communication.

Two third-party network communication frameworks on the iOS platform: afnetworking and ASIHTTPRequest, both of which are highly encapsulated in the iOS network communication API, allowing for more

Simple programming to achieve network communication

Detecting Network StatusCheck network status

The following two steps are required to check the network status of a device.

1

Download, add reachability class

Reachability.zip compressed packages can be downloaded via https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip link, Extracting the package will get a Xcode project

You can also search for reachability through the Xcode help group system, then you can see the Reachability sample project in the "Sample Code" section, select the "reachability" list item to view Reachability project

Click the Open Project button to open the project

2

Add a systemconfiguration.framework framework to a project

Code Snippets

1 VIEWCONTROLLER.M2 3 #import"ViewController.h"4 5 #import"Reachability.h"6 7 @implementationViewcontroller8 9- (void) ViewdidloadTen  One { A  - [Super Viewdidload]; -  the } -  -   -  + //Test Network Status -  +-(Ibaction) Testnetstatus: (ID) Sender A  at { -  -nsstring* site =Self.siteFiled.text; -  -    //Create a reachability that accesses the specified site -  inreachability* reach =[reachability reachabilitywithhostname:site]; -  to    //determine the network status of the device +  -   Switch([reach Currenreachabilitystatus]) the  *   { $ Panax Notoginseng      //Cannot access -  the  Casenotreachable: +  A[Self showalert:[nsstring stringwithformat:@ "cannot access%@ ", site]"; the  +  Break; -  $ //using the 3G/4G network $  -  CaseReachableviawifi: -  the[Self showalert:[nsstring stringwithformat:@] Use 3g/4g network access%@ ", site]"; - Wuyi  Break; the  - //Use WiFi network Wu  -  CaseReachableviawwan: About  $[Self showalert:[nsstring stringwithformat:@] Use 3g/4g network access%@ ", site]"; -  -  Break; -  A } +  the } -  $   the  the //Test WiFi the  the-(Ibaction) Testwifi: (ID) Sender -  in { the  the    if([[Reachability Reachabilityforlocalwifi] currentreachabilitystatus]! =notreachable) About  the    { the  the [self showalert:@ "WiFi network is already connected"]; +  - } the Bayi Else the  the { -  - [self showalert:@: "WiFi network is not available"]; the  the } the  the } -  the   the  the //Test your mobile network94  the-(Ibaction) Testinternet: (ID) Sender the  the {98  About    if([[Reachability reachabilityforinternetconnection] currentreachabilitystatus]! =notreachable) - 101    {102 103[Self showalert:@] 3g/4G Network is connected "];104  the }106 107 Else108 109 { the 111[Self showalert:@] 3g/4G Network not available "]; the 113 } the  the } the 117- (void) Showalert: (nsstring*) msg118 119 { - 121uialertview* alert = [[Uialertview alloc] initwithtitle:@ "Network status" message:msgDelegate: nil cancelbuttontitle:@ "OK" otherbuttontitles:nil];122 123 [alert show];124  the }126 127 @end

Description

The above program first calls the Reachability class's Reachabilitywithhostname: Class method to get the Reachability object, The object's Currentreachabilitystatus method is then called to get access to the specified site, which returns the NetworkStatus enumeration value, which has the following 3:

typedef enum{

notreachable = 0,//No connection

reachableviawifi,//using 3G/4G Network

Reachableviawwan//Use WiFi

} networkstatus;

Therefore, the above program will judge the return value of the Currentreachabilitystatus method of reachability, so that the application can get the state and mode of accessing the network.

Monitor network status changes

After the program obtains the Reachability object, the Reachability object's Startnotifier method is called to turn on the object's listening state-------when the reachability

When a continuous state changes, the object sends a KREACHABILITYCHANGEDNOTIFICATION notification to the default notification hub, so the program uses only the default notification

The heart listens to the notification.

To listen for changes in the state of the network, add the following code to the Application:didfinishlaunchingwithoptions: method of the application delegate class.

code snippet

  APPDELEGATE.M  //  Use notification hubs to listen for kreachabilitychangednotification notifications  [[nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (reachabilitychanged:) name:kreachabilitychangednotification  object  :nil];  //  reachability  * reach = [reachability reachabilitywithhostname:@ "www.baidu.com"];  //  [reach Startnotifier];  

 

Description

The code above uses the default notification hubs to detect kreachabilitychangednotification notifications, which means that when reachability's connection status changes, the default notification center receives the notification. This triggers the reachabilitychanged: Method of the application delegate class, so you also need to define the following methods in the application delegate class.

Code Snippets

1 APPDELEGATE.M2 3- (void) reachabilitychanged: (Nsnotification *) Noto4 5 {6 7   //gets the reachability object being monitored by a notification object8 9reachability *curreach = [NoteObject];Ten  One   //gets the network state of the Reachability object A  -NetworkStatus status =[Curreach currentreachabilitystatus]; -  the   if(Status = =notreachable) -  -   { -  +Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Reminder" message:@ "Cannot access www.baidu.com"Delegate: Nil cancelbuttontitle:@ "YES" otherbuttontitles:nil]; -  + [alert show]; A  at } -  -}

Description

As you can see from the code above, this example listens to the Reachability object that accesses www.baidu.com, and when the object state is notreachable, the program uses Uialertview for reminders.

IOS-----Detect Network Status

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.