DEMO :https://github.com/ZackKingS/AsyncSocketDemo
一.引入 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鏈接成功,成功之后就可以定時去發(fā)送消息了,為了能在鎖屏情況下發(fā)出發(fā)出消息报腔,寫了好幾個定時器
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
NSLog(@"didConnectToHost");
//////**** 1 ****////
//連上之后可以每隔30s發(fā)送一次心跳包
// 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]);
//
// //心跳包的內(nèi)容是前后端自定義的
// NSString *heart = @"Damon";
// NSData *data= [heart dataUsingEncoding:NSUTF8StringEncoding];
// [self.myTcpSocket writeData:data withTimeout:10.0f tag:0];
// });
//
// //4.啟動執(zhí)行
// dispatch_resume(timer);
//
// //5.用強(qiáng)指針引用 定時器(保證其不被銷毀)
// 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); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結(jié)束株搔,關(guān)閉
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//定時結(jié)束后的UI處理
});
}else{
//心跳包的內(nèi)容是前后端自定義的
NSString *heart = @"Damon";
NSData *data= [heart dataUsingEncoding:NSUTF8StringEncoding];
[self.myTcpSocket writeData:data withTimeout:10.0f tag:timeout];
NSLog(@"時間 = %d",timeout);
NSString *strTime = [NSString stringWithFormat:@"發(fā)送驗(yàn)證碼(%dS)",timeout];
NSLog(@"strTime = %@",strTime);
dispatch_async(dispatch_get_main_queue(), ^{
//定時過程中的UI處理
});
timeout--;
}
});
dispatch_resume(_timer);
}
4.向服務(wù)器發(fā)送完數(shù)據(jù)之后回調(diào)
//向服務(wù)器發(fā)送完數(shù)據(jù)之后回調(diào)
- (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]; //注入系統(tǒng)
[self playVibration];
[self playNewMessageSound];
//后臺播放聲音
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
}