【问题标题】:iOS app freeze during checking internet connection在检查互联网连接期间 iOS 应用程序冻结
【发布时间】:2013-06-25 09:26:57
【问题描述】:

在我的初始视图控制器的 viewDidLoad 中,我检查互联网连接,如果可用,则开始一些下载过程。

如果没有任何连接(WiFi 或移动)或互联网可用 - 一切正常。 但是,如果设备在没有互联网的情况下连接到 WiFi,应用程序会冻结。

if ([self isInternetAvail]) {
    [[Download sharedDownload] startUpdateProcessWithIndicatorInViewController:self];
}

这是函数:

- (BOOL)isInternetAvail
{
    NSString *hostName = @"google.com";
    Reachability *hostReach = [Reachability reachabilityWithHostName:hostName];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    if (netStatus == NotReachable) {
       return NO;
    } else {
       return YES;
    }
}

应用程序在此行冻结:

NetworkStatus netStatus = [hostReach currentReachabilityStatus];

检查互联网连接的更正确方法是使用NSNotificationCenter,但在这种情况下:

1)didFinishLaunchingWithOptions 中:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(networkStateChanged:)
                                             name:kReachabilityChangedNotification
                                           object:nil];

hostReach = [Reachability reachabilityWithHostName:@"www.google.com"];
[hostReach startNotifier];
[self updateInternetAvailWithReachability: hostReach];

其他方法:

- (void)updateInternetAvailWithReachability: (Reachability *)curReach
{
    netStatus = [curReach currentReachabilityStatus];  
}

- (void)networkStateChanged:(NSNotification *)notification
{
    Reachability *curReach = [notification object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInternetAvailWithReachability:curReach];
}

2) 在我的初始视图控制器的 viewDidLoad 中:

AppDelegate *d = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (!d.netStatus == NotReachable) {
   [[Download sharedDownload] startUpdateProcessWithIndicatorInViewController:self];
}

在这一步我得到 NotReachable 并且无法开始下载

3) NSNotificationCenter 告诉我“互联网可用”

我需要一些关于如何准备的建议。

【问题讨论】:

    标签: ios reachability


    【解决方案1】:

    当您向服务器请求时,请减少 timeoutInterval 选项并将其设置为最小,这样请求就不会等待很长时间才能获得响应,通过这种方式您可以减少冻结应用程序的时间。如果你想完全摆脱它,那么你应该在另一个线程上运行所有进程以进行网络检查,可能在后台线程中。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 2014-05-21
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多