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