iOS后台如何保持socket长连接和数据传输
本文转载至 http://blog.csdn.net/zhangkongzhongyun/article/details/38678137
当程序退到后台的时候,所有线程被挂起,系统会回收所有的socket资源,那么socket连接就会被关闭,因此无法再进行数据的传输:
解决方法:
通过设置以下属性可以保持socket连接和数据的继续传输
1.需要在Info.plist文件中添加UIBackgroundModes中的VOIP键值;
2.设置流属性
CFReadStreamRef和CFWriteStreamRef通过如下方法设置kCFStreamNetworkServiceType属性为kCFStreamNetworkServiceTypeVoIP;
CFReadStreamSetProperty(theReadStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
CFWriteStreamSetProperty(theWriteStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
NSInputStream 和NSOutputStream通过如下方法设置NSStreamNetworkServiceType属性为NSStreamNetworkServiceTypeVoIP;
[self.stream setProperty: NSStreamNetworkServiceTypeVoIP forKey:NSStreamNetworkServiceType];
3.这里有一个问题,就是客户端是通过心跳来和服务端保持连接,心跳是由定时器触发的,当我退到后台以后,定时器方法被挂起,那么通过如下设置来在后台运行定时器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
-
( void )applicationDidEnterBackground:(UIApplication
*)application{ UIApplication*
app = [UIApplication sharedApplication]; __block
UIBackgroundTaskIdentifier bgTask; bgTask
= [app beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(),
^{ if
(bgTask != UIBackgroundTaskInvalid) { bgTask
= UIBackgroundTaskInvalid; } }); }]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0 ),
^{ dispatch_async(dispatch_get_main_queue(),
^{ if
(bgTask != UIBackgroundTaskInvalid) { bgTask
= UIBackgroundTaskInvalid; } }); }); } |