来搞一搞UserNotifications本地通知

来源:互联网 发布:广西网络电视台 编辑:程序博客网 时间:2024/06/16 11:51

UserNotifications
UserNotificationsUI
Human Interface Guidelines - Notifications
Local and Remote Notification Programming Guide
Introduction to Notifications
Advanced Notifications
What's New in the Apple Push Notification Service
Rich Notifications
Best Practices and What’s New in User Notifications

  从iOS 10开始,与通知有关的API发生了不小的变化,在使用时,除了需要导入独立的UserNotifications框架之外,还需要获取用户授权:

import UIKitimport UserNotificationsclass ViewController: UIViewController {    /// 用于标记通知权限(默认为false)    var isGrantedNotificationAccess = false    override func viewDidLoad() {        super.viewDidLoad()        // 获取通知权限        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in            // 当用户点击“Allow”时,granted的值为true,            // 当用户点击“Don't Allow”时,granted的值为false            self.isGrantedNotificationAccess = granted            // 如果没有获取到用户授权,就会执行下面的代码            if !granted {                // 可以考虑在这里执行一个弹窗,提示用户获取通知权限                print("需要获取通知权限才能发送通知.")            }        }    }}

  不管你是发送本地通知,还是远程通知,它本身就是一种中断用户的行为,因此,将是否需要接收通知的权限交还给用户,可以最大限度的提升用户体验:


获取用户授权

一、通知的基本使用

  点击“Allow”,获取发送通知的权限,以便后续顺利进行相应的演示。来到Main.storyboard文件中,布局几个按钮,然后给它们拖线。然后回到ViewController文件中,在拖线代码中实现相应的功能:

// MARK: - 发送通知@IBAction func sendNotifications(_ sender: UIButton) {    // 如果获取到发送通知的权限    if isGrantedNotificationAccess {        // 创建通知的内容        let content = UNMutableNotificationContent()        // 设置通知默认提示音        content.sound = UNNotificationSound.default()        // 设置通知的标题        content.title = "紧急通知"        // 设置通知的内容        content.body = "起床啦!你老婆跟人跑了! 
原创粉丝点击