chenqiyang
2021-08-27 6a63c4281fbe7e17103115320cd276397d733081
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//
//  HDLLinphoneIntercomVC.m
//  VoipTest
//
//  Created by 陈嘉乐 on 2021/8/2.
//
 
#import "HDLLinphoneIntercomVC.h"
#import "HDLLinphoneUtlis.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <AudioToolbox/AudioToolbox.h>
 
#import "HDLLinphoneManager.h"
 
#import "HDLLinPhoneSDK-Swift.h"
@interface HDLLinphoneIntercomVC ()
 
@property (nonatomic,strong) UIImage               *snapImage; //截图
 
@property (nonatomic, strong) UIButton *backButton;  //返回按钮
@property (nonatomic, strong) UILabel *titleUILabel;  //标题
@property (nonatomic, strong) UIView *centerView;  //内容背景View
@property (nonatomic, strong) UIView *videoView;
@property (nonatomic, strong) UIView *unlockView;
@property (nonatomic, strong) UIButton *screenshotImgBtn;  //截图
@property (nonatomic, strong) UIButton *unlockImgBtn;  //开锁
@property (nonatomic, strong) UIButton *hangUpImgBtn;//挂断按钮
@property (nonatomic, strong) UIButton *hangUpTextBtn;
@property (nonatomic, strong) UIButton *answerImgBtn;//接听按钮
@property (nonatomic, strong) UIButton *answerTextBtn;
@property (nonatomic, strong) UIButton *calltimeBtn; //通话时间按钮
//定时器
@property (nonatomic,strong) dispatch_source_t countdownTimer;
@property (nonatomic,strong) dispatch_source_t openDoorTimer;
@property (nonatomic, assign) int openDoorTimeout;
@property (nonatomic, assign) int callTimeout;
@end
 
@implementation HDLLinphoneIntercomVC{
    BOOL isAnswer;//是否已经点击接听过了
    
    NSString * tipStr;
    NSString * okStr;
    NSString * saveToTheAlbumsStr;
    NSString * operationFailedStr;
    NSString * refuseStr;
    NSString * answerStr;
    NSString * unlockSuccessfullyStr;
    NSString * callingStr;
    NSString * hangUpStr;
    NSString * endOfCallStr;
    //    int openDoorTimeout;
    //全局变量
    SystemSoundID sound;
    CGFloat Height66;
    bool isShowErrorAlert; //是否已经弹窗过错误提示标记,根据情况使用
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    Height66 = GetRealWidth(66);
    
    [self initLlanguage];
    [self initTopBarView];
    [self initCentetView];
    [self initData];
    [self initESVideo];
    //开始反呼
    [self StartReverseCall];
    [self ShowCalltimeBtn:callingStr];
    //注册开锁成功监听
    [self addOpenSuccessAction];
    
    if (self.titleName&&self.titleName.length!=0) {
        self.titleUILabel.text=self.titleName;
    }
//    self.titleUILabel.text=self.titleName;
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(registrationUpdate:)
                                               name:@"LinphoneRegistrationUpdate"
                                             object:nil];
 
}
 
- (void)registrationUpdate:(NSNotification *)notif {
    int state = [[notif.userInfo objectForKey:@"state"] intValue];
    if(state==11){//挂断了
        NSLog(@"挂断或出错了");
        [self showUIAlertViewWithBack:@"通话结束"];
        
    }
}
 
-(void)initLlanguage{
    NSString *languageName = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0];
    
    // 简体中文
    if ([languageName rangeOfString:@"zh-Hans"].location != NSNotFound) {
        tipStr = @"提示";
        okStr = @"确认";
        saveToTheAlbumsStr = @"已保存至手机相册.";
        operationFailedStr = @"操作失败";
        refuseStr = @"拒绝";
        answerStr = @"接听";
        hangUpStr = @"挂断";
        unlockSuccessfullyStr = @"开锁成功";
        callingStr = @"来电中...";
        endOfCallStr = @"通话结束";
    }else{
        tipStr = @"Prompt";
        okStr = @"OK";
        saveToTheAlbumsStr = @"Saved to the albums.";
        operationFailedStr = @"Operation failed.";
        refuseStr = @"Refuse";
        answerStr = @"Answer";
        hangUpStr = @"Hang up";
        unlockSuccessfullyStr = @"Unlock successfully";
        callingStr = @"Incoming call";
        endOfCallStr = @"End of call";
        
    }
}
 
- (void)initTopBarView {
    UIView *TopView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, APP_TOP_BAR_HEIGHT)];
    TopView.backgroundColor = HEXCOLORA(0xF7F7F7,1.0);
    //    [TopView addSubview:self.backButton];//隐藏返回按钮
    [TopView addSubview:self.titleUILabel];
    [self.view addSubview:TopView];
    TopView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.25].CGColor;
    TopView.layer.shadowOffset = CGSizeMake(0,0.5);
    TopView.layer.shadowOpacity = 1;
    TopView.layer.shadowRadius = 0;
}
 
- (UIButton *)backButton{
    if (_backButton == nil) {
        _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, APP_STATUS_BAR_HEIGHT, 44, 44)];
        [_backButton setImage:[UIImage imageNamed:@"ic_esvideo_on_back"] forState:UIControlStateNormal];
        _backButton.imageEdgeInsets = UIEdgeInsetsMake(12,12,12,12);
        [_backButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}
 
-(void)backAction{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    //    [self dismissViewControllerAnimated:YES completion:NULL];
    
}
 
-(UILabel *)titleUILabel{
    if (_titleUILabel == Nil) {
        _titleUILabel = [[UILabel alloc] initWithFrame:CGRectMake(90, APP_STATUS_BAR_HEIGHT, self.view.frame.size.width - 180, 44)];
        _titleUILabel.font = [UIFont fontWithName:APP_UIFont_BOLD size:18.0];
        _titleUILabel.textColor = TextColor;
        _titleUILabel.text = @"";
        _titleUILabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleUILabel;
}
 
- (void)initCentetView {
    [self.view addSubview:self.centerView];
    //    [self.centerView addSubview:self.collectButton];
    [self.centerView addSubview:self.videoView];
    [self.centerView addSubview:self.unlockView];
    [self.unlockView addSubview:self.screenshotImgBtn];
    [self.unlockView addSubview:self.unlockImgBtn];
    [self.centerView addSubview:self.hangUpImgBtn];
    [self.centerView addSubview:self.hangUpTextBtn];
    [self.centerView addSubview:self.answerImgBtn];
    [self.centerView addSubview:self.answerTextBtn];
    [self.centerView addSubview:self.calltimeBtn];
}
 
- (UIView *)centerView{
    if (_centerView == nil) {
        _centerView = [[UIButton alloc] initWithFrame:CGRectMake(0, APP_TOP_BAR_HEIGHT, APP_SCREEN_WIDTH, APP_VISIBLE_HEIGHT)];
        _centerView.backgroundColor = UIColor.whiteColor;
    }
    return _centerView;
}
 
//-(void)setRadiusWithView:(UIView *)mView{
//    //顶部圆角
//    UIRectCorner corners = UIRectCornerTopLeft | UIRectCornerTopRight;
//    if (@available(iOS 11.0, *)) {
//        mView.layer.cornerRadius = 20;
//        mView.layer.maskedCorners =  (CACornerMask)corners;
//    }else{
//        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:mView.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(20,20)];
//        //创建 layer
//        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//        maskLayer.frame = mView.bounds;
//        //赋值
//        maskLayer.path = maskPath.CGPath;
//        mView.layer.mask = maskLayer;
//    }
//}
 
-(UIView *)videoView{
    if (_videoView == Nil) {
        _videoView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, GetRealWidth(210))];
        _videoView.backgroundColor = UIColor.lightGrayColor;
        _videoView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.25].CGColor;
        _videoView.layer.shadowOffset = CGSizeMake(0,0.5);
        _videoView.layer.shadowOpacity = 1;
        _videoView.layer.shadowRadius = 0;
    }
    return _videoView;
}
 
 
- (UIView *)unlockView{
    if (_unlockView == nil) {
        _unlockView = [[UIView alloc] initWithFrame:CGRectMake(0, GetRealWidth(210), APP_SCREEN_WIDTH, GetRealWidth(72))];
        _unlockView.backgroundColor = HEXCOLORA(0x232323, 1.0);
        _unlockView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
        _unlockView.layer.shadowColor = [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:0.4].CGColor;
        _unlockView.layer.shadowOffset = CGSizeMake(0,0.5);
        _unlockView.layer.shadowOpacity = 1;
        _unlockView.layer.shadowRadius = 0;
    }
    return _unlockView;
}
//截图按钮
- (UIButton *)screenshotImgBtn{
    if (_screenshotImgBtn == nil) {
        _screenshotImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(44), GetRealWidth(44))];
        [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_unselect"] forState:UIControlStateNormal];
        //        [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_select"] forState:UIControlStateSelected];
        [_screenshotImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_screenshotImgBtn addTarget:self action:@selector(screenshotAction) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
        [_screenshotImgBtn addTarget:self action:@selector(screenshotDownAction) forControlEvents:UIControlEventTouchDown];
        _screenshotImgBtn.adjustsImageWhenHighlighted = NO;
        _screenshotImgBtn.center = CGPointMake(APP_SCREEN_WIDTH/4, GetRealWidth(38));
    }
    return _screenshotImgBtn;
}
//截图按钮按下事件
-(void)screenshotDownAction{
    [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_select"] forState:UIControlStateNormal];
}
//截图按钮抬起事件
-(void)screenshotAction{
    [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_unselect"] forState:UIControlStateNormal];
    
    //截图
    
}
 
- (UIButton *)unlockImgBtn{
    if (_unlockImgBtn == nil) {
        _unlockImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0, GetRealWidth(44), GetRealWidth(44))];
        [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_unselect"] forState:UIControlStateNormal];
        //        [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_select"] forState:UIControlStateSelected];
        [_unlockImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_unlockImgBtn addTarget:self action:@selector(unlockAction) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
        [_unlockImgBtn addTarget:self action:@selector(unlockDownAction) forControlEvents:UIControlEventTouchDown];
        _unlockImgBtn.adjustsImageWhenHighlighted = NO;
        _unlockImgBtn.center = CGPointMake((APP_SCREEN_WIDTH/4) * 3, GetRealWidth(38));
    }
    return _unlockImgBtn;
}
 
-(void)unlockDownAction{
    [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_select"] forState:UIControlStateNormal];
    
}
//点击解锁
-(void)unlockAction{
    [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_unselect"] forState:UIControlStateNormal];
    //开锁
    if(self.hdlLinphoneCallDelegate != NULL){
        [self.hdlLinphoneCallDelegate onUnlockAction];
    }
}
 
#pragma 挂断和开锁
//挂断 图标按钮
- (UIButton *)hangUpImgBtn{
    if (_hangUpImgBtn == nil) {
        _hangUpImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Height66, Height66)];
        [_hangUpImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_hangup"] forState:UIControlStateNormal];
        //        [_hangUpImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_hangup"] forState:UIControlStateSelected];
        [_hangUpImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_hangUpImgBtn addTarget:self action:@selector(hangUpAction) forControlEvents:UIControlEventTouchUpInside];
        _hangUpImgBtn.center = CGPointMake(APP_SCREEN_WIDTH/4, GetRealHeight(452) + Height66/2);
    }
    return _hangUpImgBtn;
}
 
//挂断按钮事件
-(void)hangUpAction{
    //1.回调事件
    if(self.hdlLinphoneCallDelegate != NULL){
        if(isAnswer){
            //如果之前已经接听了,回调是挂断
            [self.hdlLinphoneCallDelegate onHangUpAction:_callTimeout];
        }else{
            //如果之前没接听了,回调是拒接
            [self.hdlLinphoneCallDelegate onRejectCallAction];
        }
    }
    //2.页面关闭
    [self backAction];
}
//拒接 文本按钮
- (UIButton *)hangUpTextBtn{
    if (_hangUpTextBtn == nil) {
        _hangUpTextBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(100), GetRealWidth(20))];
        [_hangUpTextBtn setTitle:@"拒绝" forState:UIControlStateNormal];
        _hangUpTextBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        _hangUpTextBtn.titleLabel.font = [UIFont fontWithName:APP_UIFont size:14.0];
        [_hangUpTextBtn setTitleColor:TextColor forState:UIControlStateNormal];
        [_hangUpTextBtn setTitleColor:TextSelectColor forState:UIControlStateSelected];
        [_hangUpTextBtn addTarget:self action:@selector(screenshotAction) forControlEvents:UIControlEventTouchUpInside];
        _hangUpTextBtn.center = CGPointMake(_hangUpImgBtn.center.x, GetRealHeight(530));
        
    }
    return _hangUpTextBtn;
}
//接听 图标按钮
- (UIButton *)answerImgBtn{
    if (_answerImgBtn == nil) {
        _answerImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Height66, Height66)];
        [_answerImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_answer"] forState:UIControlStateNormal];
        //        [_answerImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_answer"] forState:UIControlStateSelected];
        [_answerImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_answerImgBtn addTarget:self action:@selector(answerIAction) forControlEvents:UIControlEventTouchUpInside];
        
        _answerImgBtn.center = CGPointMake((APP_SCREEN_WIDTH/4)*3, GetRealHeight(452) + Height66/2);
    }
    return _answerImgBtn;
}
//点击接听事件
-(void)answerIAction{
    [self stopPlaySystemSound];
    
//    [[HDLCallManager instance] acceptCallByCallID:self.CallId hasVideo:self.hasVideo];
    [[HDLLinphoneManager instance] acceptCall];
    /// 开启对讲
    [self startTalk];
    
    _answerImgBtn.hidden = YES;
    _answerTextBtn.hidden = YES;
    
    //挂断按钮移动中间
    _hangUpImgBtn.center = CGPointMake(APP_CONTENT_WIDTH / 2, _hangUpImgBtn.center.y);
    _hangUpTextBtn.center = CGPointMake(APP_CONTENT_WIDTH / 2, _hangUpTextBtn.center.y);
    
    [_hangUpTextBtn setTitle:hangUpStr forState:UIControlStateNormal];
    //开始计时
    _callTimeout = 0;
    [self startCountdown];
    isAnswer = YES;
    
    if(self.hdlLinphoneCallDelegate != NULL){
        [self.hdlLinphoneCallDelegate onAnswerAction];
    }
    
//    [[HDLCallManager instance] acceptCallWithCall: hasVideo:YES];
//    let call = HDLCallManager.instance().callByCallId(callId: callId)
//    if (call == nil || call?.state != Call.State.IncomingReceived) {
//        // The application is not yet registered or the call is not yet received, mark the call as accepted. The audio session must be configured here.
//        HDLCallManager.configAudioSession(audioSession: AVAudioSession.sharedInstance())
//        callInfo?.accepted = true
//        callInfos.updateValue(callInfo!, forKey: uuid)
//        HDLCallManager.instance().providerDelegate.endCallNotExist(uuid: uuid, timeout: .now() + 10)
//    } else {
//        HDLCallManager.instance().acceptCall(call: call!, hasVideo: call!.params?.videoEnabled ?? false)
//    }
}
 
-(void)setAnswerBtnEnable:(BOOL)ISEnable{
    [_answerImgBtn setEnabled:ISEnable];
    [_answerTextBtn setEnabled:ISEnable];
}
//接听文本按钮
- (UIButton *)answerTextBtn{
    if (_answerTextBtn == nil) {
        _answerTextBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(100), GetRealWidth(20))];
        [_answerTextBtn setTitle:@"接听" forState:UIControlStateNormal];
        _answerTextBtn.titleLabel.font = [UIFont fontWithName:APP_UIFont size:14.0];
        _answerTextBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        //        _unlockTextBtn.titleLabel.textColor = TextColor;
        [_answerTextBtn setTitleColor:TextColor forState:UIControlStateNormal];
        [_answerTextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
        [_answerTextBtn setTitleColor:TextSelectColor forState:UIControlStateSelected];
        [_answerTextBtn addTarget:self action:@selector(answerIAction) forControlEvents:UIControlEventTouchUpInside];
        _answerTextBtn.center = CGPointMake(_answerImgBtn.center.x, GetRealHeight(530));
    }
    return _answerTextBtn;
}
//通话记录计时按钮
- (UIButton *)calltimeBtn{
    if (_calltimeBtn == nil) {
        _calltimeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(100), GetRealWidth(40))];
        _calltimeBtn.backgroundColor = HEXCOLORA(0x000000, 0.6);
        [_calltimeBtn setTitle:@"00:00" forState:UIControlStateNormal];
        _calltimeBtn.titleLabel.font = [UIFont fontWithName:APP_UIFont size:14.0];
        _calltimeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_calltimeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _calltimeBtn.hidden = YES;
        _calltimeBtn.layer.cornerRadius = 12;
        _calltimeBtn.center = CGPointMake(APP_CONTENT_WIDTH/2, GetRealWidth(340));
    }
    return _calltimeBtn;
}
 
#pragma mark - 通话时间显示处理
-(void)ShowTime:(int)nowTime {
    if(_calltimeBtn.hidden) _calltimeBtn.hidden = NO;
    NSString *timeStr = [self timeFormatted:nowTime];
    [self setCalltimeButtonText:timeStr isTime:YES];
}
 
-(void)ShowCalltimeBtn:(NSString*)mesStr{
    if(_calltimeBtn.hidden) _calltimeBtn.hidden = NO;
    [self setCalltimeButtonText:mesStr isTime:NO];
}
 
/*
 根据文字调整按钮宽
 */
-(void)setCalltimeButtonText:(NSString*) mesStr isTime:(BOOL)isTime
{
    [_calltimeBtn setTitle:mesStr forState:UIControlStateNormal];
    if(isTime){
        _calltimeBtn.frame = CGRectMake(0, 0, GetRealWidth(80), GetRealWidth(30));
    }else{
        _calltimeBtn.frame = CGRectMake(0, 0, GetRealWidth(115), GetRealWidth(30));
    }
    _calltimeBtn.center = CGPointMake(APP_SCREEN_WIDTH/2, GetRealWidth(340));
}
 
//时间格式化
- (NSString *)timeFormatted:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60);
    return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    
}
 
//- (int *)getTextWidth:(UIButton*) btn
//{
//    int textWidth = 0;
//    //     CGSize size = [btn.titleLabel.textsizeWithFont:[UIFontboldSystemFontOfSize:15]constrainedToSize:contentMaxSizes lineBreakMode:UILineBreakModeCharacterWrap];
//    //    textWidth = (int)fontSize.Width;
//    return textWidth;
//}
 
 
 
/** 开启倒计时 */
- (void)startCountdown {
    
    if (_callTimeout > 100) {
        return;
    }
    _callTimeout = 0;
    // GCD定时器
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _countdownTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_countdownTimer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_countdownTimer, ^{
        WEAKSELF_AT
        if(weakSelf_AT.callTimeout >= 100 ){// 计时结束
            // 关闭定时器
            dispatch_source_cancel(weakSelf_AT.countdownTimer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"超时");
                [weakSelf_AT backAction];
                
            });
            
        }else{// 计时中
            weakSelf_AT.callTimeout++;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf_AT ShowTime:weakSelf_AT.callTimeout];
            });
            
            
        }
    });
    
    // 开启定时器
    dispatch_resume(_countdownTimer);
    
}
 
#pragma 开锁成功
//开锁成功后,开锁按钮禁用,倒计时结束后重新允许点击
-(void)setOpenDoorSuccess{
    [self setUnlock:NO];
    _openDoorTimeout = 0;
    [self startOpenDoorCountdown];
    [self showUIAlertView:unlockSuccessfullyStr];
    
}
//设置开锁按钮是否为启用状态
-(void)setUnlock:(BOOL)isEnable{
    [self.unlockImgBtn setEnabled:isEnable];
}
 
 
 
/** 开启倒计时 */
- (void)startOpenDoorCountdown {
    
    if (_openDoorTimeout > 20) {
        return;
    }
    
    _openDoorTimeout = 0;
    
    // GCD定时器
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _openDoorTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_openDoorTimer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_openDoorTimer, ^{
        WEAKSELF_AT
        if(weakSelf_AT.openDoorTimeout >= 20 ){// 计时结束
            // 关闭定时器
            dispatch_source_cancel(weakSelf_AT.openDoorTimer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf_AT setUnlock:YES];
                
            });
            
        }else{// 计时中
            weakSelf_AT.openDoorTimeout++;
            
        }
    });
    
    // 开启定时器
    dispatch_resume(_openDoorTimer);
    
}
 
 
 
#pragma SDK可视对讲 功能部分
//初始化可视对讲SDK
-(void)initESVideo{
    //TODO:
    
    linphone_core_set_native_video_window_id([HDLLinphoneManager getLc], (__bridge void *)(self.videoView));
}
 
//初始化参数
-(void)initData{
    //    _titleUILabel.text = [[LCApiKit sharedInstance] currentDeviceName];
    [_hangUpTextBtn setTitle:refuseStr forState:UIControlStateNormal];
    [_answerTextBtn setTitle:answerStr forState:UIControlStateNormal];
    
}
 
// 暂停播放
- (void)stopPlay {
    //TODO:
    
    [HDLLinphoneManager.instance endCall];
}
 
// 开始播放
- (void)startPlay {
    //TODO:
    
    [HDLLinphoneManager.instance fetchVideo];
}
 
// 开启对讲
- (void)startTalk {
    if (!isAnswer) {
        //对讲开启
        [self startPlay];
    }
}
 
/**
 开始反呼
 */
-(void)StartReverseCall{
    [self startPlaySystemSound];
    //TODO:
    
}
 
//-(NSString *)getCurrentdateInterval
//{
//    NSDate *datenow = [NSDate date];
//    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
//    return timeSp;
//}
 
//弹窗提示,确认后没动作
-(void)showUIAlertView:(NSString *)mes
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tipStr message:mes preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:okStr style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertController animated:YES completion:nil];
}
 
///错误信息提示,点击确认关闭当前页面
-(void)showUIAlertViewWithBack:(NSString *)mes
{
    isShowErrorAlert = true;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tipStr message:mes preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:okStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self backAction];
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
 
///应用程会挂起 会调用 applicationWillResignActive 方法
- (void)onResignActive:(id)sender {
    [self stopPlay];
}
 
 
#pragma viewDidAppear
-(void)viewDidAppear:(BOOL)animated{
    //这个方法请根据App的具体情况调用
    
}
 
-(void)viewWillDisappear:(BOOL)animated{
    NSLog(@"viewWillDisappear");
    [super viewWillDisappear:animated];
    [self stopPlaySystemSound];
    //防止用户不按挂断,或者不等收到对方的挂断,点击返回按钮。
    //1.暂停SDK相关播放
    [self stopPlay];
    //2.Delegate释放
    self.hdlLinphoneCallDelegate = nil;
    //3.定时器释放
    if(_openDoorTimer){
        dispatch_source_cancel(_openDoorTimer);
        _openDoorTimer = nil; // OK
    }
    if(_countdownTimer){
        dispatch_source_cancel(_countdownTimer);
        _countdownTimer = nil; // OK
        
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
 
-(void)dealloc{
    NSLog(@"==============dealloc  1");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)willEnterForeground:(NSNotification*)notification{
    NSLog(@"willEnterForeground");
    
}
///
- (void)willEnterBackground:(NSNotification *)notification {
    NSLog(@"willEnterBackground");
}
 
#pragma 截图成功后 保存图片到相册相关
- (void)saveImageToPhotosAlbum:(UIImage *)savedImage
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined)
    {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if(status == PHAuthorizationStatusAuthorized)
            {
                UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), NULL);
            }
        }];
    }
    else
    {
        if (status == PHAuthorizationStatusAuthorized)
        {
            UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), NULL);
        }
    }
}
 
// 指定回调方法
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = nil;
    if (!error) {
        message = saveToTheAlbumsStr;
        // 截图成功回调
        if(self.hdlLinphoneCallDelegate != NULL){
            [self.hdlLinphoneCallDelegate onScreenshotSuccessfulAction:image];
        }
    }
    else
    {
        message = operationFailedStr;
    }
    [self showUIAlertView:message];
}
 
/// 保存视频截图
- (void)saveThumbImage {
    //TODO:
    
}
 
#pragma 震动实现貌似和SDK冲突 不能实现震动
//开始播放的时候调用
-(void)startPlaySystemSound{
//    return;
    //    //震动的提示文件名放到资源目录下
    //    NSString *path = [[NSBundle mainBundle] pathForResource:@"ring" ofType:@"wav"];
    //    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &sound);
    //分别注册铃声和震动完后的回调
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, HDLLPVibrationCompleteCallback, NULL);
    //    AudioServicesAddSystemSoundCompletion(sound, NULL, NULL, soundCompleteCallback, NULL);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//开始震动
    //    AudioServicesPlaySystemSound(sound);//开始播放铃声
}
 
//手动停止播放的时候调用
- (void)stopPlaySystemSound{
//    return;
    NSLog(@"stop PlaySystemSound");
    HDLLPStopRingAndVibration();
}
 
//停止响铃和震动,移除回调并处理掉铃声和震动
void HDLLPStopRingAndVibration() {
    AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
    //    AudioServicesRemoveSystemSoundCompletion(sound);
    AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
    //    AudioServicesDisposeSystemSoundID(sound);
}
 
//震动完成回调,因为震动一下便会调用一次,这里延迟800ms再继续震动,和微信差不多,时间长短可自己控制。参数sound即为注册回调时传的第一个参数
void HDLLPVibrationCompleteCallback(SystemSoundID sound,void * clientData) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(800 * NSEC_PER_MSEC)), dispatch_get_global_queue(0, 0), ^{
        AudioServicesPlaySystemSound(sound);
    });
}
 
////铃声播放完成回调,这种方法x播放的音频限制在30秒内,播放完直接响铃和震动
//void soundCompleteCallback(SystemSoundID sound,void * clientData) {
//
//    stopRingAndVibration();
//}
 
 
#pragma mark - 开锁成功通知事件
- (void)addOpenSuccessAction {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:HDLLPCallDelegateOpenDoorSuccess
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(setOpenDoorSuccess)
                                                 name:HDLLPCallDelegateOpenDoorSuccess
                                               object:nil];
}
 
- (void)removeOpenSuccessAction {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:HDLLPCallDelegateOpenDoorSuccess
                                                  object:nil];
}
 
@end