iOS: 本地通知(UILocalNotification )的應用

iOS: 本地通知(UILocalNotification )的應用  

2014-07-02 08:02:30|  分類: iOS之美 |  標籤:ios  localnotification  本地通知  |舉報|字號 訂閱

在iOS中,爲了在特定場景下給用戶彈出一個提醒, 會用到 本地通知(UILocalNotification)。 localnotification 用得恰到好處時,能達到提醒的目的;如果對通知管理不好的話,會出現紊亂情況: 該通知時不通知,不該通知時亂通知。

發送通知:  

  UILocalNotification *newNotification = [[UILocalNotification alloc] init];

    if (newNotification) {

//時區

        newNotification.timeZone=[NSTimeZone defaultTimeZone];

//推送事件---10秒後

        newNotification.fireDate=[[NSDate date] dateByAddingTimeInterval:10];

        //推送內容

        newNotification.alertBody = @"信號報警";

//應用右上角紅色圖標數字

        newNotification.applicationIconBadgeNumber = 1;

注:

//1:格式一定要支持播放,常用的格式caf

//2:音頻播放時間不能大於30秒

//3:在Resource裏要找到音頻文件,倒入時最好能點項目名稱右鍵add導入

        newNotification.soundName = @"jingBao2.caf";

//設置按鈕

newNotification.alertAction = @"關閉";

        //判斷重複與否

        newNotification.repeatInterval = NSWeekCalendarUnit;

//存入的字典,用於傳入數據,區分多個通知 

        NSMutableDictionary *dicUserInfo = [[NSMutableDictionary alloc] init];

        [dicUserInfo setValue:@"" forKey:@"clockID"];

        float floatHeng = userLocation.location.coordinate.latitude;

        float floatShu = userLocation.location.coordinate.longitude;

        [dicUserInfo setValue:[NSString stringWithFormat:@"%f",strX] forKey:@"heng"];

        [dicUserInfo setValue:[NSString stringWithFormat:@"%f",strY] forKey:@"shu"];

        newNotification.userInfo = [NSDictionary dictionaryWithObject:dicUserInfo forKey:@"dictionary"];

        [dicUserInfo release];

        [[UIApplication sharedApplication] scheduleLocalNotification:newNotification];

    }

    NSLog(@"Post new localNotification:%@", newNotification);

    [newNotification release];

    [pool release];


取消通知:

通知完一定要取消,IOS最多允許最近本地通知數量是64個,超過限制的本地通知將被忽略。

1:刪除應用所有通知

[[UIApplication sharedApplication] cancelAllLocalNotifications];

2:根據字典刪除個別通知 

key:發送通知時候傳入的字典值來判斷是哪個推送

 

    for (int i=0; i<[myArray count]; i++) {

        UILocalNotification    *myUILocalNotification=[myArray objectAtIndex:i];

        if ([[[myUILocalNotification userInfo] objectForKey:@"key"] intValue]==@"字典值") {

            [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];

        }

    }


通知執行完調用的方法 AppDelegate.m類裏面

//推送完 執行的事件

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{

//notification是發送通知時傳入的字典信息

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"標題" message:notification.alertBody delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];

        [alert show];

[alert release];

}

最後還有一個地方:執行通知一定要退出應用才能收到通知。

發佈了17 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章