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)
    }
}
  • 效果。
相关推荐
咕噜企业签名分发-淼淼2 小时前
App防止恶意截屏功能的方法:iOS、Android和鸿蒙系统的实现方案
android·ios·harmonyos
Dream_Ji2 小时前
Swift入门(二 - 基本运算符)
服务器·ssh·swift
游戏开发爱好者87 小时前
iOS 26 崩溃日志深度解读,获取方式、系统变动、定位策略
android·macos·ios·小程序·uni-app·cocoa·iphone
深盾科技10 小时前
如何读懂Mach-O:构建macOS和iOS应用安全的第一道认知防线
安全·macos·ios
FreeBuf_12 小时前
iOS 0Day漏洞CVE-2025-24085相关PoC利用细节已公开
macos·ios·cocoa
林鸿群15 小时前
MacOS arm64 编译GStreamer iOS平台库
macos·ios
2501_916007471 天前
iOS 混淆与团队协作,研发、安全、运维、测试如何在加固流程中高效配合(iOS 混淆、ipa 加固、协作治理)
android·ios·小程序·https·uni-app·iphone·webview
HarderCoder1 天前
Swift 6.1 `withTaskGroup` & `withThrowingTaskGroup` 新语法导读
ios·swift
HarderCoder1 天前
Swift 并发:Actor、isolated、nonisolated 完全导读
ios·swift
贝多财经1 天前
OPPO手机“绿线”问题争议,高价等于高端,何以分食iPhone市场?
ios·智能手机·iphone