Приложение iPhone зависает, когда оно находится вне зоны действия Wi-Fi-соединения?

Я разработал приложение для радио, которое использует сетевое соединение для потоковой передачи в Интернете, а также я проверяю условие, доступна ли сеть или нет. если нет сетевого подключения, отображается предупреждение «нет доступной сети». Мой код здесь

 - (void)viewDidLoad
  {
  [super viewDidLoad];


  //checking network reachability statys, this will show one alert view if no network available
    Reachability* reachabile = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus remoteHostStatus = [reachabile currentReachabilityStatus];

   if(remoteHostStatus == NotReachable) 
    {

    NSLog(@"not reachable");
       UIAlertView *notReachableAlert1=[[UIAlertView alloc]initWithTitle:@"NO INTERNET  CONNECTION" message:@"This Application Need Internet To Run" delegate:self cancelButtonTitle:@"Okay Buddy" otherButtonTitles:nil];
    notReachableAlert1.delegate=self;
     [notReachableAlert1 show];
     [notReachableAlert1 release];


    }




    [[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(moviePlayerPlaybackStateDidChange:) 
                                             name:MPMoviePlayerPlaybackStateDidChangeNotification 
                                           object:nil];




    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerLoadStateChanged:) name:MPMoviePlayerLoadStateDidChangeNotification object:player];



    // Do any additional setup after loading the view from its nib.
  }

также я проверил состояние уведомлений

  -(void) moviePlayerPlaybackStateDidChange:(NSNotification*)notification 
  {
  Reachability* reachabile = [Reachability reachabilityWithHostName:@"www.apple.com"];
  NetworkStatus remoteHostStatus = [reachabile currentReachabilityStatus];

  NSLog(@"playbackDidChanged");

  MPMoviePlayerController *moviePlayer = notification.object;
  player=notification.object;
  MPMoviePlaybackState playbackState = moviePlayer.playbackState;
   if(playbackState == MPMoviePlaybackStateStopped) 
     {
      NSLog(@"MPMoviePlaybackStateStopped");


   }
   else if(playbackState == MPMoviePlaybackStatePlaying) {
    NSLog(@"MPMoviePlaybackStatePlaying");


} else if(playbackState == MPMoviePlaybackStatePaused) {
    NSLog(@"MPMoviePlaybackStatePaused");

    if(remoteHostStatus == NotReachable) 
    {

          NSLog(@"not reachable");
          UIAlertView *notReachableAlert1=[[UIAlertView alloc]initWithTitle:@"NO INTERNET CONNECTION" message:@"This Application Need Internet To Run" delegate:self cancelButtonTitle:@"Okay Buddy" otherButtonTitles:nil];
        notReachableAlert1.delegate=self;
        [notReachableAlert1 show];
        [notReachableAlert1 release];


      }
 } else if(playbackState == MPMoviePlaybackStateInterrupted) 
    {
    NSLog(@"MPMoviePlaybackStateInterrupted");

    if((remoteHostStatus == NotReachable)&&(remoteHostStatus != ReachableViaWiFi)) 
    {

          NSLog(@"not reachable");
          UIAlertView *notReachableAlert1=[[UIAlertView alloc]initWithTitle:@"NO INTERNET CONNECTION" message:@"This Application Need Internet To Run" delegate:self cancelButtonTitle:@"Okay Buddy" otherButtonTitles:nil];
        notReachableAlert1.delegate=self;
        [notReachableAlert1 show];
        [notReachableAlert1 release];


     }

моя проблема в том, что когда приложение выходит за пределы диапазона Wi-Fi-соединения без 3G и обычного подключения для передачи данных, оно зависает на некоторое время. и когда я вернулся в диапазон, он переходит в активное состояние и показывает предупреждение.

что-то не так с проверкой доступности сети?


person Neeraj Neeru    schedule 18.05.2012    source источник


Ответы (1)


это образец, который вы можете редактировать в зависимости от вашего приложения

@class Reachability;

@interface urAppDelegate : NSObject <UIApplicationDelegate> 
{

        Reachability* internetReachable;

        Reachability* hostReachable;

        BOOL   hostActive;

        BOOL   internetActive; 

}

@property (nonatomic, assign) BOOL hostActive;

@property (nonatomic, assign) BOOL internetActive;
@end

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    self.internetActive=NO;
    self.hostActive=NO;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@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];

    // now patiently wait for the notification

 [self.window makeKeyAndVisible];
    return YES;
}

-(void) checkNetworkStatus:(NSNotification *)notice{
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];

    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            self.internetActive = NO;            
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;            
            break;
        }
    }

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;            
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;
            break;
        }
    }


    if (internetActive && hostActive)
    {       
        // Net work Available.......

    }
    else
    {
        UIAlertView *netWorkAlert=[[UIAlertView alloc]initWithTitle:@"Network Connection Error" message:@"Please Check Connection" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
        [netWorkAlert show];
        [netWorkAlert release];
    }

}
person Musthafa    schedule 18.05.2012
comment
хорошо, спасибо за ваш отзыв, не могли бы вы указать, какие объекты являются этими internetReachable, hostReachable. ? это объекты для класса достижимости? - person Neeraj Neeru; 18.05.2012
comment
И internetReachable, и hostReachable являются экземплярами класса Reachability. - person Musthafa; 18.05.2012