1. 程式人生 > >本地推送 UILocalNotification

本地推送 UILocalNotification

初始化本地推送

- (void)initLocationNotification
{
    //初始化
    UILocalNotification *locationNotification = [[UILocalNotification alloc]  init];
    //設定推送時間,這裡使用相對時間,如果fireDate採用GTM標準時間,timeZone可以至nil
    locationNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
    locationNotification.timeZone = [NSTimeZone defaultTimeZone];
    //設定重複週期
    locationNotification.repeatInterval = NSWeekCalendarUnit;
    //設定通知的音樂
    locationNotification.soundName = UILocalNotificationDefaultSoundName;
    //設定通知內容
    locationNotification.alertBody = @"推送測試--balabala";
    //設定程式的Icon數量
    locationNotification.applicationIconBadgeNumber = 1;
    //執行本地推送
    [[UIApplication sharedApplication] scheduleLocalNotification:locationNotification];
}

本地推送執行時會呼叫UIApplication的協議方法
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification

在此方法中可以獲取推送的內容
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
        NSLog(@"推送資訊已經獲得: %@",[notification alertBody]);
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:[notification alertBody] delegate:self cancelButtonTitle:nil otherButtonTitles:@"good", nil] autorelease];
    [alert show];
}

響應結果:


如果使用的是伺服器推送,則會進入回撥方法:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo