重複の可能性:
ネットワークがダウンしてもアプリが残る
ネットワーク接続がダウンすると、インターネットからのデータの読み込みにより、アプリが低速状態になります。この問題を解決する方法はありますか。
重複の可能性:
ネットワークがダウンしてもアプリが残る
ネットワーク接続がダウンすると、インターネットからのデータの読み込みにより、アプリが低速状態になります。この問題を解決する方法はありますか。
便利な場所ならどこでもインターネットをチェックできます。viewDidLoad または didFinishLaunching メソッドにある可能性があります。以下は、インターネット接続をチェックするために使用するコード例です。
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}
Apple は、ネットワークの可用性をテストする方法を示す Reachabilityサンプル アプリケーションを提供しています。以下のコードを使用すると、自動到達可能性を実現できます。
if ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] == ReachableViaWiFi)
{
// perform action that requires a local WiFi connection
}
else
{
// give a message that local WiFi is required
}
インターネット接続を確認できます。次のコードを使用して、checkReachabilityメソッドを呼び出します。これは、didFinishLaunchingまたはviewWillAppearまたはviewDidLoadメソッドに含めることができます。
-(void)checkReachability{//インターネット接続を確認します[[NSNotificationCenterdefaultCenter] addObserver:selfセレクター:@selector(checkNetworkStatus :) name:kReachabilityChangedNotification object:nil];
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
// check if a pathway to a random host exists
hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
[hostReachable startNotifier];
}
-(void)checkNetworkStatus:(NSNotification *)notice {
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
break;
}
}
}