iOS26适配指南之通知

介绍

  • UIKit 带来了强类型通知,为通知系统带来了期待已久的类型与并发安全性。
  • 不再使用基于字符串的标识符以及通过userInfo字典传递数据,该种方式存在线程安全、拼写错误、类型转换等问题。
  • 通过全新的并发安全通知协议NotificationCenter.MainActorMessage(主线程消息)与NotificationCenter.AsyncMessage(异步消息)可以做到编译时检测,从而提前发现潜在的问题。
  • 与老版本的通知系统完全兼容。

使用

  • 代码。
swift 复制代码
import UIKit

public class NotificationSubject {
    static let shared = NotificationSubject()
}

// MARK: - 消息类型
public struct CustomMainActorMessage: NotificationCenter.MainActorMessage {
    // 发送者
    public typealias Subject = NotificationSubject
    public static var name: Notification.Name {
        .init("CustomMainActorMessage")
    }

    // 数据
    let info: String
}

class ViewController: UIViewController {
    lazy var label: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
        label.textAlignment = .center
        label.text = "暂无通知消息"
        label.center = view.center
        return label
    }()

    var mainActorMessageToken: NotificationCenter.ObservationToken!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(label)
        // 监听通知
        mainActorMessageToken = NotificationCenter.default.addObserver(of: NotificationSubject.shared, for: CustomMainActorMessage.self) { message in
            self.label.text = "\(message.info)"
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // 发送通知
        NotificationCenter.default.post(CustomMainActorMessage(info: "you have a new message"), subject: NotificationSubject.shared)
    }

    deinit {
        NotificationCenter.default.removeObserver(mainActorMessageToken)
    }
}
  • 效果。
相关推荐
00后程序员张19 小时前
从审核被拒到稳定过审,iOS 上架技术优化
android·ios·小程序·https·uni-app·iphone·webview
健了个平_241 天前
LottieConverter:一键生成 .lottie 文件
ios·chatgpt·动效
开心就好20251 天前
Win11 抓包工具怎么选?网页请求与设备流量抓取
后端·ios
恋猫de小郭1 天前
你的蓝牙设备可能正在泄漏你的隐私? Bluehood 如何追踪附近设备并做隐私分析
android·前端·ios
UXbot1 天前
AI App 设计生成工具哪个好?
ui·kotlin·软件构建·产品经理·ai编程·swift
FreeBuf_1 天前
Coruna漏洞利用工具揭示Triangulation iOS攻击框架的演进
macos·ios·cocoa
2501_915918411 天前
WebKit 抓包,WKWebView 请求的完整数据获取方法
android·前端·ios·小程序·uni-app·iphone·webkit
黄林晴1 天前
Swift 杀进 Android,Google 和 Apple 都要失眠了?
android·前端·swift
东坡肘子2 天前
一墙之隔,不同的时空 -- 肘子的 Swift 周报 #129
人工智能·swiftui·swift