iOS 发送 Socket GCD 心跳包

项目中需要发送心跳包给服务端的需求
贴出代码望大神指点

自定义GCD定时函数

#pragma mark - GCD socket心跳事件

/**
 开启一个定时器
 
 @param target 定时器持有者
 @param timeInterval 执行间隔时间
 @param handler 重复执行事件
 */
void dispatchTimer(id target, double timeInterval,void (^handler)(dispatch_source_t timer))
{
    //获取一个低优先级的系统线程队列 DISPATCH_QUEUE_PRIORITY_LOW
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
    dispatch_source_t timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(timeInterval *NSEC_PER_SEC), 0);
    // 设置回调
    __weak __typeof(target) weaktarget  = target;
    dispatch_source_set_event_handler(timer, ^{
        if (!weaktarget)  {
            dispatch_source_cancel(timer);
        } else {
            
             /*这里是异步的根据业务需求设置主线执行回调
            dispatch_async(dispatch_get_main_queue(), ^{
                    if (handler) handler(timer);
                });
            */
            //异步回调
            if (handler) handler(timer);
        }
    });
    // 启动定时器
    dispatch_resume(timer);
}
///启用串行队列保证线程安全 不然会出现在多个子线程中操作 NSMutableDictionary 的情况
@property (nonatomic, strong) dispatch_queue_t queue;
///发送心跳包需要携带的数据 这个数据是根据服务端协好需要的数据
@property (nonatomic, strong) NSMutableDictionary *heartbeatDic;
//动态添加心跳包所需参数 使用线程同步队列保证线程安全
dispatch_sync(weakSelf.queue, ^(){
   [weakSelf.heartbeatDic setObject:@"value" forKey:@"key"];
 });

在需要启动定时器的地方调用函数

- (void)viewDidLoad {
    __weak typeof(self) weakSelf = self;
    dispatchTimer(self, 5, ^(dispatch_source_t timer) {
       //子线程发送心跳包
       dispatch_sync(weakSelf.queue, ^(){
           if(判断socket是否连接){
                //发送与服务端协同好的socket心跳包事件
            }
        });
     });
}
另外这是一个我觉得还不错的关于GCD博客

你可能感兴趣的:(iOS 发送 Socket GCD 心跳包)