Повтор локального оповещения в разное время - PullRequest
1 голос
/ 25 марта 2012

У меня есть приложение, которое генерирует время молитвы (5 раз в день), я хочу создать уведомление для 5 молитв, но проблема в том, что времена меняются каждый день на основе некоторых расчетов.

Edit:

Расчеты выполняются на основе местоположения GPS, поэтому, когда пользователь переходит в другой город, время будет соответственно обновляться. Я ввожу в метод дату, часовой пояс, координаты GPS и получаю значения времени молитвы в формате (ЧЧ: мм) для данного дня / местоположения. Теперь мне нужно настроить уведомления. Я не уверен, где их настроить.

вот код

#import "PrayerTimeViewController.h"
#import "PrayTime.h"

@implementation PrayerTimeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UITabBarItem *tbi = [self tabBarItem];
        [tbi setTitle:NSLocalizedString(@"PrayerTimes", nil)];
        UIImage *i = [UIImage imageNamed:@"11-clock"];

        [tbi setImage:i];
        [i release];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{   

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Madinah"]];
    self.view.backgroundColor = background;
    [background release];

    locationManager = [[CLLocationManager alloc]init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager startUpdatingLocation];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow];
    if (t < -180) {
        return;
    }

    PrayTime *prayerTime = [[PrayTime alloc]init];
    [prayerTime setCalcMethod:0];
    [prayerTime setFajrAngle:16];
    [prayerTime setIshaAngle:14];
    [prayerTime setAsrMethod:0];



    NSDate *curentDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* compoNents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:curentDate];     
    CLLocationCoordinate2D currLoc = [newLocation coordinate];


    NSMutableArray *prayerCal = [prayerTime getDatePrayerTimes:[compoNents year]  andMonth:[compoNents month] andDay:[compoNents day] andLatitude:currLoc.latitude andLongitude:currLoc.longitude andtimeZone:[[NSTimeZone localTimeZone] secondsFromGMT]/3600];
    [prayerTime release];

    [fajer setText:[prayerCal objectAtIndex:0]];
//    UILocalNotification *localNotification = [[UILocalNotification alloc] init];

    NSString *time = [prayerCal objectAtIndex:0];
    NSString *dates = [NSString stringWithFormat:@"%d-%d-%d %@",[compoNents year],[compoNents month],[compoNents day],time];


    NSDateFormatter *dateText = [[NSDateFormatter alloc]init];
    [dateText setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateText setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:[[NSTimeZone localTimeZone] secondsFromGMT]]];

    NSLog(@"%@",[dateText dateFromString:dates]);

    [shrooq setText:[prayerCal objectAtIndex:1]];

    [duhur setText:[prayerCal objectAtIndex:2]];

    [aser setText:[prayerCal objectAtIndex:3]];

    [maghreb setText:[prayerCal objectAtIndex:5]];

    [isha setText:[prayerCal objectAtIndex:6]];

    [prayerCal release];

}



@end

Ответы [ 2 ]

2 голосов
/ 26 марта 2012

Вы можете использовать параметр repeatInterval, чтобы повторить пять уведомлений, чтобы они появлялись в одно и то же время каждый день. К сожалению, нет способа отрегулировать время без запуска приложения.

Вы можете запускать приложение GPS в фоновом режиме, хотя это может привести к разрядке батареи только для установки некоторых таймеров. (Этот фоновый процесс действительно предназначен для приложений GPS-трекера. Я не уверен, что Apple будет использовать его для немного другой цели.)

Но самым простым способом было бы просто обновить приложение при запуске. При запуске вы получите текущие уведомления (используя свойство scheduledLocalNotifications UIApplication), отмените их, если они неправильные или устарели, и создайте новые. Каждое уведомление имеет словарную полезную нагрузку, которую вы можете использовать, чтобы упростить идентификацию ваших сигналов тревоги.

0 голосов
/ 12 июня 2019

У меня была такая же проблема. Посмотрите на эту ветку (https://stackoverflow.com/a/56533797/5806009),, вот как я ее решил.

...