使用本地通知UILocalNotification實現簡易鬧鐘

// 關鍵代碼如下
- (void)resetClock:(NSDate*)date
{
// 試圖取消以前的通知
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[self saveDate:date];

if (date == nil) {
return;
}

// 設置新的通知
UILocalNotification* noti = [[[UILocalNotification alloc] init] autorelease];
// 設置響應時間
noti.fireDate = date;
// 設置時區,默認即可
noti.timeZone = [NSTimeZone defaultTimeZone];

// 重複提醒,這裏設置一分鐘提醒一次,只有啓動應用,纔會停止提醒。
noti.repeatInterval = NSMinuteCalendarUnit;
// noti.repeatCalendar = nil;

// 提示時的顯示信息
noti.alertBody = @”時間到”;
// 下面屬性僅在提示框狀態時的有效,在橫幅時沒什麼效果
noti.hasAction = NO;
noti.alertAction = @”open”;

// 這裏可以設置從通知啓動的啓動界面,類似Default.png的作用。
noti.alertLaunchImage = @”lunch.png”;

// 提醒時播放的聲音
// 這裏用系統默認的聲音。也可以自己把聲音文件加到工程中來,把文件名設在下面。最後可以播放時間長點,鬧鐘啊
noti.soundName = UILocalNotificationDefaultSoundName;

// 這裏是桌面上程序右上角的數字圖標,設0的話,就沒有。類似QQ的未讀消息數。
noti.applicationIconBadgeNumber = 1;

// 這個屬性設置了以後,在通過本應用通知啓動應用時,在下面回調中
// – (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// lanuchOptions裏面會含有這裏的userInfo.
// 正常點擊應用圖標進入應用,這個屬性就用不到了
noti.userInfo = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];

// 生效
[[UIApplication sharedApplication] scheduleLocalNotification:noti];
}

// 應用收到通知時,會調到下面的回調函數裏,當應用在啓動狀態,收到通知時不會自動彈出提示框,而應該由程序手動實現。
// 只有在退出應用後,收到本地通知,系統纔會彈出提示。
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
if (application.applicationState == UIApplicationStateActive) {
// 如不加上面的判斷,點擊通知啓動應用後會重複提示
// 這裏暫時用簡單的提示框代替。
// 也可以做複雜一些,播放想要的鈴聲。
UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@”"
message:@”時間到”
delegate:self
cancelButtonTitle:@”關閉”
otherButtonTitles:nil, nil] autorelease];
[alert show];
}
}

#pragma mark – UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
[self resetClock:nil];
}
}

// 不足之處有:
1. 不能設置提示框樣式,是橫幅還是彈框
2. 不能靈活設置重複的時間,只能按秒,分,小時,天,周,月這樣設置

示例工程代碼參見:https://github.com/TianLibin/clock

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章