iOS 10 UserNotifications 入门学习笔记

iOS 10 中的通知 API 已经抛弃了之前本地通知和远程通知分开的情况,并且加入了通知附件等新特性,今天在 YouTube 上着了个教程,学习了一下本地通知,完成的代码在这里

获取通知权限

首先引入 UserNotifications 头文件

import UserNotifications

打开项目 AppDelegate.swift 中,在 application:didFinishLaunchingWithOptions: 方法中插入获取通知权限的代码:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler:{ (granted, error) in
            if granted {
                print("获取通知权限成功")
            }else {
                print(error?.localizedDescription)
            }
        })

实现通知

新建一个方法 scheduleNotification,插入如下代码:

let content = UNMutableNotificationContent()
        content.title = "Pop Quiz!"
        content.subtitle = "Let's see how smart you are!"
        content.body = "How many countries are there in Africa?"
        content.badge = 1
        content.categoryIdentifier = "quizCategory"
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let requestIdentifer = "africaQuzi"
        let request = UNNotificationRequest(identifier: requestIdentifer, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
            //handle error
        })

关联并执行这个方法,按下主按钮,5 秒后就会触发本地通知。

程序前台时也执行通知

首先继承 UNUserNotificationCenterDelegate, 在 viewDidLoad 方法中,将 delegate 设置为 self

UNUserNotificationCenter.current().delegate = self

实现 userNotificationCenter: willPresent notification: 方法:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }

加入通知按钮和响应

首先要在 application:didFinishLaunchingWithOptions: 方法中初始化通知 Category

let answerOne = UNNotificationAction(identifier: "answerOne", title: "29", options: [.foreground])
        let answerTwo = UNNotificationAction(identifier: "answerTwo", title: "23", options: [.foreground])
        let clue = UNNotificationAction(identifier: "clue", title: "Get a clue...", options: [.foreground])
        
        let quizCategory = UNNotificationCategory(identifier: "quizCategory", actions: [answerOne, answerTwo, clue], intentIdentifiers: [], options: [])
        
        UNUserNotificationCenter.current().setNotificationCategories([quizCategory])

然后实现 userNotificationCenter:didReceive: 方法:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        switch response.actionIdentifier {
        case "answerOne":
            imageView.image = UIImage(named: "pig")
        case "answerTwo":
            imageView.image = UIImage(named: "birth_invite")
        case "clue":
            let alert = UIAlertController(title: "Hint", message: "你个大笨蛋", preferredStyle: UIAlertControllerStyle.alert)
            let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
            alert.addAction(action)
            self.present(alert, animated: true, completion: nil)
        default: break
        }
    }

就可以在通知时执行方法。

Comments
Write a Comment