NTESAVNotifier.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. //
  2. // NTESAVNotifier.m
  3. // NIM
  4. //
  5. // Created by amao on 2017/5/4.
  6. // Copyright © 2017年 Netease. All rights reserved.
  7. //
  8. #import "NTESAVNotifier.h"
  9. #import "NTESGlobalMacro.h"
  10. @import AudioToolbox;
  11. static void VibrateCompletion(SystemSoundID soundID, void *data)
  12. {
  13. id notifier = (__bridge id)data;
  14. if([notifier isKindOfClass:[NTESAVNotifier class]])
  15. {
  16. SEL selector = NSSelectorFromString(@"vibrate");
  17. SuppressPerformSelectorLeakWarning([(NTESAVNotifier *)notifier performSelector:selector withObject:nil afterDelay:1.0]);
  18. }
  19. }
  20. @interface NTESAVNotifier ()
  21. @property (nonatomic,strong) UILocalNotification *currentNotification;
  22. @property (nonatomic,assign) BOOL shouldStopVibrate;
  23. @property (nonatomic,assign) NSInteger vibrateCount;
  24. @end
  25. @implementation NTESAVNotifier
  26. - (instancetype)init
  27. {
  28. if (self = [super init])
  29. {
  30. [[NSNotificationCenter defaultCenter] addObserver:self
  31. selector:@selector(willEnterForeground:)
  32. name:UIApplicationWillEnterForegroundNotification
  33. object:nil];
  34. }
  35. return self;
  36. }
  37. - (void)dealloc
  38. {
  39. [[NSNotificationCenter defaultCenter] removeObserver:self];
  40. }
  41. - (void)start:(NSString *)text
  42. {
  43. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground)
  44. {
  45. return;
  46. }
  47. [self stop];
  48. _vibrateCount = 0;
  49. _shouldStopVibrate = NO;
  50. [self raiseNotification:text];
  51. [self vibrate];
  52. }
  53. - (void)stop
  54. {
  55. if (_currentNotification)
  56. {
  57. [[UIApplication sharedApplication] cancelLocalNotification:_currentNotification];
  58. _currentNotification = nil;
  59. }
  60. _shouldStopVibrate = YES;
  61. }
  62. - (void)willEnterForeground:(NSNotification *)notification
  63. {
  64. [self stop];
  65. }
  66. - (void)vibrate
  67. {
  68. if (!_shouldStopVibrate)
  69. {
  70. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
  71. AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, VibrateCompletion, (__bridge void *)self);
  72. _vibrateCount++;
  73. if (_vibrateCount >= 15)
  74. {
  75. _shouldStopVibrate = YES;
  76. }
  77. }
  78. }
  79. - (void)raiseNotification:(NSString *)text
  80. {
  81. _currentNotification = [[UILocalNotification alloc] init];
  82. _currentNotification.soundName = @"video_chat_push.mp3";
  83. _currentNotification.alertBody = text;
  84. [[UIApplication sharedApplication] presentLocalNotificationNow:_currentNotification];
  85. }
  86. @end