Search code examples
iosswiftsettings

How do I open phone settings when a button is clicked?


I am trying to implement a feature in an App that shows an alert when the internet connection is not available. The alert has two actions (OK and Settings), whenever a user clicks on settings, I want to take them to the phone settings programmatically.

I am using Swift and Xcode.


Solution

  • Using UIApplication.openSettingsURLString

    Update for Swift 5.1

     override func viewDidAppear(_ animated: Bool) {
        let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
    
        let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
    
            guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                return
            }
    
            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                    print("Settings opened: \(success)") // Prints true
                })
            }
        }
        alertController.addAction(settingsAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alertController.addAction(cancelAction)
    
        present(alertController, animated: true, completion: nil)
    }
    

    Swift 4.2

    override func viewDidAppear(_ animated: Bool) {
        let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
    
        let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
    
            guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
                return
            }
    
            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                    print("Settings opened: \(success)") // Prints true
                })
            }
        }
        alertController.addAction(settingsAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alertController.addAction(cancelAction)
    
        present(alertController, animated: true, completion: nil)
    }