2014年1月4日土曜日

一定時間後にローカル通知する


UILocalNotificationを使って一定時間後(例では10秒後)にローカル通知する。

- (IBAction)sendNotification:(id)sender {
    NSLog(@"%s", __func__);
    
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    
    //    // iOS4未満用の処理?
    //    if (notification == nil)
    //        return;
    
    notification.fireDate = [[NSDate date] dateByAddingTimeInterval:10];
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.alertBody = @"Hello, LocalNotification!";
    notification.hasAction = YES;
    notification.alertAction = @"Launch";
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.applicationIconBadgeNumber = 1;
    
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"Recevied." forKey:@"kExtra"];
    notification.userInfo = infoDict;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ 
    // notificationの有無に関わらず、アプリ起動時に呼ばれる。
    NSLog(@"%s", __func__);
    
    UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    
    if (notification) {
        NSDictionary *infoDict = [notification userInfo];
        NSString *extra = [infoDict objectForKey:@"kExtra"];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSStringFromSelector(_cmd) message:extra delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
    }
    
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSLog(@"%s", __func__);
    // アプリ強制終了の場合も考慮して、ここにバッジクリア処理を入れるのが良さそうか?
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    // アプリがフォアグランドまたはバックグラウンドにある場合に呼ばれる。
    NSLog(@"%s", __func__);
    NSDictionary *infoDict = [notification userInfo];
    NSString *extra = [infoDict objectForKey:@"kExtra"];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSStringFromSelector(_cmd) message:extra delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];
}


[参考URL]
LocalおよびPush Notification プログラミングガイド

0 件のコメント:

コメントを投稿