在iOS中保持应用程序空闲一段时间后,SRWebsocket连接将自动closures

我正在使用SRWebSocket在iOS中打开一个websocket连接。 但是,如果我有时保持应用程序空闲,连接将自动closures。 之后,当我试图发送任何数据,websocket连接失败。

无论如何保持websocket连接活着,直到我手动断开?

我们需要间歇地ping服务器(在我的情况下,我每隔30秒就会这样做),以避免closures服务器端的连接。

- (void)webSocketDidOpen:(SRWebSocket *)webSocket; { NSLog(@"Websocket Connected"); // Sending autoping to server [self startConnectionCheckTimer]; } // Checking for WSconnection by Sending Scheduled Ping - (void)startConnectionCheckTimer { if (!_timer) { _timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(sendPing:) userInfo:nil repeats:YES]; } } - (void)stopConnectionCheckTimer { if ([_timer isValid]) { [_timer invalidate]; } _timer = nil; } - (void)sendPing:(id)sender { [_webSocket sendPing:nil]; } 

其中, _webSocket是我的SRWebSocket对象, _timer是NSTimer的一个对象。

当应用程序闲置或应用程序进入后台时,Web Socket会断开连接。 你可以尝试使用这个:
[UIApplication sharedApplication] .idleTimerDisabled = YES

如果您的应用程序正在运行,使用此function将禁用iPhone的提供。