This article reprinted to http://blog.csdn.net/zhangkongzhongyun/article/details/38678137A TCP long connection is used in the project to transfer data to and from the server,Iosplatform, due to Apple's background mechanism, there will be the following issues:
When the program is back in the background, all the threads are suspended and the system reclaims all the socket resources, then the socket connection is closed and the data can no longer be transferred:
Workaround:
You can maintain the socket connection and the continuation of data transfer by setting the following properties
1. Need to add the VoIP key value in the Uibackgroundmodes in the Info.plist file;
2. Set Flow properties
Cfreadstreamref and Cfwritestreamref set the Kcfstreamnetworkservicetype property to Kcfstreamnetworkservicetypevoip by the following method;
Cfreadstreamsetproperty (Thereadstream, Kcfstreamnetworkservicetype, Kcfstreamnetworkservicetypevoip);
Cfwritestreamsetproperty (Thewritestream, Kcfstreamnetworkservicetype, Kcfstreamnetworkservicetypevoip);
Nsinputstream and Nsoutputstream set the Nsstreamnetworkservicetype property to Nsstreamnetworkservicetypevoip by the following method;
[Self.stream Setproperty:nsstreamnetworkservicetypevoip Forkey:nsstreamnetworkservicetype];
3. Here is a problem, that is, the client is through the heartbeat and the server to maintain the connection, the heartbeat is triggered by the timer, when I retire to the background, the timer method is suspended, then the following settings to run the timer in the background
?
123456789101112131415161718192021 |
- (
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;
}
});
});
}
|
How to keep the socket long connection and data transfer in iOS background