在現階的APP中關于消息的處理需求越來越大,系統需要將一下消息以音頻或者文字的形式提示用戶,這里便用到推送,推送消息主要有本地和遠程推送,今天我們先研究一下簡單的本地通知,下面以鬧鐘為例子。
1、我們首先要注冊通知
UIapplication * application=[UIApplication sharedApplication]; //如果當前應用程序沒有注冊本地通知,需要注冊 if([application currentUserNotificationSettings].types==UIUserNotificationTypeNone){ //設置提示支持的提示方式// UIUserNotificationTypeBadge 提示圖標// UIUserNotificationTypeSound 提示聲音// UIUserNotificationTypeAlert 提示彈框 UIUserNotificationSettings * setting=[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil]; [application registerUserNotificationSettings:setting]; } //刪除之前的重復通知 [application cancelAllLocalNotifications];通知注冊完成之后可以在設置里面進行查看,同時也可以刪除。如圖:
2、設置通知
#PRagma mark - 添加本地通知- (void) _addLocalNotification:(NSDate *) date{ UILocalNotification * noti=[[UILocalNotification alloc] init]; //設置開始時間 noti.fireDate=date; //設置body noti.alertBody=@"該起床了"; //設置action noti.alertAction=@"解鎖"; //設置鬧鈴 noti.soundName=@"4195.mp3"; #warning 注冊完之后如果不刪除,下次會繼續存在,即使從模擬器卸載掉也會保留 //注冊通知 [[UIApplication sharedApplication] scheduleLocalNotification:noti]; }
這樣就會在設置的時間內鬧鐘響起來,如圖:
3、這樣鬧鐘的功能基本實現,但是還有一個問題,因為如果當前程序是打開的會導致鬧鐘不會響起來,那我們如何解決問題呢。此時我們需要借助播放器來解決
@interface AppDelegate (){ //定義播放器播放音樂 AVAudioPlayer * player; //用來判斷是不是從通知窗口打開 BOOL isFromNotification;}- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{ //如果是從通知窗口進來的則不需要播放音頻 if (isFromNotification) { return; } //初始化音樂播放音樂 NSURL * url=[[NSBundle mainBundle] URLForResource:@"4195.mp3" withExtension:nil]; player=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; player.numberOfLoops=0; [player prepareToPlay]; [player play]; }
這樣便大功告成了。
疑問咨詢或技術交流,請加入官方QQ群: (452379712)
新聞熱點
疑難解答