2013-04-17 117 views
0

我从applicationDidBecomeActive方法的服务器获取数据。当网络连接速度太慢时,应用程序不断崩溃。我不知道如何处理这个问题。任何帮助将不胜感激。提前感谢。应用程序在Internet上崩溃

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]; 

      } 
+0

发布您的代码? – Ramz

+0

我发布了我的代码。 – user2134883

+0

崩溃说什么? –

回答

1

它可能崩溃,因为连接已经开始下载,但它并没有因此结束,允许编译器通过您的if语句,这将不可避免地给一个零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之前没有完成而导致应用程序挂起。

+0

可以给你dispatch_async语句的例子吗? – user2134883

+0

@ user2134883在stackoverflow上有很多例子。这里是[一](http://stackoverflow.com/a/8636840/1576979)。请记住,在后台线程中,您可以通过使用dispatch_async(dispatch_get_main_queue()^ {//您的代码在这里});''切换到主线程来执行GUI操作或其他所需的东西。 – tolgamorf

1

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

仅用于调试目的,请在您的FirstViewControllerviewDidAppear方法中尝试使用相同的代码。它应该在那里工作得很好。如果是这样,你需要改变你的呼叫到其他地方(也最好在一些后台线程或异步)。

编辑:虽然,如果它在其他地方工作,你需要改变调用为后台线程上的异步或更平滑的用户体验。

+0

我可以在performSelectorInBackGround方法中运行整个代码吗? – user2134883

+0

是的,你可以。 **一个建议:**使用简单但效率不高的解决方案可能会在不久的将来失败。至少,它们不可扩展。 – viral