Thursday, July 3, 2014

Running Tasks, UILocalNotifications in Background


- (void)applicationDidEnterBackground:(UIApplication *)application {
 
  if ([[UIDevice currentDevice] isMultitaskingSupported]) {
   
    UIApplication *application = [UIApplication sharedApplication];
   
    __block UIBackgroundTaskIdentifier background_task;
    background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
     
      NSLog(@"ExpirationHandler about to expire...");
//      [application endBackgroundTask: background_task];
//      background_task = UIBackgroundTaskInvalid;
    }];
   
   
    NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue addOperationWithBlock:^{
   
      // Perform long-running tasks without blocking main thread
     
      while(TRUE)
      {
        //backgroundTimeRemaining time does not go down.
       
        //NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
       
        UIDevice *device              = [UIDevice currentDevice];
        NSLog(@"Battey Level : %f", (device.batteryLevel));
       
        if(device.batteryLevel == 0.20f) {
          NSLog(@"Should show alert view.....for local notifications");
         
          int currentBatteryLevel      = (int)(device.batteryLevel * 100);

         
          NSDate *now = [NSDate date];
          NSCalendar *calendar = [NSCalendar currentCalendar];
          NSDateComponents *components = [[NSDateComponents alloc] init];
          [components setSecond:5];
          NSDate *dateTime = [calendar dateByAddingComponents:components
                                                              toDate:now
                                                             options:0];
         
         
          UILocalNotification *localNotification = [[UILocalNotification alloc] init];
          localNotification.fireDate = dateTime;
          localNotification.alertBody = [NSString stringWithFormat:@"Battery Level : %d percent", currentBatteryLevel];
          localNotification.soundName = UILocalNotificationDefaultSoundName;
          //localNotification.applicationIconBadgeNumber = 1;
          [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
         
         
            [application endBackgroundTask: background_task];
            background_task = UIBackgroundTaskInvalid;
        }
       
        [[NSNotificationCenter defaultCenter] postNotificationName:@"UIDeviceBatteryLevelDidChangeNotification" object:self userInfo:nil];
       
        [NSThread sleepForTimeInterval:10]; //wait for 1 sec

      }
     
    }];
   
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           
      // Wait until the pending operations finish
      [operationQueue waitUntilAllOperationsAreFinished];

     
      NSLog(@"ExpirationHandler is called");

    });
  }
}

No comments: