「Swift」通知Notification使用方法

前言:我们数据通常是页面与页面之间的传递,但一旦需要传递的两个页面不是相邻的两个页面并且相距较远,数据的传递就稍显麻烦,以及跨组件之间的数据传递也令人头疼;所以此时使用通知就会非常方面和不受局限性

1.初始化通知Notification

通常在每个组件的定义,初始化的文件中进行初始化

/// 通知
extension Notification.Name {
    struct Release {
        /// 成功发布信息通知
        public static let ReleaseSuccess = Notification.Name(rawValue: "ReleaseSuccess")
    }
}
2.通知Notification监听

在需要收到数据,收到响应的页面进行通知的监听
ps:记得建立监听后也需要在同页面进行监听的销毁

/// 建立监听
/// selector:收到通知后会执行的操作
/// name:监听的通知名称
private func addNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleReleaseSuccess), name: Notification.Name.Release.ReleaseSuccess, object: nil)
    }
 
/// 销毁监听   
deinit {
     NotificationCenter.default.removeObserver(self)
 }
 
/// 收到通知后执行的操作
/// 可以通过userInfo获取到通知传递的数据
@objc
private func handleReleaseSuccess(notifi: Notification) {
    ///执行收到通知后的操作
   if let leaseType = notifi.userInfo?["leaseType"] as? Int {
            if leaseType == 1 {
                pring("leaseType")
                
            }else {
                pring(leaseType)
            }
        }
}
3.发送通知Notification
 /// 发送发布成功通知
 /// 可以通过userInfo进行数据的传递,userInfo类型如同字典
NotificationCenter.default.post(name: Notification.Name.Release.ReleaseSuccess, object: nil, userInfo: ["leaseType": 1])

整理不易,如有帮助,请多多点赞收藏!谢谢大家!

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
发出的红包

打赏作者

淡酒交魂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值