如何在 iOS 中创建本地通知?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6047117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create local notifications in iOS?
提问by learner2010
I would like to know how I can setup local notifications so that at the time I set, my app generates a notification/alert with a customized message...
我想知道如何设置本地通知,以便在我设置时,我的应用程序生成带有自定义消息的通知/警报...
回答by Jayprakash Dubey
Here is sample code for LocalNotificationthat worked for my project.
这是适用于我的项目的LocalNotification示例代码。
Objective-C:
目标-C:
This code block in AppDelegate
file :
AppDelegate
文件中的此代码块:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// Override point for customization after application launch.
return YES;
}
// This code block is invoked when application is in foreground (active-mode)
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"This local notification"
delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[notificationAlert show];
// NSLog(@"didReceiveLocalNotification");
}
This code block in .m file of any ViewController
:
任何 .m 文件中的此代码块ViewController
:
-(IBAction)startLocalNotification { // Bind this method to UIButton action
NSLog(@"startLocalNotification");
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
notification.alertBody = @"This is local notification!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 10;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
The above code display an AlertView after time interval of 7 seconds when pressed on button that binds startLocalNotification
If application is in background then it displays BadgeNumber
as 10 and with default notification sound.
当按下绑定的按钮时,上面的代码在 7 秒的时间间隔后显示 AlertViewstartLocalNotification
如果应用程序在后台,则显示BadgeNumber
为 10 并带有默认通知声音。
This code works fine for iOS 7.x and below but for iOS 8 it will prompt following erroron console:
此代码适用于 iOS 7.x 及以下版本,但对于iOS 8,它会在控制台上提示以下错误:
Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts
尝试使用警报安排本地通知,但尚未获得用户显示警报的许可
This means you need register for local notification. This can be achieved using:
这意味着您需要注册本地通知。这可以使用以下方法实现:
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
You can also refer blogfor local notification.
您也可以参考博客获取本地通知。
Swift:
迅速:
You AppDelegate.swift
file should look like this:
您的AppDelegate.swift
文件应如下所示:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))
return true
}
The swift file (say ViewController.swift
) in which you want to create local notification should contain below code:
ViewController.swift
您要在其中创建本地通知的 swift 文件(例如)应包含以下代码:
//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
println("buttonIsPressed function called \(UIButton.description())")
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
localNotification.alertBody = "This is local notification from Swift 2.0"
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
localNotification.userInfo = ["Important":"Data"];
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = 5
localNotification.category = "Message"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//MARK: - viewDidLoad
class ViewController: UIViewController {
var objButton : UIButton!
. . .
override func viewDidLoad() {
super.viewDidLoad()
. . .
objButton = UIButton.buttonWithType(.Custom) as? UIButton
objButton.frame = CGRectMake(30, 100, 150, 40)
objButton.setTitle("Click Me", forState: .Normal)
objButton.setTitle("Button pressed", forState: .Highlighted)
objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)
. . .
}
. . .
}
The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.
您在 iOS 9 及更低版本中使用本地通知的方式在 iOS 10 中完全不同。
Below screen grab from Apple release notes depicts this.
下面从 Apple 发行说明中截取的屏幕描述了这一点。
You can refer apple reference documentfor UserNotification.
你可以参考苹果的 UserNotification参考文档。
Below is code for local notification:
以下是本地通知的代码:
Objective-C:
目标-C:
In
App-delegate.h
file use@import UserNotifications;
App-delegate should conform to
UNUserNotificationCenterDelegate
protocolIn
didFinishLaunchingOptions
use below code:UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { NSLog(@"request authorization succeeded!"); [self showAlert]; } }]; -(void)showAlert { UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Ok clicked!"); }]; [objAlertController addAction:cancelAction]; [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{ }]; }
Now create a button in any view controller and in IBAction use below code :
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil]; objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil]; objNotificationContent.sound = [UNNotificationSound defaultSound]; // 4. update application icon badge number objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1); // Deliver the notification in five seconds. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10.f repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten” content:objNotificationContent trigger:trigger]; // 3. schedule localNotification UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@“Local Notification succeeded“); } else { NSLog(@“Local Notification failed“); } }];
在
App-delegate.h
文件使用中@import UserNotifications;
App-delegate 应该符合
UNUserNotificationCenterDelegate
协议在
didFinishLaunchingOptions
使用下面的代码:UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { NSLog(@"request authorization succeeded!"); [self showAlert]; } }]; -(void)showAlert { UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Ok clicked!"); }]; [objAlertController addAction:cancelAction]; [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{ }]; }
现在在任何视图控制器和 IBAction 中创建一个按钮,使用以下代码:
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil]; objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil]; objNotificationContent.sound = [UNNotificationSound defaultSound]; // 4. update application icon badge number objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1); // Deliver the notification in five seconds. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10.f repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten” content:objNotificationContent trigger:trigger]; // 3. schedule localNotification UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@“Local Notification succeeded“); } else { NSLog(@“Local Notification failed“); } }];
Swift 3:
斯威夫特 3:
- In
AppDelegate.swift
file useimport UserNotifications
- Appdelegate should conform to
UNUserNotificationCenterDelegate
protocol In
didFinishLaunchingWithOptions
use below code// Override point for customization after application launch. let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. if error != nil { print("Request authorization failed!") } else { print("Request authorization succeeded!") self.showAlert() } } func showAlert() { let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert) objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) //self.presentViewController(objAlert, animated: true, completion: nil) UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil) }
Now create a button in any view controller and in IBAction use below code :
let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil) content.sound = UNNotificationSound.default() content.categoryIdentifier = "notify-test" let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false) let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request)
- 在
AppDelegate.swift
文件使用中import UserNotifications
- Appdelegate 应该符合
UNUserNotificationCenterDelegate
协议 正在
didFinishLaunchingWithOptions
使用下面的代码// Override point for customization after application launch. let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. if error != nil { print("Request authorization failed!") } else { print("Request authorization succeeded!") self.showAlert() } } func showAlert() { let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert) objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) //self.presentViewController(objAlert, animated: true, completion: nil) UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil) }
现在在任何视图控制器和 IBAction 中创建一个按钮,使用以下代码:
let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil) content.sound = UNNotificationSound.default() content.categoryIdentifier = "notify-test" let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false) let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request)
回答by Madhu
In appdelegate.m file write the follwing code in applicationDidEnterBackground to get the local notification
在 appdelegate.m 文件中,在 applicationDidEnterBackground 中写入以下代码以获取本地通知
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
回答by Kashfa Khan
Creating local notifications are pretty easy. Just follow these steps.
创建本地通知非常简单。只需按照以下步骤操作即可。
On viewDidLoad() function ask user for permission that your apps want to display notifications. For this we can use the following code.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in })
Then you can create a button, and then in the action function you can write the following code to display a notification.
//creating the notification content let content = UNMutableNotificationContent() //adding title, subtitle, body and badge content.title = "Hey this is Simplified iOS" content.subtitle = "iOS Development is fun" content.body = "We are learning about iOS Local Notification" content.badge = 1 //getting the notification trigger //it will be called after 5 seconds let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) //getting the notification request let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger) //adding the notification to notification center UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
Notification will be displayed, just click on home button after tapping the notification button. As when the application is in foreground the notification is not displayed. But if you are using iPhone X. You can display notification even when the app is in foreground. For this you just need to add a delegate called UNUserNotificationCenterDelegate
在 viewDidLoad() 函数中,请求用户许可您的应用程序想要显示通知。为此,我们可以使用以下代码。
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in })
然后你可以创建一个按钮,然后在action函数中你可以编写如下代码来显示一个通知。
//creating the notification content let content = UNMutableNotificationContent() //adding title, subtitle, body and badge content.title = "Hey this is Simplified iOS" content.subtitle = "iOS Development is fun" content.body = "We are learning about iOS Local Notification" content.badge = 1 //getting the notification trigger //it will be called after 5 seconds let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) //getting the notification request let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger) //adding the notification to notification center UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
将显示通知,只需点击通知按钮后单击主页按钮。当应用程序处于前台时,不会显示通知。但如果您使用的是 iPhone X。即使应用程序在前台,您也可以显示通知。为此,您只需要添加一个名为UNUserNotificationCenterDelegate的委托
For more details visit this blog post: iOS Local Notification Tutorial
有关更多详细信息,请访问此博客文章:iOS 本地通知教程
回答by swiftBoy
Updated with Swift 5Generally we use three type of Local Notifications
更新为Swift 5通常我们使用三种类型的本地通知
- Simple Local Notification
- Local Notification with Action
- Local Notification with Content
- 简单的本地通知
- 带操作的本地通知
- 带有内容的本地通知
Where you can send simple text notification or with action button and attachment.
您可以在其中发送简单的文本通知或带有操作按钮和附件。
Using UserNotifications package in your app, the following example Request for notification permission, prepare and send notification as per user action AppDelegate itself, and use view controller listing different type of local notification test.
在您的应用程序中使用 UserNotifications 包,以下示例请求通知权限,根据用户操作 AppDelegate 本身准备和发送通知,并使用视图控制器列出不同类型的本地通知测试。
AppDelegate
应用程序委托
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Confirm Delegete and request for permission
notificationCenter.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
//MARK: Local Notification Methods Starts here
//Prepare New Notificaion with deatils and trigger
func scheduleNotification(notificationType: String) {
//Compose New Notificaion
let content = UNMutableNotificationContent()
let categoryIdentifire = "Delete Notification Type"
content.sound = UNNotificationSound.default
content.body = "This is example how to send " + notificationType
content.badge = 1
content.categoryIdentifier = categoryIdentifire
//Add attachment for Notification with more content
if (notificationType == "Local Notification with Content")
{
let imageName = "Apple"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
//Add Action button the Notification
if (notificationType == "Local Notification with Action")
{
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: categoryIdentifire,
actions: [snoozeAction, deleteAction],
intentIdentifiers: [],
options: [])
notificationCenter.setNotificationCategories([category])
}
}
//Handle Notification Center Delegate methods
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "Local Notification" {
print("Handling notifications with the Local Notification Identifier")
}
completionHandler()
}
}
and ViewController
和视图控制器
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var appDelegate = UIApplication.shared.delegate as? AppDelegate
let notifications = ["Simple Local Notification",
"Local Notification with Action",
"Local Notification with Content",]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notifications.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = notifications[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let notificationType = notifications[indexPath.row]
let alert = UIAlertController(title: "",
message: "After 5 seconds " + notificationType + " will appear",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
self.appDelegate?.scheduleNotification(notificationType: notificationType)
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
回答by cathy.s
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:]
before being able to schedule and present UILocalNotifications, do not forget this.
这是可行的,但在 iOS 8.0 及更高版本中,您的应用程序必须-[UIApplication registerUserNotificationSettings:]
在能够安排和呈现 UILocalNotifications 之前注册用户通知,不要忘记这一点。
回答by Manoj Kumar
iOS 8 users and above, please include this in App delegate to make it work.
iOS 8 及以上用户,请将此包含在 App 委托中以使其工作。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
{
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
return YES;
}
And then adding this lines of code would help,
然后添加这行代码会有所帮助,
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
回答by Ashutosh Shukla
I am assuming that you have requested for authorisation and registered your app for notification.
我假设您已请求授权并注册了您的应用程序以获取通知。
Here is the code to create local notifications
这是创建本地通知的代码
@available(iOS 10.0, *)
func send_Noti()
{
//Create content for your notification
let content = UNMutableNotificationContent()
content.title = "Test"
content.body = "This is to test triggering of notification"
//Use it to define trigger condition
var date = DateComponents()
date.calendar = Calendar.current
date.weekday = 5 //5 means Friday
date.hour = 14 //Hour of the day
date.minute = 10 //Minute at which it should be sent
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let uuid = UUID().uuidString
let req = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(req) { (error) in
print(error)
}
}
回答by shikha kochar
-(void)kundanselect
{
NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
NSArray *allControllersCopy = [allControllers copy];
if ([[allControllersCopy lastObject] isKindOfClass: [kundanViewController class]])
{
[[NSNotificationCenter defaultCenter]postNotificationName:@"kundanViewControllerHide"object:nil userInfo:nil];
}
else
{
[[NSUserDefaults standardUserDefaults] setInteger:4 forKey:@"selected"];
[self performSegueWithIdentifier:@"kundansegue" sender:self];
}
}
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];