ios nstimer run in background for check alarm time is equal to current time and play audio

前端 未结 3 1840
猫巷女王i
猫巷女王i 2020-12-18 17:48

I googled it for hours, but could not find any information if there is any way to keep a running NSTimer active when the app is running in the background ? Please Help me ,

3条回答
  •  天命终不由人
    2020-12-18 18:00

    Scheduling local notification will do that you want.Use Calendar and date components for firing local notification on today at specific time or on some other date at specific time here you go

    NSCalendar *calendar = [NSCalendar currentCalendar];
    
        // Split the date into components but only take the year, month and day and leave the rest behind
        NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]]; // Current Date
    
        // Build the date formatter
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"h:mm a"];
        // Convert the string time into an NSDate
        NSDate *time = [formatter dateFromString:@"1:59 PM"]; //your hour:minutes am/pm values
    
        // Split this one in components as well but take the time part this time
        NSDateComponents *timeComponents = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit ) fromDate:time];
    
        // Do some merging between the two date components
        dateComponents.hour = timeComponents.hour;
        dateComponents.minute = timeComponents.minute;
    
        // Extract the NSDate object again
        NSDate *fireTime = [calendar dateFromComponents:dateComponents];
    
        NSLog(@"Fire Time is  FireTime %@", fireTime);
         localNotification.fireDate = fireTime;
    

    if you check it in simulator then it will print TimeZone free Date/time value. Don't worry the notification will be fired with local timezone of device.

提交回复
热议问题