Simple App Delegate method to show an UIAlertController (in Swift)

后端 未结 5 2064
暖寄归人
暖寄归人 2020-12-13 18:00

In obj-C when another iOS app (mail attachment, web link) was tapped with a file or link associated with my app. I would then catch this on openURL or didFinishLaunchi

相关标签:
5条回答
  • 2020-12-13 18:14

    Try using

    self.window?.rootViewController?.presentViewController(importAlert, animated: true, completion: nil)
    

    All you need is a viewController object to present the AlertController from.

    In Swift 4:

    self.window?.rootViewController?.present(importAlert, animated: true, completion: nil)
    
    0 讨论(0)
  • 2020-12-13 18:14

    The best way I've found is the following:

            let importantAlert: UIAlertController = UIAlertController(title: "Action Sheet", message: "Hello I was presented from appdelegate ;)", preferredStyle: .ActionSheet) //.Alert .ActionSheet
            var hostVC = UIApplication.sharedApplication().keyWindow?.rootViewController
            while let next = hostVC?.presentedViewController {
                hostVC = next
            }
            hostVC?.presentViewController(importantAlert, animated: true, completion: nil)
    
    
            let delay = 1.5 * Double(NSEC_PER_SEC)
            let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
            dispatch_after(time, dispatch_get_main_queue()) {
    
                importantAlert.dismissViewControllerAnimated(true, completion: nil)
    
                return
            }
    

    I've added a timer so the UIAlertController is dismissed since it doesn't have any buttons in it.

    Thanks to: https://stackoverflow.com/a/33128884/6144027 Brilliant answer on how to present a UIAlertController from AppDelegate.

    0 讨论(0)
  • 2020-12-13 18:17

    Use this code to launch alertCV from appdelegate

        dispatch_async(dispatch_get_main_queue(), {
              let importantAlert: UIAlertController = UIAlertController(title: "Action Sheet", message: "Hello I was presented from appdelegate ;)", preferredStyle: .ActionSheet)
            self.window?.rootViewController?.presentViewController(importantAlert, animated: true, completion: nil)
        })
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-13 18:18

    From inside the app delegate.

    window.rootViweController.presentViewController...

    0 讨论(0)
  • 2020-12-13 18:26

    The accepted answer in Swift 3 in case it helps anyone:

    self.window?.rootViewController?.present(importAlert, animated: true, completion: nil)
    
    0 讨论(0)
提交回复
热议问题