2

我有一个 UIAlert 通知用户他们没有互联网连接并且他们需要一个才能使用该应用程序。除了让他们通过点击 ok 操作来解除警报之外,我还希望有一个操作,当点击时将用户带到设置应用程序。

func displayAlert(title: String, message: String){

    var formEmpty = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

    formEmpty.addAction((UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in

    })))
4

3 回答 3

3

使用此代码。可能会有所帮助。

override func viewDidAppear(animated: Bool) {
    var alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .Alert)

    var settingsAction = UIAlertAction(title: "Settings", style: .Default) { (_) -> Void in
        let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
        if let url = settingsUrl {
            UIApplication.sharedApplication().openURL(url)
        }
    }

    var cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
    alertController.addAction(settingsAction)
    alertController.addAction(cancelAction)

    presentViewController(alertController, animated: true, completion: nil);
}

请注意UIApplicationOpenSettingsURLString仅在 iOS8.0 和之后可用,因此如果您的应用程序应该支持 iOS7,您必须检查常量的可​​用性(或者如果使用 Swift 2.0,请使用#availability关键字)。

于 2015-07-29T07:28:55.993 回答
0

您可以使用以下代码导航到设置:

let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(settingsUrl!)

在您的函数中添加此代码后,您的函数将如下所示:

func displayAlert(title: String, message: String){

    var formEmpty = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

    formEmpty.addAction((UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in
        //This will call when you press ok in your alertview
        let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
        UIApplication.sharedApplication().openURL(settingsUrl!)
    })))
}
于 2015-07-29T07:35:53.167 回答
0

对于 iOS 10、Swift 3:

    let alert = UIAlertController(title: "Alert!", message: "your message here", preferredStyle: .alert)
    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
    let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
    UIApplication.shared.open(settingsUrl as! URL, options: [:], completionHandler: nil)
    alert.addAction(settingsAction)
    present(alert, animated: true, completion: nil)
于 2017-06-13T09:52:01.937 回答