iOS 鬧鐘功能實現+本地通知+音頻播放
問題描述:通過picker設置時間,到了設定好的時間 鬧鐘響起,并彈出提示框,點擊確定,停止播放音頻。如果設置好了鬧鐘,沒有停在該頁面,而是返回了手機主屏幕或是手機鎖屏,當到了鬧鐘設定的時間,會彈出消息通知。(如果設定的時間是已經過去的時間,頁面不會有響應,直到設置正確的時間為止.)
效果圖如下:
具體代碼如下:
NaoZhongViewController.m文件
#import "NaoZhongViewController.h"
#import <AVFoundation/AVFoundation.h>
#define kW self.view.frame.size.width
#define kH self.view.frame.size.height
@interface NaoZhongViewController ()
{
NSTimer * _timer; //定時器
AVAudioPlayer * _player;
}
@property(nonatomic, weak)UIDatePicker * picker;
@property(nonatomic,weak) UILabel * label;
@property(nonatomic,assign)NSInteger lt;
@property(nonatomic,weak) UIButton * button;
@end
@implementation NaoZhongViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title=@"鬧鐘";
self.view.backgroundColor=[UIColor whiteColor];
[self _loadView];
}
- (void) _loadView
{
//view
UIView * view=[[UIView alloc]initWithFrame:CGRectMake(, 20+45, kW, kH)];
UIDatePicker * picker=[[UIDatePicker alloc]init];
picker.backgroundColor=[UIColor colorWithRed:0.1 green:0.1 blue:0.5 alpha:0.1];
[view addSubview:picker];
_picker=picker;
[self.view addSubview:view];
UIButton * button=[[UIButton alloc]initWithFrame:CGRectMake(, , 100, 50)];
button.backgroundColor=[UIColor colorWithRed:0.1 green:0.5 blue:0.8 alpha:0.2];
button.center=self.view.center;
[button setTitle:@"確定" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(countTime:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"確定" forState:UIControlStateSelected];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateSelected];
_button=button;
[self.view addSubview:button];
UILabel * label=[[UILabel alloc]initWithFrame:CGRectMake(20, 400, kW-40, kH-400-80)];
label.backgroundColor=[UIColor colorWithRed:0.2 green:0.2 blue:0.6 alpha:0.2];
label.text=@"00:00:00";
label.textAlignment=NSTextAlignmentCenter;
[label setFont:[UIFont fontWithName:nil size:80]];
_label=label;
[self.view addSubview:label];
UILabel * label1=[[UILabel alloc]initWithFrame:CGRectMake(25, 400, kW-40, 40)];
label1.text=@"鬧鐘還剩時間:";
[self.view addSubview: label1];
}
- (void) countTime:(UIButton *) button
{
button.selected=!button.selected;
//求從現在到設置時間的時長秒數(有誤差)
/*
//1970到picker的秒數
NSTimeInterval seconds=[_picker.date timeIntervalSince1970];
NSLog(@"%@",_picker.date); //設置的時間
NSLog(@"%.0f",seconds);
//1970到現在的秒數
NSDate * date=[[NSDate alloc]init];
NSLog(@"%@",date);
NSTimeInterval seconds2=[date timeIntervalSince1970];
NSLog(@"%.0f",seconds2);
NSLog(@"時間差是:----%.0f 秒",seconds-seconds2);
*/
//求從現在到設置時間的時長秒數(有誤差)
/*
NSDate * date=[[NSDate alloc]init];
NSLog(@"%@",date);
NSTimeInterval seconds2=[_picker.date timeIntervalSinceDate:date];
NSLog(@"%.0f",seconds2);
NSLog(@"時間差是:----%.0f 秒",seconds2);
*/
//picker 設置的時間
//格式
NSDateFormatter * format1=[[NSDateFormatter alloc]init];
[format1 setDateFormat:@"hh"];
NSDateFormatter * format2=[[NSDateFormatter alloc]init];
[format2 setDateFormat:@"mm"];
//獲取小時
NSString * str1=[format1 stringFromDate:_picker.date];
NSInteger temp1=[str1 integerValue];
NSDate * date3=[[NSDate alloc]init];
NSString * str3=[format1 stringFromDate:date3];
NSInteger temp3=[str3 integerValue];
//獲取分鐘
NSString * str2=[format2 stringFromDate:_picker.date];
NSInteger temp2=[str2 integerValue];
NSDate * date4=[[NSDate alloc]init];
NSString * str4=[format2 stringFromDate:date4];
NSInteger temp4=[str4 integerValue];
NSLog(@"鬧鐘時長:%li 秒",(temp1-temp3)*60*60+(temp2-temp4)*60);
//--------------------------------------------------------------------
NSInteger lt=(temp1-temp3)*60*60+(temp2-temp4)*60;
_lt=lt;
if (_lt> && _button.selected)
{
NSString * strT=[NSString stringWithFormat:@"%02i:%02i:%02i",(int)lt/3600%60,(int)lt/60%60,(int)lt%60];
_label.text=strT;
}
else
{
NSLog(@"請重新設置時間....");
_label.text=@"00:00:00";
return;
}
if(_timer==nil)
{
//每隔0.01秒刷新一次頁面
_timer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(runAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
NSLog(@"開始倒計時.....");
}
else
{
[_timer invalidate]; //定時器失效
}
}
- (void) runAction
{
_lt--;
if (_lt==)
{
[_timer invalidate];//讓定時器失效
UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"關閉鬧鐘" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
// [alert addButtonWithTitle:@"確定"];
alert.delegate=self;
// [alert clickedButtonAtIndex:0];
[alert show];
//提示框彈出的同時,開始響鬧鐘
NSString * path=[[NSBundle mainBundle]pathForResource:@"4948.mp3" ofType:nil];
NSURL * url=[NSURL fileURLWithPath:path];
NSError * error;
_player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
_player.numberOfLoops=-1; //無限循環 =0 一遍 =1 兩遍 =2 三遍 =負數 單曲循環
_player.volume=2; //音量
[_player prepareToPlay]; //準備工作
//[_player stop]; //卡一下
[_player play]; //開始播放
// 1 注冊通知
UIApplication * app=[UIApplication sharedApplication];
NSArray * array=[app scheduledLocalNotifications];
NSLog(@"%ld",array.count);
for (UILocalNotification * local in array) {
NSDictionary * dic= local.userInfo;
if ([dic[@"name"] isEqual:@"zhangsan"]) {
//刪除指定的通知
[app cancelLocalNotification:local];
}
}
//刪除所有通知
// [app cancelAllLocalNotifications];
//
//判斷是否已經注冊通知
UIUserNotificationSettings* setting= [app currentUserNotificationSettings];
//如果setting.types==UIUserNotificationTypeNone 需要注冊通知
if(setting.types==UIUserNotificationTypeNone){
UIUserNotificationSettings* newSetting= [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[app registerUserNotificationSettings:newSetting];
}else{
[self addLocalNotification];
}
}
NSString * str=[NSString stringWithFormat:@"%02d:%02d:%02d",(int)(self.lt)/3600%24,(int)(self.lt)/60%60,(int)(self.lt)%60];
_label.text=str;
}
#pragma mark - 增加本地通知
- (void) addLocalNotification{
UILocalNotification * notification=[[UILocalNotification alloc] init];
notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:];
notification.alertBody=@"鬧鐘響了。。。。。。";
notification.alertAction=@"打開鬧鐘";
notification.repeatInterval=NSCalendarUnitSecond;
notification.applicationIconBadgeNumber=1;
//notification.userInfo=@{@"name":@"zhangsan"};
//notification.soundName=@"4195.mp3";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
//注冊完成后調用
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
[self addLocalNotification];
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
NSLog(@"+========我接受到通知了");
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[_player stop];
}
@end