【问题标题】:socket connection killed after iOS app goes to backgroundiOS应用程序进入后台后套接字连接被终止
【发布时间】:2013-01-30 08:17:19
【问题描述】:

我在使用 iPhone 应用程序聊天时使用套接字连接与服务器通信。当应用程序移到后台时,我可以看到服务器能够与应用程序通信大约 5 分钟。但是在这个时间之后,套接字连接被破坏了。但是应用程序一进入后台就停止执行。为什么套接字连接保持5分钟而不是应用程序执行。苹果是否指定了保持连接的确切时间。

【问题讨论】:

  • 您的应用注册为 VoIP 应用了吗?
  • 不。它没有注册为 Voip。

标签: ios iphone multitasking


【解决方案1】:

通过在 applicationDidEnterBackground 中使用以下代码,您可以获得 600 秒(10 分钟)的最大时间:

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");
        [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
    });
  }
}

文档可以在这里找到http://disanji.net/iOS_Doc/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

我刚刚实现了 backgroundTaskIdentifier 对象并使 background_task 无效以检查时间,应用程序处于活动状态并且正在运行 600 秒。你甚至可以使用这个来获取剩余时间

NSLog(@"Time remaining: %f", application.backgroundTimeRemaining);

【讨论】:

  • 如果您的目标是 iOS 4.3 或更高版本,则不需要最初的两个 if 语句。
  • @chinta 为后台的 VoIP 使用配置套接字可以在这里找到。信息量很大wiseman-safiq.blogspot.in/2010/11/…
【解决方案2】:

来自 Apple 的IOS Programming Guide

大多数进入后台状态的应用程序被移动到 此后不久处于暂停状态。在这种状态下, 应用程序不执行任何代码,可能会从内存中删除 随时。为用户提供特定服务的应用程序 可以请求后台执行时间以提供那些 服务。

这至少解释了应用程序停止执行的原因。为什么您的服务器仍然能够与您的应用程序通信 5 分钟可能是因为您设置了一个额外的超时时间并且没有在您的应用程序进入后台时明确关闭套接字连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多