前言:
推播有分2種,本地推播和遠端推播
由於iOS的遠端推播較為麻煩(需透過蘋果的APNS)
故本篇以本地推播為主
正文:
本地推播通知有三種
指定時間,發送通知(Day19有提到用法)
UNCalendarNotificationTrigger
進入或離開某個範圍,發送通知(本篇不會用到)
UNLocationNotificationTrigger
間隔多久,發送通知
UNTimeIntervalNotificationTrigger
首先要實作這個方法
class AppDelegate: ...,UNUserNotificationCenterDelegate{
在AppDelegate下 加上
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 在程式一啟動即詢問使用者是否接受圖文(alert)、聲音(sound)、數字(badge)三種類型的通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge, .carPlay], completionHandler: { (granted, error) in
if granted {
print("允許")
} else {
print("不允許")
}
})
// 代理 UNUserNotificationCenterDelegate,這麼做可讓 App 在前景狀態下收到通知
UNUserNotificationCenter.current().delegate = self
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("在前景收到通知...")
completionHandler([.badge, .sound, .alert])
}
接著到要推播的頁面 加上
func notification() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
let content = UNMutableNotificationContent()
content.title = "驗證碼通知"
content.subtitle = "驗證碼為"
content.body = "\(verificationcode)"
content.sound = UNNotificationSound.default
//timeInterval 幾秒後推播
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in
print("成功建立通知...")
})
}
再利用程式呼叫 notification()