iOS 判斷網路狀態 簡單樣本

來源:互聯網
上載者:User

iOS 判斷網路狀態 簡單樣本

添加SystemConfiguration.framework 到工程中

對應的.h檔案

 

#import @interface ViewController : UIViewController//如果方法前面加+,就相當於類的靜態方法,這裡要注意一下- (BOOL) connectedToNetwork;@end
對應的.m檔案

 

 

#import "ViewController.h"#import #import #import #import #import @interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    UIButton *btn = [[UIButton alloc]init];    btn.frame = CGRectMake(20, 20, 40, 40);    btn.backgroundColor = [UIColor brownColor];    [self.view addSubview:btn];    [btn addTarget:self action:@selector(testOut:) forControlEvents:UIControlEventTouchUpInside];    // Do any additional setup after loading the view, typically from a nib.}-(BOOL) connectedToNetwork{    // Create zero addy    struct sockaddr_in zeroAddress;    bzero(&zeroAddress, sizeof(zeroAddress));    zeroAddress.sin_len = sizeof(zeroAddress);    zeroAddress.sin_family = AF_INET;        // Recover reachability flags    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);    SCNetworkReachabilityFlags flags;        BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);    CFRelease(defaultRouteReachability);        if (!didRetrieveFlags)        {        printf("Error. Could not recover network reachability flags\n");        return NO;        }        BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);    return (isReachable && !needsConnection) ? YES : NO;}//在調用的時候,在對應的按鈕中加入判斷:- (IBAction)testOut:(UIButton *)sender{    if(![self connectedToNetwork])        {        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"網路連接失敗,請查看網路是否串連正常!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];        [alert show];        }        NSLog(@"testOut Event");}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.