The project uses a TCP long connection to data transfer with the server, on the iOS platform, due to Apple's background mechanism, there are 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
1- (void) Applicationdidenterbackground: (UIApplication *) application{2 3uiapplication* app =[UIApplication sharedapplication];4 __block uibackgroundtaskidentifier bgtask;5Bgtask = [App beginbackgroundtaskwithexpirationhandler:^{6Dispatch_async (Dispatch_get_main_queue (), ^{7 if(Bgtask! =uibackgroundtaskinvalid)8 {9Bgtask =Uibackgroundtaskinvalid;Ten } One }); A }]; -Dispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{ -Dispatch_async (Dispatch_get_main_queue (), ^{ the if(Bgtask! =uibackgroundtaskinvalid) - { -Bgtask =Uibackgroundtaskinvalid; - } + }); - }); +}
Keep long connections in IOS background