iOS开发-知识合集程序员半栈工程师

iOS CocoaAsyncSocket长连接DEMO(可以在锁

2017-09-07  本文已影响357人  曾柏超

DEMO :https://github.com/ZackKingS/AsyncSocketDemo

WechatIMG2237.jpeg

一.引入 CocoaAsyncSocket

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

target 'AsyncSocketDemo' do
  # Uncomment this line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!
  pod 'CocoaAsyncSocket'  
  pod 'Masonry'
  # Pods for AsyncSocketDemo
end

二.TCP开始建立长连接

-(void)tcpTest:(UIButton*)sender
{
    NSLog(@"tcpTest");
    self.myTcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self tcpConnetwithData:[NSString stringWithFormat:@"%d",(int)sender.tag]];
    [self.mySocketArray addObject: self.myTcpSocket];
}

-(void)tcpConnetwithData:(NSString*)userData
{
    [self.myTcpSocket setUserData:userData];
    
    NSError *error = nil;
    if (![ self.myTcpSocket connectToHost:@"hudongdong.com" onPort:80 withTimeout:2.0f error:&error]) {
        NSLog(@"error:%@",error);
    }

}

3. didConnectToHost链接成功,成功之后就可以定时去发送消息了,为了能在锁屏情况下发出发出消息,写了好几个定时器

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"didConnectToHost");
    
    //////****  1      ****////
    //连上之后可以每隔30s发送一次心跳包
//        self.mytime =[NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(heartbeatFunc) userInfo:nil repeats:YES];
//        [self.mytime fire];
    
    
      //////****  2      ****////
//    NSRunLoop *currentRunloop = [NSRunLoop currentRunLoop];
//    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(runn) userInfo:nil repeats:YES];
//    [currentRunloop run];
    
    
    
      //////****  3      ****////
    
  
//    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
//    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
//    dispatch_source_set_event_handler(timer, ^{
//        NSLog(@"GCD---%@",[NSThread currentThread]);
//        
//        //心跳包的内容是前后端自定义的
//        NSString *heart = @"Damon";
//        NSData *data= [heart dataUsingEncoding:NSUTF8StringEncoding];
//        [self.myTcpSocket writeData:data withTimeout:10.0f tag:0];
//    });
//    
//    //4.启动执行
//    dispatch_resume(timer);
//    
//    //5.用强指针引用 定时器(保证其不被销毁)
//    self.timer = timer;
    
    
    
      //////****  4     ****////
    
    [self startTime];
    
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
    
    
    
    
    
}




- (void)startTime{
  
    
    __block int timeout = 60; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),3.0*NSEC_PER_SEC, 0); //每秒执行
   
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束,关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //定时结束后的UI处理
            });
        }else{
            
            //心跳包的内容是前后端自定义的
            NSString *heart = @"Damon";
            NSData *data= [heart dataUsingEncoding:NSUTF8StringEncoding];
            [self.myTcpSocket writeData:data withTimeout:10.0f tag:timeout];
            
            
            NSLog(@"时间 = %d",timeout);
            NSString *strTime = [NSString stringWithFormat:@"发送验证码(%dS)",timeout];
            NSLog(@"strTime = %@",strTime);
            dispatch_async(dispatch_get_main_queue(), ^{
                //定时过程中的UI处理
            });
            
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
}

4.向服务器发送完数据之后回调

//向服务器发送完数据之后回调
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"have send");
    
    //本地推送
    [self run:(long)tag];
    
    if (tag == 1) {
        NSLog(@"first send");
    }
    else if (tag ==2){
        NSLog(@"second send");
    }
}






-(void)run:(long)tag
{
    
    
    
    
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];  //30秒后推送
    
    //        localNotification.fireDate = [NSDate date];  //30秒后推送
    localNotification.timeZone = [NSTimeZone localTimeZone];
    localNotification.userInfo = @{
                                   @"name":@"the Name",
                                   @"id":@"0",
                                   };
    localNotification.alertBody = @"alertBody";
    localNotification.alertTitle = [NSString stringWithFormat:@"%ld",tag];
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; //注入系统
    
    
    
    [self playVibration];
    
    [self playNewMessageSound];
    
    //后台播放声音
    
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    
    
}





上一篇 下一篇

猜你喜欢

热点阅读