Swift如何在paymentQueueRestoreCompletedTransactionsFinished中显示警报?

时间:2016-06-15 17:40:42

标签: swift alert

我已经实现了以下代码,但我收到了一条警告消息:

  

警告:尝试显示其视图不在窗口层次结构中!   在paymentQueueRestoreCompletedTransactionsFinished(队列:SKPaymentQueue)

并且不显示警报。 [edit]如果我旋转手机,则会在旋转[/ edit]

之后显示警告

这是我的代码:

func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
    alert("Félicitations", message: "Vous avez restauré vos packs, cliquez sur ok pour les télécharger !")

}

func alert(title:String, message:String = "") {
    let alert = UIAlertController(title: title, message:message, preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in
        if title == "Félicitations" {
            let next = self.storyboard?.instantiateViewControllerWithIdentifier("TelechargementVC") as! TelechargementViewController
            self.presentViewController(next, animated: true, completion: nil)

        }

        })
    self.presentViewController(alert, animated: true){}

}

注意:从其他功能调用警报功能没有问题。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

感谢这篇有用的帖子:https://stackoverflow.com/a/26667122/5030969 我已经更改了alert函数以获取最顶层的视图控制器并从那里创建presentViewController

func alert(title:String, message:String = "") {

    if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
        // topController should now be your topmost view controller
        let alert = UIAlertController(title: title, message:message, preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in
            if title == "Félicitations" {
                let next = self.storyboard?.instantiateViewControllerWithIdentifier("TelechargementVC") as! TelechargementViewController
                topController.presentViewController(next, animated: true, completion: nil)

            }
        })

        topController.presentViewController(alert, animated: true){}

    }

}