当app进入后台时杀死连接

时间:2013-04-11 03:43:09

标签: ios uiwebview nsurlconnection

我的iOS(版本5-6.2)应用程序中有很多UIWebView。当应用程序进入后台时,一切都顺利进行。但是,当它在大约10分钟后进入前台时,我收到一条错误消息,或者说“无法找到有效的主机名”或“连接超时”。

我假设这与我在调用applicationDidEnterBackground:时对这些UIWebViews缺乏操作有关。我怎么能杀死这些连接?我知道我需要使用通知中心,但与之前的问题不同,我使用的是ARC,因此没有dealloc方法可以删除观察者。

修改

以下是我的一些网络视图代码: WebViewController.m

NSURLRequest *request = [NSURLRequest requestWithURL:urlToLoad  cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];
// load the request to the UIWebView _webView
[_webView loadRequest:request];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:TRUE];
if (connection) {
    receivedData = [NSMutableData data];
}

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

如果您正在执行一些重要或珍贵的下载或上传操作并且您的应用程序进入后台,在这种情况下,您可以请求从“IOS”完成工作的额外时间,它会在您的应用程序中额外花费10分钟来完成处于后台模式。

但请记住,您的操作必须重要且可接受,否则您的应用可能会被Apple Review Process拒绝。

有关详细信息,请参阅Apple文档Background Execution and Multitasking

现在,结束我的点和时间进行一些操作,在后台继续你的任务,你可以使用以下方法执行,无需管理Application Delegate方法。只需使用以下代码段,不要使用委托进行下载或上传。

if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
    if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
        UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
        __block UIBackgroundTaskIdentifier background_task; //Create a task object
        background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
            [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
            background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
            //System will be shutting down the app at any point in time now
        }];
        //Background tasks require you to use asyncrous tasks
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //Perform your tasks that your application requires
            NSLog(@"\n\nRunning in the background!\n\n");

            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"YOUR HOST URL"]];
            NSURLResponse *response = nil;
            NSError *requestError = nil;
            NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];

            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            NSLog(@"ResponseString:%@",responseString);

            [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
            background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
        });
    }
}