LoginSignup
46
46

More than 5 years have passed since last update.

iPhoneアプリのネットワークステータスを取得する

Last updated at Posted at 2013-01-17

ネットワークに接続する iPhone アプリを圏外で起動した場合にも
アラート表示をする等の動作をしないと、ユーザビリティが悪く Apple の審査に落ちてしまう。
そのため、アプリケーションからネットワークステータスを取得して
挙動を変える必要がある。

準備

ここから ARC に対応した Reachability を導入する。
CocoaPods を導入している場合は、Podfile に下記を追記する。

pod 'Reachability'

SystemConfiguration.framework を追加する。

実装

#import "Reachability.h"

@interface xxxViewController ()
@property (nonatomic) Reachability *reachability;
@end

- (void)viewDidAppear:(BOOL)animated {
    // ネットワーク状態が変更された際に通知を受け取る
    _reachability  = [Reachability reachabilityForInternetConnection];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifiedNetworkStatus:) name:kReachabilityChangedNotification object:nil];
    [_reachability startNotifier];

    NetworkStatus networkStatus = [_reachability currentReachabilityStatus];
    /*
     ここで networkStatus には
     NotReachable : 接続されていない
     ReachableViaWWAN : 3G接続
     ReachableViaWiFi : Wi-Fi接続
     が入る
     */
    if (networkStatus == NotReachable) {
        // ここに UIAlertView など、圏外の場合の処理
    } else {
        [self xxx]; // ここに正常系の処理を関数で書く
    }
}

- (void)notifiedNetworkStatus:(NSNotification *)notification
{
    NetworkStatus networkStatus = [_reachability currentReachabilityStatus];
    // ネットワーク接続の通知を受け取った場合に、正常系の処理を行う
    if (networkStatus != NotReachable) {
        [self xxx];
    }
}
46
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
46