在我的应用程序中,我有复杂的架构,所以一开始就有一点理论。当我收到远程通知时,我会呼叫
NotificationCenter.default.post(Notification.Name("myName"),
object: nil,
userInfo: userInfo)在AppDelegate中。
在另一个文件中,我使用选择器函数创建了一个UIViewController扩展名,如下所示:
func myFunction(_ notification: Notification) { }现在,我在我的视图控制器中所做的事情(让我们称他为MyVC),我称之为
override viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self,
selector:#selector(myFunction),
name: Notification.Name("myName"),
object: nil)
}MyVC包含带有对象的数组。当应用程序收到推送通知时,我需要在myFunction中处理这个数组,但实际上我不知道如何传递它。
我尝试的是在选择器函数中添加额外的参数,但没有成功。我能以某种方式实现吗?
编辑:以及如何将我的数组传递到.addObserver函数中的object参数中?我能通过调用myFunction notification.object来获取它吗?
发布于 2017-05-17 12:38:48
可以通过以下方式将通知传递给myFunction
NotificationCenter.default.addObserver(self, selector: #selector(myFunction(_:)), name: Notification.Name("myName"), object: nil)然后在myFunction中处理通知,从通知对象的userInfo中提取数据。
发布于 2017-05-17 12:49:05
在AppDelegate :中接收远程通知
//---------------------------------------------------------
// Notification event received when APN comes in ... pre 10.0+
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
{
RemoteNotificationProcessor.handleRemoteNotification(userInfo, handler : completionHandler)
}
//-------------------------------------------------------------------------
// UNUserNotificationDelegate implementation 10.0+
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
// Received a Local or Remote Notification (ios 10.0+), we can do what we want
RemoteNotificationProcessor.handleRemoteNotification(notification, handler : completionHandler)
}实现RemoteNotificationProcessor (传递信息):
// NON 10.0+ version....
class func handleRemoteNotification(_ notif : [AnyHashable : Any],
handler : @escaping (UIBackgroundFetchResult) -> Void)
{
NotificationCenter.default.post(name: Notification.Name("myName"),
object: nil,
userInfo: notif)
handler(UIBackgroundFetchResult.newData)
}
@available(iOS 10.0, *)
class func handleRemoteNotification(_ notif : UNNotification,
handler : @escaping (UNNotificationPresentationOptions)->Void)
{
guard let trigger = notif.request.trigger else {
print("Don't know origin of notification trigger")
handler([.alert, .badge, .sound])
return
}
if trigger is UNPushNotificationTrigger {
if let json = notif.request.content.userInfo as? [String : Any]
{
NotificationCenter.default.post(name: Notification.Name("myName"),
object: nil,
userInfo: info)
}
else {
print("Notified other than APN")
}
handler([.alert, .badge, .sound])
}处理#选择器中的数据
@objc
func myFunction(_ notification : Notification)
{
if let info = (notification as NSNotification).userInfo {
}
}https://stackoverflow.com/questions/44024040
复制相似问题