アプリの最上位クラスで実装する。
1. ヘッダファイルの実装
hoge.AppDelegate.h
#import "Reachability.h"
@interface hogeAppDelegate : NSObject{
NetworkStatus remoteHostStatus;
NetworkStatus internetConnectionStatus;
NetworkStatus localWiFiConnectionStatus;
}
@property NetworkStatus remoteHostStatus;
@property NetworkStatus internetConnectionStatus;
@property NetworkStatus localWiFiConnectionStatus;
@end
2. メソッドの実装
hoge.AppDelegate.m
#import "hogeAppDelegate.h"
@implementation hogeAppDelegate
@synthesize remoteHostStatus;
@synthesize internetConnectionStatus;
@synthesize localWiFiConnectionStatus;
// ネットワーク接続状態の更新
- (void)updateStatus {
self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
}
// ネットワーク切断のときに通知される
- (void)reachabilityChanged:(NSNotification *)note {
LOG_CURRENT_METHOD;
[self updateStatus];
if (self.remoteHostStatus == NotReachable) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"AppName", nil) message:NSLocalizedString(@"NotReachable", nil)
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
// アプリ起動時にネットワーク接続状態の監視に入る。
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// ネットワーク接続状態チェックの接続先ホストの設定
[[Reachability sharedReachability] setHostName:@"www.apple.com"];
// ネットワークの状態が変わったときに通知を受ける
[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
// ネットワークの状態が変わったときに通知を受けるメソッドを登録
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)
name:@"kNetworkReachabilityChangedNotification" object:nil];
[self updateStatus];
}
- (void)dealloc {
// 通知センタ登録削除
[[NSNotificationCenter defaultCenter] removeObserver:self];
[window release];
[super dealloc];
}
3. フレームワークの追加
SystemConfiguration.framework をプロジェクトに追加する。
4. Appleのサンプルコードから追加
iPhone Dev Center - Apple Developer Connection から、サンプルコード"Reachability"をダウンロードする。
http://developer.apple.com/iphone/library/samplecode/Reachability/index.html
その中の、Reachability.h Reachability.m を自分のプロジェクトにコピーする。
■参考記事
http://d.hatena.ne.jp/KishikawaKatsumi/20090118/1232223329
http://d.hatena.ne.jp/nakamura001/20090214/1234634953
タグ:iPhone
【ネットワーク圏外通知の最新記事】