最近新开一个项目,要使用UDP通讯来和智能设备进行数据传输。大家都知道,在iOS平台上,由于苹果的后台机制,会有以下问题:
- 当程序退到后台的时候,一段时间后(大概300s)所有线程被挂起。
- 线程挂起后,系统就会回收所有的socket资源,那么socket连接就会被关闭,因此无法再进行数据的传输。
解决方案:
1.
2.在AppDelegate中:
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 2 { 3 //socket心跳包 4 NSTimer *socketTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(socketTimer) userInfo:nil repeats:YES]; 5 [[NSRunLoop mainRunLoop] addTimer:socketTimer forMode:NSRunLoopCommonModes]; 6 return YES; 7 }
1 //socket心跳包 2 - (void)socketTimer 3 { 4 [[NSNotificationCenter defaultCenter] postNotificationName:@"SOCKETTIMER" object:nil];//计时器内周期性去调用socket心跳包,保持连接。 5 }
1 - (void)applicationDidEnterBackground:(UIApplication *)application 2 { 3 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 4 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 5 6 [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];//开启后台任务 7 8 } 9 10 11 - (void)applicationWillEnterForeground:(UIApplication *)application 12 { 13 // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 14 [[UIApplication sharedApplication] endBackgroundTask:UIBackgroundTaskInvalid];//结束后台任务 15 }
注意:经测试使用以上方法在App上架时会被苹果审核组拒绝。