应用程序在慢速Internet连接上崩溃

时间:2013-04-17 06:37:49

标签: objective-c

我在applicationDidBecomeActive方法中从服务器获取数据。当网络连接速度太慢时,应用程序会继续崩溃。我不知道如何处理这个问题。任何帮助都会受到赞赏。谢谢提前。

NSString *post =[[NSString alloc] initWithFormat:@"=%@@=%@",myString,acMobileno];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:///?data=%@&no=%@",myString,acMobileno]];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSError *error1 = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error1];
    NSString *string;
    if ([response statusCode] >=200 && [response statusCode] <300)
            {
            string = [[NSString alloc] initWithData:urlData encoding:NSMacOSRomanStringEncoding];

            }

2 个答案:

答案 0 :(得分:1)

它可能崩溃,因为连接已经开始下载,但它还没有完成,因此允许编译器传递你的if语句,这将不可避免地给出一个nil urlData参数。

要解决此问题,您应该检查是否存在错误,然后检查下载的响应标头。此外,我建议在后台线程上运行此操作,以免它阻止用户体验 - 此时,应用程序将根据文件大小和用户的推迟启动下载速度。

NSError *error1 = nil;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error1];
NSString *string = nil;
if (error != nil && ([response statusCode] >=200 && [response statusCode] <300)){ 
    string = [[NSString alloc] initWithData:urlData encoding:NSMacOSRomanStringEncoding];
}
else {
    NSLog(@"received error: %@", error.localizedDescription);
}

对于后台线程,请在dispatch_async语句中运行上述代码,或使用-sendAsynchronousRequest:代替-sendSynchronousRequest

或者,正如@Viral所说,请求可能花费的时间太长,并且由于在应该加载UI之前未完成同步请求,应用程序会挂起。

答案 1 :(得分:1)

最有可能的是,这是由于Application的委托方法中的同步调用。加载UI需要花费太多时间(因为互联网连接很慢而你在主线程上调用web服务);因此操作系统认为您的应用程序由于无响应的用户界面而挂起并导致应用程序本身崩溃。

仅出于调试目的,请在FirstViewController的{​​{1}}方法中尝试使用相同的代码。它应该在那里工作正常。如果是这样,您需要将呼叫更改为其他地方(也可以,最好是在某些后台线程中,或者Async)。

编辑但是,如果它在其他地方有效,则需要在后台线程上将调用更改为Async OR,以获得更顺畅的用户体验。