[英]Open Local Notification on tap when Notification received - iOS - Swift
[英]iOS - Trigger Local Notification when message is received
我正在構建一個允許其用戶發送彼此消息的應用程序。 收到新消息后,它將顯示在當前用戶的“表”視圖中。 我希望我的應用在收到新消息時向當前用戶發送通知。 有人知道我該怎么做嗎?
我已經在AppDelegate中設置了通知:
appdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Let the device know we want to receive push notifications
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
並且我知道以下代碼將允許我在指定的時間(例如,由選擇器設置)觸發通知:
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = self.itemText.text;
localNotification.alertAction = @"You are being notified!";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self];
// Dismiss the view controller
[self dismissViewControllerAnimated:YES completion:nil];
但是,當已登錄用戶的新消息發布到服務器(並出現在表視圖中)時,如何發出通知?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];}
如果您的系統是iOS8,則需要注冊權限。
UILocalNotification * notification = [[UILocalNotification alloc] init];
NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:Time];
if (notification!=nil) {
notification.fireDate= pushDate;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = kCFCalendarUnitDay;
notification.soundName = UILocalNotificationDefaultSoundName;
notification.alertBody = @"Time O.K!";
NSLog(@"Ready");
notification.applicationIconBadgeNumber = 1;
//notification.applicationIconBadgeNumber = [[[UIApplication sharedApplication] scheduledLocalNotifications] count]+1;
NSDictionary * inforDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
notification.userInfo =inforDic;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
您可以嘗試一下,我可以在設備上成功使用此代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.