iOS开发之后台保持socket的连接

最近新开一个项目,要使用UDP通讯来和智能设备进行数据传输。大家都知道,在iOS平台上,由于苹果的后台机制,会有以下问题:

  1. 当程序退到后台的时候,一段时间后(大概300s)所有线程被挂起。
  2. 线程挂起后,系统就会回收所有的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上架时会被苹果审核组拒绝。

 

转载于:https://www.cnblogs.com/liuhuakun/p/6704762.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值