我试图在用户点击本地通知后呈现AlertView.AlertView具有取消或确定选项.
extension ViewController:UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Tapped in notification")
if(defaults.object(forKey: "alertOn") != nil){
// Create the alert controller
let alertController = UIAlertController(title: "Some text", message: "Some text again", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
}
}
func triggerNotification(){
print("notification will be triggered in five seconds..Hold on tight")
let content = UNMutableNotificationContent()
content.title = "SomeText"
content.body = "Some more text"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5.0, repeats: false)
let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self as! UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().add(request){(error) in
if (error != nil){
print(error?.localizedDescription)
}
}
}
Run Code Online (Sandbox Code Playgroud)
它应该显示警报视图,可以选择确定或取消请求.相反,它显示我的消息UIAlertController,其视图不在窗口层次结构中
当我将alertview放在viewdidapear中它工作正常但是当我把它放在userNotificationCenter中时,我的AlertView没有附加到主视图.
代码简介
extension ViewController:UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
Present UIAlertView
}
}
ViewController{
Call to notification when app is in background
triggerNotification()
triggerNotification(){
Definition
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个
func currentTopViewController() -> UIViewController {
var topVC: UIViewController? = UIApplication.shared.delegate?.window?.rootViewController
while topVC?.presentedViewController {
topVC = topVC?.presentedViewController
}
return topVC!
}
Run Code Online (Sandbox Code Playgroud)
并将VC呈现为
let currentTopVC: UIViewController? = self.currentTopViewController()
currentTopVC.present(alertController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2413 次 |
| 最近记录: |