来搞一搞UserNotifications本地通知

本文介绍了从iOS 10开始的通知权限变化,并提供了一个简单的示例代码来展示如何请求用户的授权来发送本地通知。此外,文章强调了用户体验的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 UIKit
import UserNotifications

class 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 = "起床啦!你老婆跟人跑了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值