有没有一种易于理解的模式来发送一个NSNotification(Objective C)| Notification(Swift),以及如何接收一个?代码片段呢?文档在这个主题上写了大约150页。希望能看到一个快速的例子。
有没有一种易于理解的模式来发送一个NSNotification(Objective C)| Notification(Swift),以及如何接收一个?代码片段呢?文档在这个主题上写了大约150页。希望能看到一个快速的例子。
发送通知:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyCacheUpdatedNotification" object:self];
收到它:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cacheUpdated:) name:@"MyCacheUpdatedNotification" object:nil];
采取行动:
- (void)cacheUpdated:(NSNotification *)notification {
[self load];
}
并且将其处理掉:
[[NSNotificationCenter defaultCenter] removeObserver:self];
相应的Swift版本:
在需要发布通知时:
最初的回答
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UpdateAccepted"), object: self)
最初的回答:
在您希望接收通知的控制器中:override func viewDidLoad(_ animated: Bool) {
super.viewDidLoad(true) {
NotificationCenter.default.addObserver(self, selector: #selector(updateAccepted(notification:)), name: NSNotification.Name(rawValue: "UpdateAccepted"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "UpdateAccepted"), object: nil)
}
@objc func updateAccepted(notification: Notification) {
handleRefresh()
}
注册推送通知配置文件并在您的应用程序中设置它,这里是一个链接 PushNotification (请注意,您需要一些服务器或其他捕获设备推送通知ID的东西才能向这些设备发送通知)
接下来,假设您正在使用Windows Server或其他与.net兼容的服务器作为您的服务器,则有一个很好的C# API编写用于向苹果服务器发送推送通知(一旦您拥有证书和已在其中注册了设备并将其存储在您的服务器上),这里有演示如何使用它的演示,非常酷,这里是一个链接 C# push notification src
就是这样...我给了您一个快速解决方案,使用了.Net技术,如果您使用其他平台,可以浏览一下看看是否有可用的解决方案,我相信您会找到一些,如果没有,您总是可以自己制作 :)