gpt4 book ai didi

swift - 管理同一部手机上多个用户的 APN 通知

转载 作者:行者123 更新时间:2023-11-28 06:42:55 25 4
gpt4 key购买 nike

我想知道当许多用户在同一台​​设备上使用同一应用程序时如何管理 Apple 推送通知,因为每台设备的设备 token 都是唯一的。

如果我在同一台设备上的应用程序上有 2 个注册用户,如果通知是针对用户 A 但用户 B 当前已登录到应用程序,如何防止推送通知出现?

如果应用程序在前台,则可以通过用户 ID 轻松管理,如果 APN 不适用于该用户,该用户 ID 会阻止代码执行。

但是如果应用程序在后台怎么处理呢?设备将收到 APN,发出警报,并显示通知,无论用户当前登录到应用程序是什么...

最佳答案

根据您关于在应用程序位于前台时能够处理这种情况的评论,我假设通知包含一些信息来识别通知所针对的用户。似乎如果您在 NSUserDefaults 中存储一些标识当前登录用户的信息,您应该能够在 didReceiveRemoteNotification 中检索该信息并根据该信息决定是否通知是否应该处理。

更新添加更多信息:

您还需要实现 application:didReceiveRemoteNotification:fetchCompletionHandler并将您的通知变成“无声”通知,然后在从要抑制的通知中过滤出要显示的通知后,您将为要显示的通知创建本地通知。您还需要在您的 info.plist 中添加一个 UIBackgroundModes 并在您的有效负载中包含一个“内容可用”键。参见 here了解更多详情。

<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>remote-notification</string>
</array>

关键实现带有 fetchCompletionHandler 的版本,因为当应用程序处于后台时不会调用没有它的版本。

这是我的一个应用程序的示例,它接收位置更新请求的“静默”通知,还接收一些“非静默”通知。如果应用程序处于事件状态,我会显示“toast”,如果应用程序在后台,我会根据远程通知创建本地通知,然后触发它。

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void ) {
log?.info("******* got a remote message = \(userInfo) *******")
let message: String = (userInfo["message"] ?? "stop") as! String
log?.info("message = \(message)")
switch message {
case "update_locations":
log?.info("starting location update cycle")
locationUploader?.startUploading(handler)
case "micropost_created":
log?.info("got a new micropost notification")
let notification = UILocalNotification()
let userName = userInfo["user_name"] as? String ?? ""
let content = userInfo["content"] as? String ?? ""
notification.alertTitle = "Micropost from \(userName)"
let alertBody = "\(userName) said: \(content)"
notification.alertBody = alertBody
notification.soundName = UILocalNotificationDefaultSoundName
application.presentLocalNotificationNow(notification)
if let topMostView = application.keyWindow {
topMostView.makeToast(message: alertBody)
}
handler(.NewData)
default:
handler(.NoData)
}
}

关于swift - 管理同一部手机上多个用户的 APN 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com