本例仅涉及本地通知,远程推送(APNs)鉴于证书的获得性这里不做介绍,网上有很多可供参考。
使用:
在待使用的类前先import。
import UserNotifications
首先先在AppDelegate里面申请权限。
import UIKit
import UserNotifications
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
(accepted, error) in
if !accepted {
print("Failed to apply permession.")
}
}
return true
}
}
接着定义推送方法:
private func sendNotice() {
// Define content.
let content = UNMutableNotificationContent()
content.title = "Compent"
content.subtitle = "Nice! I'll got it for u."
content.body = "Nancy.Losie"
content.sound = .defaultCritical
content.launchImageName = "taylor"
// Define trigger.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let requestIdentifier = "com.my.compent"
let request = UNNotificationRequest(identifier: requestIdentifier,
content: content, trigger: trigger)
// Add notification into NotificationCenter.
UNUserNotificationCenter.current().add(request) { error in
if error == nil {
print("Time Interval Notification scheduled: \(requestIdentifier)")
}
}
}
调用该方法后启动应用程序,10s后就收到通知了。
内容体:
内容体是用户能看到的对象,其包括标题、子标题、声音、图像等。
多媒体交互:
iOS10后支持多媒体交互。比较明显的看到使用多媒体交互的效果有Apple Music的新专辑推送,下面模拟一下:
private func sendNotice() {
let content = UNMutableNotificationContent()
content.title = "Apple Music"
content.subtitle = "<<Lover>>"
content.body = "Taylor Swift all new album to explore."
content.sound = .defaultCritical
// Picture.
if let imageURL = Bundle.main.url(forResource: "taylor", withExtension: "jpeg"),
let attachment = try? UNNotificationAttachment(identifier: "testImage",
url: imageURL, options: nil) {
content.attachments = [attachment]
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let requestIdentifier = "com.my.compent"
let request = UNNotificationRequest(identifier: requestIdentifier,
content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if error == nil {
print("Time Interval Notification scheduled: \(requestIdentifier)")
}
}
}
效果(支持3D Touch、Haptic Touch):
触发器:
触发器(仅限于本地通知,APNs无效)是决定本地通知的触发效果的。
指定过了多久触发:
repeats用于决定发送后是否重复。
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
指定何时触发:
var components = DateComponents()
components.year = 2021
components.month = 6
components.day = 20
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)