diff --git a/SocketIO.h b/SocketIO.h index 9624629..72787a0 100755 --- a/SocketIO.h +++ b/SocketIO.h @@ -79,7 +79,7 @@ typedef enum { // heartbeat NSTimeInterval _heartbeatTimeout; - NSTimer *_timeout; + dispatch_source_t _timeout; NSMutableArray *_queue; diff --git a/SocketIO.m b/SocketIO.m index b4d8164..69d69d8 100755 --- a/SocketIO.m +++ b/SocketIO.m @@ -359,6 +359,11 @@ - (void) removeAcknowledgeForKey:(NSString *)key - (void) onTimeout { + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; + } + DEBUGLOG(@"Timed out waiting for heartbeat."); [self onDisconnect:[NSError errorWithDomain:SocketIOError code:SocketIOHeartbeatTimeout @@ -368,16 +373,29 @@ - (void) onTimeout - (void) setTimeout { DEBUGLOG(@"start/reset timeout"); - if (_timeout != nil) { - [_timeout invalidate]; - _timeout = nil; + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; } - _timeout = [NSTimer scheduledTimerWithTimeInterval:_heartbeatTimeout - target:self - selector:@selector(onTimeout) - userInfo:nil - repeats:NO]; + _timeout = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, + 0, + 0, + dispatch_get_main_queue()); + + dispatch_source_set_timer(_timeout, + dispatch_time(DISPATCH_TIME_NOW, _heartbeatTimeout * NSEC_PER_SEC), + 0, + 0); + + __weak SocketIO *weakSelf = self; + + dispatch_source_set_event_handler(_timeout, ^{ + [weakSelf onTimeout]; + }); + + dispatch_resume(_timeout); + } @@ -556,9 +574,9 @@ - (void) onDisconnect:(NSError *)error [_queue removeAllObjects]; // Kill the heartbeat timer - if (_timeout != nil) { - [_timeout invalidate]; - _timeout = nil; + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; } // Disconnect the websocket, just in case @@ -768,8 +786,10 @@ - (void) dealloc _transport = nil; - [_timeout invalidate]; - _timeout = nil; + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; + } _queue = nil; _acks = nil;