UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
})
然后您可以创建一个按钮,然后在操作功能中,您可以编写以下代码来显示通知 .
//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)
6 回答
以下是适用于我的项目的LocalNotification的示例代码 .
Objective-C:
AppDelegate
文件中的此代码块:任何
ViewController
的.m文件中的此代码块:上面的代码显示一个AlertView后7秒的时间间隔按下按钮时绑定
startLocalNotification
如果应用程序在后台,则它显示BadgeNumber
为10并具有默认通知声音 .此代码适用于iOS 7.x及更低版本,但对于iOS 8,它将在控制台上提示以下错误:
这意味着您需要注册本地通知 . 这可以通过以下方式实现:
您也可以参考blog进行本地通知 .
Swift:
你
AppDelegate.swift
文件应该如下所示:要在其中创建本地通知的swift文件(例如
ViewController.swift
)应包含以下代码:The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.
苹果发布说明下面的屏幕抓取描述了这一点 .
您可以参考apple reference document进行UserNotification .
以下是本地通知的代码:
Objective-C:
在
App-delegate.h
文件中使用@import UserNotifications;
App-delegate应符合
UNUserNotificationCenterDelegate
协议在
didFinishLaunchingOptions
使用以下代码:Swift 3:
在
AppDelegate.swift
文件中使用import UserNotifications
Appdelegate应符合
UNUserNotificationCenterDelegate
协议在
didFinishLaunchingWithOptions
中使用以下代码在appdelegate.m文件中,在applicationDidEnterBackground中编写以下代码以获取本地通知
创建本地通知非常简单 . 只需按照以下步骤操作
有关详细信息,请访问此博文: iOS Local Notification Tutorial
这是有效的,您的应用程序必须使用
-[UIApplication registerUserNotificationSettings:]
注册用户通知才能安排和呈现UILocalNotifications,不要忘记这一点 .iOS 8及以上用户,请在App委托中包含此功能以使其正常工作 .
然后添加这行代码会有所帮助,
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];