SRWebsocket connection is closing automatically after keeping app idle for sometime in iOS

后端 未结 2 940
庸人自扰
庸人自扰 2021-01-20 14:28

I am using SRWebSocket to open a websocket connection in iOS. But if I am keeping the application idle for sometimes, the connection is closing automatically. After that whe

相关标签:
2条回答
  • 2021-01-20 14:57

    Web Socket gets disconnected when the app is kept idle or when the app goes in background. You can try using this:
    [UIApplication sharedApplication].idleTimerDisabled = YES

    Using this, will disable the provision of iPhone to be idle if your app is running.

    0 讨论(0)
  • 2021-01-20 15:23

    We need to ping the server intermittently (In my case, I do this in every 30 seconds), for avoiding to close the connection from the server side.

    - (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];
    }
    

    Where, _webSocket is my SRWebSocket object, _timer is an object of NSTimer.

    0 讨论(0)
提交回复
热议问题