Iphone 如何发布和接收NSC通知(目标C)|通知(Swift)?
是否有一种简单的模式,即如何发送NSNotification(目标C)|通知(Swift)以及如何接收通知?代码片段?这些文档在这个主题上写了150页。我想看一个简单的例子Iphone 如何发布和接收NSC通知(目标C)|通知(Swift)?,iphone,notifications,nsnotificationcenter,nsnotifications,Iphone,Notifications,Nsnotificationcenter,Nsnotifications,是否有一种简单的模式,即如何发送NSNotification(目标C)|通知(Swift)以及如何接收通知?代码片段?这些文档在这个主题上写了150页。我想看一个简单的例子 注册推送通知配置文件,并在应用程序中进行设置。此处有一个链接可用于注册推送通知配置文件(请注意,您需要一些服务器或捕获设备推送通知ID的设备,以便能够向这些设备发送通知) 接下来,假设您使用的是Windows服务器或与.net兼容的服务器,有一个很好的C#api,用于向apple服务器发送推送通知(一旦您拥有证书和存储在服务
[[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()
}
在要接收通知的控制器上:
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()
}
他没有询问推送通知。当然,他可能是有意的,但他不是这么说的:——)@Paul你是对的——但我认为Daniel选择了正确的答案,因为我真的想知道除了推送通知之外,应用程序应该如何接收通知。--只要阅读你的答案,是的,这当然也是一个通知:)通知是iPhone编程中常见的习惯用法。请参阅下面的答案。我指的是来自NSNotificationCenter的通知;-)但是很高兴知道推送通知是如何工作的。谢谢是的,问题是关于通知中心不用于推送通知。-(void)cacheUpdated:(NSNotification*)通知{[self load];}