TUICaptureTimer.m 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Created by Tencent on 2023/06/09.
  2. // Copyright © 2023 Tencent. All rights reserved.
  3. #import "TUICaptureTimer.h"
  4. @interface TUICaptureTimer ()
  5. @property(nonatomic, strong) dispatch_source_t gcdTimer;
  6. @property(nonatomic, assign) CGFloat captureDuration;
  7. @end
  8. @implementation TUICaptureTimer
  9. - (instancetype)init {
  10. self = [super init];
  11. if (self) {
  12. self.maxCaptureTime = 15.0f;
  13. }
  14. return self;
  15. }
  16. - (void)startTimer {
  17. self.gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
  18. NSTimeInterval delayTime = 0.f;
  19. NSTimeInterval timeInterval = 0.1f;
  20. dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (uint64_t)(delayTime * NSEC_PER_SEC));
  21. dispatch_source_set_timer(self.gcdTimer, startDelayTime, timeInterval * NSEC_PER_SEC, timeInterval * NSEC_PER_SEC);
  22. dispatch_source_set_event_handler(self.gcdTimer, ^{
  23. self.captureDuration += timeInterval;
  24. /**
  25. * Updating UI on the main thread
  26. */
  27. dispatch_async(dispatch_get_main_queue(), ^{
  28. if (self.progressBlock) {
  29. self.progressBlock(self.captureDuration / self.maxCaptureTime, self.captureDuration);
  30. }
  31. });
  32. /**
  33. * Fnish
  34. */
  35. if (self.captureDuration >= self.maxCaptureTime) {
  36. /**
  37. * Invalid timer
  38. */
  39. CGFloat ratio = self.captureDuration / self.maxCaptureTime;
  40. CGFloat recordTime = self.captureDuration;
  41. [self cancel];
  42. dispatch_async(dispatch_get_main_queue(), ^{
  43. if (self.progressFinishBlock) self.progressFinishBlock(ratio, recordTime);
  44. });
  45. }
  46. });
  47. /**
  48. * Start the task. After the GCD timer is created, it needs to be started manually
  49. */
  50. dispatch_resume(self.gcdTimer);
  51. }
  52. - (void)stopTimer {
  53. [self cancel];
  54. dispatch_async(dispatch_get_main_queue(), ^{
  55. if (self.progressCancelBlock) self.progressCancelBlock();
  56. });
  57. }
  58. - (void)cancel {
  59. if (self.gcdTimer) {
  60. dispatch_source_cancel(self.gcdTimer);
  61. self.gcdTimer = nil;
  62. }
  63. self.captureDuration = 0;
  64. }
  65. @end