2012-01-24 25 views
3

我正在制作一个闹钟应用程序,我会问一个问题,可能以前曾被问过一百万次。如何做在背景中与应用程序响铃时钟

当用户使用UIDate选取器在我的闹钟应用程序中设置日期&,并点击其iPhone上的主页按钮或关闭手机,让我的应用程序在后台运行时,我怎么还可以做一个铃声来唤醒他起来了吗?

示例代码将非常感谢。

回答

2

您可以使用本地通知http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction/Introduction.htmlhttp://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW13

- (void)scheduleNotificationWithItem:(ToDoItem *)item interval:(int)minutesBefore { 
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar]; 
    NSDateComponents *dateComps = [[NSDateComponents alloc] init]; 
    [dateComps setDay:item.day]; 
    [dateComps setMonth:item.month]; 
    [dateComps setYear:item.year]; 
    [dateComps setHour:item.hour]; 
    [dateComps setMinute:item.minute]; 
    NSDate *itemDate = [calendar dateFromComponents:dateComps]; 
    [dateComps release]; 

    UILocalNotification *localNotif = [[UILocalNotification alloc] init]; 
    if (localNotif == nil) 
     return; 
    localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)]; 
    localNotif.timeZone = [NSTimeZone defaultTimeZone]; 

    localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"%@ in %i minutes.", nil), 
     item.eventName, minutesBefore]; 
    localNotif.alertAction = NSLocalizedString(@"View Details", nil); 

    localNotif.soundName = UILocalNotificationDefaultSoundName; 
    localNotif.applicationIconBadgeNumber = 1; 

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.eventName forKey:ToDoItemKey]; 
    localNotif.userInfo = infoDict; 

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
    [localNotif release]; 
} 
+0

太感谢你了。如果我想用我自己的声音,我该怎么做,而不是使用UILocalNotificationDefaultSoundName –

+0

回答了我自己的问题:localNotif.soundName = @“alarmsound.caf”; –

相关问题