Swift使用通知Notification

 

通知简介

通知(Notification)是观察者模式(observer)中的一种, 结构为: 发布者 -> 通知中心 -> 接收者, 是iOS 开发中常用通信方式,为单例模式使用。可以实现一对一、一对多通信。

原理如下图:

传统通知使用

监听通知

 /// 监听通知
    private func registerNoti() -> Void {
        NotificationCenter.default.addObserver(self, selector: #selector(receive(noti:)), name: NSNotification.Name("viewNotiSecond"), object: nil)
    }

发送通知

/// 发送通知
    func postNoti() -> Void {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "viewNotiSecond"), object: nil, userInfo: nil)
    }

 

更优雅的使用通知

参考: Swift extension 扩展Tips

何为更优雅,有Swfit语言风格兼顾便于统一与管理[当有多个通知或者Selector方法]

扩展Notification.Name

extension Notification.Name {
    static let viewNotiSecond = Notification.Name(rawValue: "viewNotiSecond")
}

扩展Selector

fileprivate extension Selector {
    static let viewNotiSecond = #selector(ViewController.receive(noti:))
}

注册通知

注册通知时,只需要通过点语法即可,而Selector扩展前加入权限控制防止污染其他地方的扩展。

 /// 注册通知
    private func registerNoti() -> Void {
        NotificationCenter.default.addObserver(self, selector: .viewNotiSecond, name: .viewNotiSecond, object: nil)
    }

发送通知

/// 发送通知
    func postNoti() -> Void {
        NotificationCenter.default.post(name: .viewNotiSecond, object: nil, userInfo: nil) //直接通过点语法即可  
    }

注意操作

由于通知是单列的,所以使用完后必须在析构deinit中移除通知,否则后期将引发难以查询的莫名错误

 deinit {
        // 移除通知
        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.removeObserver(self, name: .viewNotiSecond, object: nil) // 移除特定通知
    }

总结

传统方法缺点,容易导致发送端与注册端通知名字拼写错误

优雅的方式,缺陷是可能会增加一点代码, 优点是增加代码模块性,避免拼写错误。统一管理方法。

 

 

SwiftUI中,你可以使用UserNotifications框架来实现推送通知。UserNotifications框架允许你创建本地和远程推送通知,并在用户设备上展示。下面是一个简单的示例代码,展示如何创建本地推送通知: ``` import UserNotifications struct ContentView: View { var body: some View { Button("Send Notification") { let content = UNMutableNotificationContent() content.title = "New Message" content.body = "You have a new message" content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: "message", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } } } ``` 在这个例子中,我们在ContentView视图中创建了一个Button,并在点击按钮时创建了一个本地推送通知。我们使用UNMutableNotificationContent来设置通知的标题、内容和声音。然后,我们使用UNTimeIntervalNotificationTrigger来设置通知触发时间,这里我们设置了5秒后触发。最后,我们使用UNNotificationRequest来创建通知请求,并使用UNUserNotificationCenter将通知请求添加到用户设备上。 需要注意的是,你需要在应用程序启动时请求用户授权,才能在用户设备上展示推送通知。可以使用UNUserNotificationCenter的requestAuthorization方法来请求授权。此外,远程推送通知需要在后台服务器上进行设置和处理,需要使用APNs证书来进行身份验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值