闹钟基本实现

闹钟所实现的基本功能:定时提醒 

  //定义声音

    CFBundleRef mainBundle;
	mainBundle = CFBundleGetMainBundle ();
	
	// Get the URL to the sound file to play
	soundFileURLRef  =	CFBundleCopyResourceURL (
                                                 mainBundle,
                                                 CFSTR ("tap"),
                                                 CFSTR ("aif"),
                                                 NULL
                                                 );
    //将nsstring转为cfstring
    
    
	// Create a system sound object representing the sound file
	AudioServicesCreateSystemSoundID
    (
     soundFileURLRef,
     &soundFileObject
     );//声音的绑定(类似数据库时用的数据库指针)

 利用之前介绍的uidatepicker选取要提醒的时间

//计算多少秒后闹钟响应时间	
			int hm=(hs*3600)+(ms*60)-sec;
			//建立后台消息对象	
			UILocalNotification *notification=[[UILocalNotification alloc] init];
			if (notification!=nil) 
			{   
				notification.repeatInterval=NSDayCalendarUnit;
				NSDate *now1=[NSDate new];
				notification.fireDate=[now1 dateByAddingTimeInterval:hm];//距现在多久后触发代理方法
				notification.timeZone=[NSTimeZone defaultTimeZone];
				notification.soundName = @"tap.aif";
				notification.alertBody = [NSString stringWithFormat:NSLocalizedString(@"你设置的时间是:%i : %i .",nil),htime1 ,mtime1];
				[[UIApplication sharedApplication]   scheduleLocalNotification:notification];
				[now1 release];
			}

点击确定时触发此方法

-(void)notfacation{
	//获取当前时间
	sure=YES;
	NSDate* now = [NSDate date];
	NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *comps = [[NSDateComponents alloc] init];
	NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
	NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
	comps = [calendar components:unitFlags fromDate:now];
	hour = [comps hour];
	min = [comps minute];
	
	sec = [comps second]; 
	
	htime1=[textField.text intValue];
	mtime1=[textField1.text intValue];
	
	hs=htime1-hour;
	ms=mtime1-min;
	//设置弹出框提醒用户	
	UIAlertView *at=[[UIAlertView alloc] initWithTitle:@"!" 
											   message:[NSString stringWithFormat:@"你设置的时间: %i:%i ",htime1,mtime1]
											  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"关闭",nil];
	[at setDelegate:self];
	[at show];
	[at release];	
} 

  所设定的时间到了会触发此代理

//到时间时触发的代理
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"123123123131231231++++++++++++");
    AudioServicesPlaySystemSound (self.soundFileObject);

	sure=NO;
    UIApplicationState state = application.applicationState;
	
    if (state == UIApplicationStateActive) 
    {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"时间提醒"
														message:notification.alertBody
													   delegate:self
											  cancelButtonTitle:@"确定"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
     }
}

猜你喜欢

转载自dxldy.iteye.com/blog/1757364