您的位置:首页 > 移动开发 > IOS开发

在ios5 中 使用通知机制(notification ) 来显示一个消息(banner 和 alert)

2012-05-30 20:41 447 查看
在ios5 中使用通知机制 来显示 一个消息提示,可以是显示 alert 或者 banner的方式。同时显示在通知中心。

在 ViewController.m中加入通知触发机制

- (void)viewWillAppear:(BOOL)animated {
[self setupLocalNotifications];
}

- (void)setupLocalNotifications {
[[UIApplication sharedApplication] cancelAllLocalNotifications];

UILocalNotification *localNotification = [[UILocalNotification alloc] init];

// current time plus 10 secs
NSDate *now = [NSDate date];
NSDate *dateToFire = [now dateByAddingTimeInterval:5];

NSLog(@"now time: %@", now);
NSLog(@"fire time: %@", dateToFire);

localNotification.fireDate = dateToFire;
localNotification.alertBody = @"Time to get up!";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1; // increment

NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Object 1", @"Key 1", @"Object 2", @"Key 2", nil];
localNotification.userInfo = infoDict;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}


在AppDelegate.m中注册消息接受机制

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

if (notification) {
[self showAlarm:notification.alertBody];
NSLog(@"AppDelegate didFinishLaunchingWithOptions");
application.applicationIconBadgeNumber = 0;
}

[self.window makeKeyAndVisible];
return YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[self showAlarm:notification.alertBody];
application.applicationIconBadgeNumber = 0;
NSLog(@"AppDelegate didReceiveLocalNotification %@", notification.userInfo);
}


在AppDelegate.m显示消息

- (void)showAlarm:(NSString *)text {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alarm"
message:text delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}


这个应用的主要功能是 在界面显示5s后发送一个 通知消息。然后在界面显示此消息。

如果程序正在运行,在程序界面上显示 一个alert 视窗



如果程序在后台运行(运行后按下home键),在iphone主界面显示



这个消息的显示方式可以在 setting里面进行设置。

同时测试不能在模拟器上测试。只能在真机上测试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: