Objective-C (iOS): 通知

LocationNotificationViewController

Objective-C: LocationNotificationViewController.h

#import <UIKit/UIKit.h>

@interface LocationNotificationViewController : UIViewController

@end

Objective-C: LocationNotificationViewController.m

#import "LocationNotificationViewController.h"

@interface LocationNotificationViewController ()

@end

@implementation LocationNotificationViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(0, 0, 120, 50);
    [button setTitle:@"30秒後通知" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UIButton *cancelbutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    cancelbutton.frame = CGRectMake(0, 50, 120, 50);
    [cancelbutton setTitle:@"通知をキャンセル" forState:UIControlStateNormal];
    [cancelbutton addTarget:self action:@selector(cancelButtonWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelbutton];
    
}
- (void)buttonWasTapped:(UIButton *)button
{
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:30];
    localNotif.alertBody = @"Hello World.";
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    localNotif.soundName = @"Notification.aif"; // バンドルに含んでおく
    [localNotif setUserInfo:[NSDictionary dictionaryWithObject:@"1" forKey:@"NOTIF_KEY"]]; // この通知の ID を設定
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    
}
- (void)cancelbuttonWasTapped:(UIButton *)button
{
    // 全ての通知をキャンセル
//    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    // アラート通知をキャンセル
    for (UILocalNotification *notify in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
        NSString *keyId = [notify.userInfo objectForKey:@"NOTIF_KEY"];
        if ([keyId isEqualToString:@"1"]) {
            [[UIApplication sharedApplication] cancelLocalNotification:notify];
        }
    }
}

@end