Как я могу повторить звук моего локального уведомления, повторяемый до тех пор, пока я не нажму на его кнопку «Просмотр»?

#iphone #objective-c #alarm #uilocalnotification

#iPhone #objective-c #тревога #uilocalnotification

Вопрос:

Звук уведомления длится 20 секунд, но я хочу повторить этот звук как минимум на 60 секунд. после этого он будет отложен. Вот мой драгоценный код: D посмотрите и, пожалуйста, помогите мне…

Код:-

 @interface SetAlarmViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{

    IBOutlet UITableView *tableview;
    IBOutlet UIDatePicker *datePicker;
    IBOutlet UITextField *eventText;

    IBOutlet UINavigationBar *titleBar;
    IBOutlet UIButton *setAlarmButton;
}

@property (nonatomic, retain) IBOutlet UITableView *tableview;
@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic, retain) IBOutlet UITextField *eventText;

@property(nonatomic, retain) IBOutlet UINavigationBar *titleBar;
@property(nonatomic, retain) IBOutlet UIButton *setAlarmButton;
@property(nonatomic) UIReturnKeyType returnKeyType;  

- (IBAction) scheduleAlarm:(id) sender;
- (void)showReminder:(NSString *)text;


@implementation SetAlarmViewController
@synthesize datePicker,tableview, eventText,titleBar,setAlarmButton,returnKeyType;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    eventText.returnKeyType = UIReturnKeyDone;

    datePicker.minimumDate = [NSDate date];
    NSDate *now = [NSDate date];
    [datePicker setDate:now animated:YES];

    eventText.delegate = self;
}

- (void) viewWillAppear:(BOOL)animated {
    [self.tableview reloadData];
}

- (IBAction) scheduleAlarm:(id) sender {
    [eventText resignFirstResponder];
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    // Get the current date
    NSDate *pickerDate = [self.datePicker date];

    // Break the date up into components
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) 
                                                   fromDate:pickerDate];
    NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) 
                                                   fromDate:pickerDate];
    // Set up the fire time
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]];
    // Notification will fire in one minute
    [dateComps setMinute:[timeComponents minute]];
    [dateComps setSecond:[timeComponents second]];
    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = itemDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];

    // Notification details
    localNotif.alertBody = [eventText text];

    // Set the action button
    localNotif.alertAction = @"Show me";
    localNotif.repeatInterval = NSDayCalendarUnit;
    localNotif.soundName = @"jet.wav";
    localNotif.applicationIconBadgeNumber = 1;

    // Specify custom data for the notification
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:eventText.text
                                                         forKey:kRemindMeNotificationDataKey];
    localNotif.userInfo = userDict;

    // Schedule the notification
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];

    [self.tableview reloadData];
    eventText.text = @"";
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
    if(notif)
    {   
        [[UIApplication sharedApplication] cancelLocalNotification:notif];
    }

    [self.tableview reloadData];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...

    NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];

    [cell.textLabel setText:notif.alertBody];
    [cell.detailTextLabel setText:[notif.fireDate description]];

    return cell;
}

- (void)viewDidUnload {
    datePicker = nil;
    tableview = nil;
    eventText = nil;
    [super viewDidUnload];

}

#pragma mark -
#pragma mark === Text Field Delegate ===
#pragma mark -

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];
    return YES;
}


#pragma mark -
#pragma mark === Public Methods ===
#pragma mark -

- (void)showReminder:(NSString *)text {

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Reminder" 
                                                        message:text delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [self.tableview reloadData];

    [alertView release];
}


- (void)dealloc {
    [super dealloc];
//  [datePicker release];
//  [tableview release];
//  [eventText release];
}

@end
  

Комментарии:

1. @chown: — я новичок в этом, что вы изменили … ? 🙂

2. Просто исправлена 1 строка форматирования кода. @end Не было отступа 4 пробела. 🙂

3. хорошо, спасибо за это … кстати, есть какие-нибудь предположения относительно моего вопроса ..??

Ответ №1:

Просто запланируйте несколько локальных уведомлений с интервалами the sound's duration до тех пор, пока не истечет общее время fireDate >= 60 . Если они игнорируются, они снова отключатся, и если пользователь Show Me нажмет, вы можете отменить расписание оставшихся уведомлений для этого события при запуске приложения.

Тогда остается единственная проблема: что происходит, когда они нажимают Close . Я думаю, что должен быть обратный вызов, чтобы вы могли что-то сделать, когда уведомление закрыто.. верно? (Я не могу найти его прямо сейчас)

Комментарии:

1. @darvidsOn: — Спасибо, чувак, на самом деле я также обнаружил, что мне нужно отправлять несколько уведомлений (мы можем дать до 128) я все еще думаю, как все это реализовать. Ваше предложение тоже хорошо. позвольте мне попробовать, если это сделает мою работу, я буду рад принять ответ. Спасибо