iPhone alarms that wake up the device from sleep with sound
I'm a bit confused on iPhone's capabilities for alarms (local notifications) and I haven't found a clear answer yet. I would like to create functionality like the alarm clock (or even new mail). Specifically, if the device is asleep, it gets waken with a buzz or sound. A popup message that you can't see (because the device is asleep) is a lot less useful. But, it seems that using the UILocalNotification service, this doesn't seem to be happening. I haven't checked out push notifications, but they seem to be for something else.
I'm may be missing something (and I'm hoping so), so someone that knows, please clarify this issue for me. The alarm clock, mail and facebook all do this.
Code snippet of what I'm doi开发者_如何转开发ng now:
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:0];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
alarm.fireDate = itemDate;
alarm.timeZone = [NSTimeZone defaultTimeZone];
alarm.repeatInterval = NSDayCalendarUnit;
alarm.soundName = @"alarmsound2.m4a";
alarm.alertBody = NSLocalizedString(@"WakeUp", @"");
alarm.hasAction = YES;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"alarm_notify" forKey:@"type"];
alarm.userInfo = infoDict;
[app scheduleLocalNotification:alarm];
[alarm release];
I just created a sample application with the following code in the AppDelegate and it working as expected. I get a notification with default sound and alert when the phone is in sleep mode.
Please note that the Local notifications only work with iOS 4.0 or later.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = @"Local Notification Body : Some Alert";
localNotification.alertAction = @"Action String";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
精彩评论