如何在 iOS 推送通知后在除一个视图之外的任何地方显示 UIAlertView

How to display an UIAlertView after a iOS push notification everywhere except in one view

我正在尝试做一个小信使,我想显示一个警告,说除了对话本身之外,应用程序上的所有地方都收到了一条新消息。现在我的警报无处不在,是否可以对其进行过滤,使其不显示在 ConversationDetailController 上?

这是我在 appdelegate 中的代码

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

    var mess:String?
    var displayName:String?


    if let result = userInfo["aps"] as? NSDictionary {

        if let alert = result["alert"] as? String {

            mess = alert

            if let extra = userInfo["extra"] as? NSDictionary
            {

                if let name = extra["displayName"] as? String
                {

                    displayName = name

                    var alert = UIAlertView(title: "You have a new message from \(displayName!)", message: mess, delegate: nil, cancelButtonTitle: "OK")
                    alert.show()

                }

            }
            NSNotificationCenter.defaultCenter().postNotificationName("newMessageReceived", object: nil)

        }

    }

}

您可以按照以下方式做一些事情:

  1. 创建一个新的 class,这是一个警报演示文稿管理器
  2. 在收到通知时创建此 class 的实例
  3. 将所有警报逻辑移至 class
  4. 应用程序委托 post发送 newMessageReceived 通知并将演示文稿管理器作为对象传递
  5. 任何看到通知的人都可以向演示管理员询问有关通知的详细信息并取消演示
  6. 如果有人取消,则不会显示通知
  7. 在 post 发送通知后,应用程序委托要求演示管理器 presentAlertIfAppropriate(检查它是否已被取消)

通知直接发送给所有观察者,所以此时您可以post通知并立即检查是否需要演示。给通知的收件人一些时间来决定是否取消可能会更好,但如果您需要执行类似的操作,事情就会变得更加复杂...