当应用程序进入后台时如何保持NSTimer?

我在这里,因为没有find我的问题的任何解决scheme:(

我正在做一个简单的应用程序,我必须发送(通过套接字)一些信息到服务器(如GPS升/ L,准确性,电池电量等)。

当应用程序在前台时,当前的代码工作正常。

myTimer = [NSTimer scheduledTimerWithTimeInterval: 2.0 target:self selector: @selector(sendPosToServer:) userInfo:nil repeats: YES]; myTimer2 = [NSTimer scheduledTimerWithTimeInterval: 3.0 target:self selector: @selector(sendBatteryToServer:) userInfo:nil repeats: YES]; myTimer3 = [NSTimer scheduledTimerWithTimeInterval: 5.0 target:self selector: @selector(sendResToServer:) userInfo:nil repeats: YES]; myTimer4 = [NSTimer scheduledTimerWithTimeInterval: 5.0 target:self selector: @selector(sendQResToServer:) userInfo:nil repeats: YES]; myTimer5 = [NSTimer scheduledTimerWithTimeInterval: 3.0 target:self selector: @selector(sendPrecisionToServer:) userInfo:nil repeats: YES]; 

所有的方法都被调用。

但是,当应用程序进入后台,所有计时器都是无效的…我读过iOS自动停止计时器..我正在寻找一种方法来调用方法和应用程序在后台时发送数据..

我需要你的帮助 :)

谢谢大家 !!

您需要阅读关于如何在后台运行任务的指南:

后台执行和多任务处理

这是我的applicationDidEnterBackground我的一个应用程序。 当我把它放到后台时,它会做一些磁盘caching维护:

 - (void)applicationDidEnterBackground:(UIApplication *)application { //As we are going into the background, I want to start a background task to clean up the disk caches if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking IE 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 //I do what i need to do here.... synchronously... [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 }); } } 

}

从苹果文档:

实现长时间运行的后台任务对于需要更多执行时间来执行的任务,您必须请求特定的权限才能在后台运行它们而不被挂起。 在iOS中,只有特定的应用程序types才能在后台运行:

  • 在后台播放可听内容的应用,例如音乐播放器应用
  • 随时向用户通知其位置的应用,例如导航应用
  • 支持网际协议语音(VoIP)的应用
  • 报亭应用程序,需要下载和处理新的内容
  • 从外部附件获得定期更新的应用程序

除非你的应用程序属于这些类别之一(听起来好像没有),否则在后台运行将无法运行。

iOS应用程序编程指南”列出了允许您的应用程序在后台保持活动状态的活动。 如果您计划通过app store分发您的应用,则您的应用必须执行其中一项列出的活动。 如果你只是为自己写点东西,那么你也许可以在允许的活动之一上搭载你的function。