我正在使用SocketRocket,但我无法在后台传递消息。当我再次打开应用程序时,它会恢复连接(不重新连接),并且所有消息都会立即进入。
这是我的连接代码:
- (void)_reconnect {
_websocket.delegate = nil;
[_websocket close];
NSString *host = @"ws://localhost:3030/primus";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:host]];
[request setValue:[NSString stringWithFormat:@"<%@>", apiKey] forHTTPHeaderField:@"Authentication"];
_websocket = [[SRWebSocket alloc] initWithURLRequest:request];
[_websocket setDelegateOperationQueue:[NSOperationQueue new]];
_websocket.delegate = self;
[_websocket open];
if (DEBUG) {
NSLog(@"Using: %@", host);
}
}
我也试过没有
[_websocket setDelegateOperationQueue:[NSOperationQueue new]];
行,但这对任何事都没有帮助。
你知道发生了什么吗?
谢谢!
答案 0 :(得分:1)
我遇到同样的问题,但仍然没有正确答案。
如果主线程被冻结(当应用程序在后台时),Socket Rocket似乎停止向指定的SRDelegate发送消息。
我甚至尝试过另一种方法但没有成功:
[_webSocket setDelegateDispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];
但是,我确实找到了解决方法,以防止主线解冻。 这不是很好,特别是因为它会导致电池耗尽,但它可以工作。
我注意到如果你的应用程序在后台有位置更新,那么WebSocket继续正常运行。
要启动位置服务,您可以在applicationDidEnterBackground上执行以下操作:
CLLocationManager* locationManager = [[CLLocationManager alloc] init];
[locationManager startUpdatingLocation];
返回时,您可以通过调用applicationWillEnterForeground上的以下代码来阻止它们:
[locationManger stopUpdatingLocation];
Ofc你需要保留对locationManager的强引用,而不仅仅是在范围内。
这不是推荐的解决方案,但如果没有任何效果......
答案 1 :(得分:0)
你刚才说过同样的问题。 新版插座火箭可以帮助解决这个问题。 现在支持一些后台模式。 See source code
我还没有测试过,但我确信这应该有所帮助(让事情更接近最终解决方案)。