将操作添加到UIAlert,使用户进行设置

时间:2015-07-29 07:23:47

标签: ios swift uialertaction

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

Class Base
{
    static List<string> a;
    static List<string> b;   
    public Base()
    {
        if(this.a == null)
        {
             a = database.GetListitemsForA();
        }

        if(this.b == null)
        {
             b = database.GetListitemsForB();
        }

    }
}

3 个答案:

答案 0 :(得分:2)

使用此代码。可能会帮助它。

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关键字)。

答案 1 :(得分: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!)
    })))
}

答案 2 :(得分: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)