iOS學習筆記32—本地通知UILocalNotification

來源:互聯網
上載者:User

[cpp]
UILocalNotification *notification = [[UILocalNotification alloc] init]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"HH:mm:ss"]; 
    //觸發通知的時間 
    NSDate *now = [formatter dateFromString:@"15:00:00"]; 
    notification.fireDate = now; 
    //時區 
    notification.timeZone = [NSTimeZone defaultTimeZone]; 
    //通知重複提示的單位,可以是天、周、月 
    notification.repeatInterval = NSDayCalendarUnit; 
    //通知內容 
    notification.alertBody = @"這是一個新的通知"; 
    //通知被觸發時播放的聲音 
    notification.soundName = UILocalNotificationDefaultSoundName; 
    //執行通知註冊 
    [[UIApplication sharedApplication] scheduleLocalNotification:notification]; 

以上代碼實現了這麼一個情境:一些Todo和鬧鐘類應用都有通知使用者的功能,使用的就是iOS中的本地通知UILocalNotification,還有些應用會在每天、每周、每月固定時間提示使用者回到應用看看,也是用的本地通知,以上程式碼片段就是實現了在每天的下午3點彈出通知提示。

 


如果要在通知中攜帶參數資訊,可以使用下面的方式:


[cpp]
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"]; 
    notification.userInfo = dic; 

如果軟體是在運行中,則可以通過AppDelegate中的回調方法擷取並處理參數資訊:


[cpp]
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 

    if (notification) { 
        NSDictionary *userInfo =  notification.userInfo; 
        NSString *obj = [userInfo objectForKey:@"key"]; 
        NSLog(@"%@",obj); 
    } 

另外,可以通過兩種方式取消註冊的本地通知,一種是取消指定的通知,第二種是取消所有的註冊通知:


[cpp]
[[UIApplication sharedApplication] cancelLocalNotification:localNotification]; 
   [[UIApplication sharedApplication] cancelAllLocalNotification]; 

以上就簡要介紹了一下UILocalNotification的使用,歡迎大家指正和補充!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.