您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 判斷網路狀態:用 SCNetworkReachability 實作連線檢測

編輯:iOS 開發綜合

要在 iOS 上判斷網路是否可用,最基礎的做法是 SystemConfiguration 框架裡的 SCNetworkReachability。使用前記得先把 SystemConfiguration.framework 加入專案。

一、頭檔宣告

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

// 如果方法前面加上 +,就是類的靜態方法,這裡先寫成實例方法
- (BOOL)connectedToNetwork;

@end

二、實作內容

#import "ViewController.h"
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonHMAC.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netdb.h>

@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];
}

- (BOOL)connectedToNetwork {
    // 建立 zero address 結構
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // 取得 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];
}

@end

三、幾點實務提醒

Reachability 只能告訴你「有沒有可用的路由」,並不代表網路真的通。基地台訊號存在但沒有實際連線、或是連上 Wi-Fi 卻沒有對外網路(常見的需登入 Portal),它仍會回報可達。因此正式專案應該搭配實際的請求逾時處理,把 Reachability 當作「提前提示」而非唯一依據。

另外,Reachability 有現成的匿名函式版本 API,能註冊通知在網路狀態變動時主動 callback,比每次操作前都去查一次更省資源。若使用 Swift,Apple 也已提供更新版的 NWPathMonitor 作為替代方案。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved