Background Task or Timer Malfunctioning

I Have the following code in my project. Background mode was enabled for bluetooth communication.

I receive data from my bluetooth device every 60 seconds then I'll reset my task. As per design "doMyWork" should never be called when bluetooth is connected. But some of the users got this local notification every minute when the app is background. I couldn't corner my issue whether the background task getting expired or timer malfuncioning. Please help me on this.


#import "ViewController.h"


@interface ViewController ()

@property (nonatomic, strong) NSTimer *myTimer;

@property (nonatomic, assign) UIBackgroundTaskIdentifier myTaskIdentifier;


@end


@implementation ViewController


- (void)viewDidLoad

{

[super viewDidLoad];


//This notification will be received every minute.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoothNotificationReceived) name:@"kMyBluetoothNotification" object:nil];

}


- (void)bluetoothNotificationReceived

{

[self removeMyTasks];

}


- (void)removeMyTasks

{

[self removeMyTimer];

[self removeMyBackgroundTask];

}


- (void)removeMyTimer

{

[_myTimer invalidate];

_myTimer = nil;

}


- (void)removeMyBackgroundTask

{

[UIApplication.sharedApplication endBackgroundTask:_myTaskIdentifier];

}


- (void)scheduleMyTasks

{

[self scheduleMyBackgroundTask];

[self scheduleMyTimer];

}


- (void)scheduleMyTimer

{

_myTimer = [NSTimer scheduledTimerWithTimeInterval:180 target:self selector:@selector(doMyWork) userInfo:nil repeats:false];

}


- (void)scheduleMyBackgroundTask

{

_myTaskIdentifier = [UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:^{

[self doMyWork];

}];

}


- (void)doMyWork

{

[self postNotification];

[self removeMyTasks];

}


- (void)postNotification

{

UILocalNotification *notification = UILocalNotification.new;

notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];

notification.timeZone = [NSTimeZone localTimeZone];

notification.alertBody = @"Bluetooth communication interrupted.";

notification.alertAction = @"Check";

notification.soundName = UILocalNotificationDefaultSoundName;

notification.applicationIconBadgeNumber = 1;

[UIApplication.sharedApplication scheduleLocalNotification:notification];

}


@end