ios 单击按钮时如何打开手机设置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28152526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:31:06  来源:igfitidea点击:

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

iosswiftsettings

提问by Solomon Ayoola

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.

我正在使用 Swift 和 Xcode。

回答by Marius Fanu

Using UIApplication.openSettingsURLString

使用 UIApplication.openSettingsURLString

Update for Swift 5.1

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

斯威夫特 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)
}

回答by vivek takrani

?? Be careful!

This answer is based on undocumented APIs and recently (since iOS12) Apple is rejecting apps with this approach.

?? 当心!

此答案基于未记录的 API,最近(自 iOS12 起)Apple 拒绝使用这种方法的应用程序。

Original answer below

原答案如下

Swift 5

斯威夫特 5

UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)

Swift 4

斯威夫特 4

UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)

NOTE: The following method works for all the versions below iOS 11, for higher versions the app might get rejected since it's a private API

注意:以下方法适用于 iOS 11 以下的所有版本,对于更高版本的应用程序可能会被拒绝,因为它是私有 API

Sometimes we want to take a user to settings other than our app settings. The following method will help you achieve that:

有时我们想让用户进入我们的应用程序设置以外的设置。以下方法将帮助您实现这一目标:

First, configure the URL Schemes in your project. You will find it in Target -> Info -> URL Scheme. click on + button and type prefs in URL Schemes

首先,在您的项目中配置 URL Schemes。您可以在 Target -> Info -> URL Scheme 中找到它。单击 + 按钮并在 URL Schemes 中键入 prefs

enter image description here

在此处输入图片说明

Swift 5

斯威夫特 5

UIApplication.shared.open(URL(string: "App-prefs:Bluetooth")!)

Swift 3

斯威夫特 3

UIApplication.shared.open(URL(string:"App-Prefs:root=General")!, options: [:], completionHandler: nil)

Swift

迅速

UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=General")!)

Objective-C

目标-C

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];

and following are all the available URLs

以下是所有可用的 URL

**On IOS < 12 **

**在 IOS < 12 上 **

  • prefs:root=General&path=About
  • prefs:root=General&path=ACCESSIBILITY
  • prefs:root=AIRPLANE_MODE
  • prefs:root=General&path=AUTOLOCK
  • prefs:root=General&path=USAGE/CELLULAR_USAGE
  • prefs:root=Brightness
  • prefs:root=Bluetooth
  • prefs:root=General&path=DATE_AND_TIME
  • prefs:root=FACETIME
  • prefs:root=General
  • prefs:root=General&path=Keyboard
  • prefs:root=CASTLE
  • prefs:root=CASTLE&path=STORAGE_AND_BACKUP
  • prefs:root=General&path=INTERNATIONAL
  • prefs:root=LOCATION_SERVICES
  • prefs:root=ACCOUNT_SETTINGS
  • prefs:root=MUSIC
  • prefs:root=MUSIC&path=EQ
  • prefs:root=MUSIC&path=VolumeLimit
  • prefs:root=General&path=Network
  • prefs:root=NIKE_PLUS_IPOD
  • prefs:root=NOTES
  • prefs:root=NOTIFICATIONS_ID
  • prefs:root=Phone
  • prefs:root=Photos
  • prefs:root=General&path=ManagedConfigurationList
  • prefs:root=General&path=Reset
  • prefs:root=Sounds&path=Ringtone
  • prefs:root=Safari
  • prefs:root=General&path=Assistant
  • prefs:root=Sounds
  • prefs:root=General&path=SOFTWARE_UPDATE_LINK
  • prefs:root=STORE
  • prefs:root=TWITTER
  • prefs:root=FACEBOOK
  • prefs:root=General&path=USAGE prefs:root=VIDEO
  • prefs:root=General&path=Network/VPN
  • prefs:root=Wallpaper
  • prefs:root=WIFI
  • prefs:root=INTERNET_TETHERING
  • prefs:root=Phone&path=Blocked
  • prefs:root=DO_NOT_DISTURB
  • prefs:root=General&path=关于
  • prefs:root=General&path=ACCESSIBILITY
  • 首选项:root=AIRPLANE_MODE
  • prefs:root=General&path=AUTOLOCK
  • prefs:root=General&path=USAGE/CELLULAR_USAGE
  • 首选项:根=亮度
  • 首选项:root=蓝牙
  • 首选项:root=General&path=DATE_AND_TIME
  • 首选项:root=FACETIME
  • 首选项:root=一般
  • prefs:root=General&path=Keyboard
  • 首选项:root = CASTLE
  • 首选项:root=CASTLE&path=STORAGE_AND_BACKUP
  • prefs:root=General&path=INTERNATIONAL
  • 首选项:root=LOCATION_SERVICES
  • 首选项:root = ACCOUNT_SETTINGS
  • 首选项:root=音乐
  • 首选项:root=音乐&路径=EQ
  • prefs:root=MUSIC&path=VolumeLimit
  • prefs:root=General&path=Network
  • 首选项:root=NIKE_PLUS_IPOD
  • 首选项:root=注意
  • 首选项:root=NOTIFICATIONS_ID
  • 首选项:root=电话
  • 首选项:root=照片
  • prefs:root=General&path=ManagedConfigurationList
  • prefs:root=General&path=Reset
  • prefs:root=声音&路径=铃声
  • 首选项:root = Safari
  • prefs:root=General&path=Assistant
  • prefs:root=声音
  • prefs:root=General&path=SOFTWARE_UPDATE_LINK
  • 首选项:root = STORE
  • 首选项:root=推特
  • 首选项:root = FACEBOOK
  • prefs:root=General&path=USAGE prefs:root=VIDEO
  • prefs:root=General&path=网络/VPN
  • 首选项:root=壁纸
  • 首选项:root=WIFI
  • 首选项:root=INTERNET_TETHERING
  • prefs:root=Phone&path=Blocked
  • 首选项:root=DO_NOT_DISTURB

On IOS 13

在 IOS 13 上

  • App-prefs:General&path=About
  • App-prefs:AIRPLANE_MODE
  • App-prefs:General&path=AUTOLOCK
  • App-prefs:Bluetooth
  • App-prefs:General&path=DATE_AND_TIME
  • App-prefs:FACETIME
  • App-prefs:General
  • App-prefs:General&path=Keyboard
  • App-prefs:CASTLE
  • App-prefs:CASTLE&path=STORAGE_AND_BACKUP
  • App-prefs:General&path=INTERNATIONAL
  • App-prefs:MUSIC
  • App-prefs:NOTES
  • App-prefs:NOTIFICATIONS_ID
  • App-prefs:Phone
  • App-prefs:Photos
  • App-prefs:General&path=ManagedConfigurationList
  • App-prefs:General&path=Reset
  • App-prefs:Sounds&path=Ringtone
  • App-prefs:Sounds
  • App-prefs:General&path=SOFTWARE_UPDATE_LINK
  • App-prefs:STORE
  • App-prefs:Wallpaper
  • App-prefs:WIFI
  • App-prefs:INTERNET_TETHERING
  • App-prefs:DO_NOT_DISTURB

    Not tested

  • App-prefs:TWITTER (??)

  • App-prefs:FACEBOOK (??)
  • App-prefs:NIKE_PLUS_IPOD (??)
  • App-prefs:General&path=About
  • 应用偏好:AIRPLANE_MODE
  • App-prefs:General&path=AUTOLOCK
  • 应用偏好:蓝牙
  • App-prefs:General&path=DATE_AND_TIME
  • 应用偏好:FACETIME
  • 应用偏好:通用
  • App-prefs:General&path=Keyboard
  • 应用偏好:城堡
  • 应用首选项:CASTLE&path=STORAGE_AND_BACKUP
  • App-prefs:General&path=INTERNATIONAL
  • 应用偏好:音乐
  • 应用偏好:注意事项
  • 应用首选项:NOTIFICATIONS_ID
  • 应用偏好:电话
  • 应用偏好:照片
  • App-prefs:General&path=ManagedConfigurationList
  • App-prefs:General&path=Reset
  • App-prefs:Sounds&path=Ringtone
  • 应用偏好:声音
  • App-prefs:General&path=SOFTWARE_UPDATE_LINK
  • 应用偏好:商店
  • 应用偏好:壁纸
  • 应用偏好:WIFI
  • 应用偏好:INTERNET_TETHERING
  • 应用偏好:DO_NOT_DISTURB

    未测试

  • 应用偏好:TWITTER (??)

  • 应用偏好:FACEBOOK (??)
  • 应用偏好:NIKE_PLUS_IPOD (??)

Note:Network setting will not be opened in a simulator, but the link will work on a real device.

注意:网络设置不会在模拟器中打开,但链接将在真实设备上工作。

回答by Christian

In iOS 8+ you can do the following:

在 iOS 8+ 中,您可以执行以下操作:

 func buttonClicked(sender:UIButton)
    {
        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString))
    }

Swift 4

斯威夫特 4

    let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)!
    UIApplication.shared.open(settingsUrl)

回答by Luca Davanzo

Using @vivek's hint I develop an utils class based on Swift 3, hope you appreciate!

使用@vivek 的提示,我开发了一个基于Swift 3的 utils 类,希望您能欣赏!

import Foundation
import UIKit

public enum PreferenceType: String {

    case about = "General&path=About"
    case accessibility = "General&path=ACCESSIBILITY"
    case airplaneMode = "AIRPLANE_MODE"
    case autolock = "General&path=AUTOLOCK"
    case cellularUsage = "General&path=USAGE/CELLULAR_USAGE"
    case brightness = "Brightness"
    case bluetooth = "Bluetooth"
    case dateAndTime = "General&path=DATE_AND_TIME"
    case facetime = "FACETIME"
    case general = "General"
    case keyboard = "General&path=Keyboard"
    case castle = "CASTLE"
    case storageAndBackup = "CASTLE&path=STORAGE_AND_BACKUP"
    case international = "General&path=INTERNATIONAL"
    case locationServices = "LOCATION_SERVICES"
    case accountSettings = "ACCOUNT_SETTINGS"
    case music = "MUSIC"
    case equalizer = "MUSIC&path=EQ"
    case volumeLimit = "MUSIC&path=VolumeLimit"
    case network = "General&path=Network"
    case nikePlusIPod = "NIKE_PLUS_IPOD"
    case notes = "NOTES"
    case notificationsId = "NOTIFICATIONS_ID"
    case phone = "Phone"
    case photos = "Photos"
    case managedConfigurationList = "General&path=ManagedConfigurationList"
    case reset = "General&path=Reset"
    case ringtone = "Sounds&path=Ringtone"
    case safari = "Safari"
    case assistant = "General&path=Assistant"
    case sounds = "Sounds"
    case softwareUpdateLink = "General&path=SOFTWARE_UPDATE_LINK"
    case store = "STORE"
    case twitter = "TWITTER"
    case facebook = "FACEBOOK"
    case usage = "General&path=USAGE"
    case video = "VIDEO"
    case vpn = "General&path=Network/VPN"
    case wallpaper = "Wallpaper"
    case wifi = "WIFI"
    case tethering = "INTERNET_TETHERING"
    case blocked = "Phone&path=Blocked"
    case doNotDisturb = "DO_NOT_DISTURB"

}


enum PreferenceExplorerError: Error {
    case notFound(String)
}

open class PreferencesExplorer {

    // MARK: - Class properties -

    static private let preferencePath = "App-Prefs:root"

    // MARK: - Class methods -

    static func open(_ preferenceType: PreferenceType) throws {
        let appPath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
        if let url = URL(string: appPath) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
               UIApplication.shared.openURL(url)
            }
        } else {
            throw PreferenceExplorerError.notFound(appPath)
        }
    }

}

This is very helpful since that API's will change for sure and you can refactor once and very fast!

这非常有用,因为 API 肯定会改变,而且您可以非常快速地重构一次!

回答by inc_london

The first response from App-Specific URL Schemesworked for me on iOS 10.3.

App-Specific URL Schemes的第一个响应在 iOS 10.3 上对我有用。

if let appSettings = URL(string: UIApplicationOpenSettingsURLString + Bundle.main.bundleIdentifier!) {
    if UIApplication.shared.canOpenURL(appSettings) {
      UIApplication.shared.open(appSettings)
    }
  }

回答by Joe Susnick

App-Prefs:root=Privacy&path=LOCATIONworked for me for getting to general location settings. Note: only works on a device.

App-Prefs:root=Privacy&path=LOCATION为我工作以进入一般位置设置。注意:仅适用于设备。

回答by ofer

word of warning: the prefs:rootor App-Prefs:rootURL schemes are considered private API. Apple may reject you app if you use those, here is what you may get when submitting your app:

警告:prefs:rootApp-Prefs:rootURL 方案被视为私有 API。如果您使用这些应用程序,Apple 可能会拒绝您,以下是您提交应用程序时可能会得到的信息:

Your app uses the "prefs:root=" non-public URL scheme, which is a private entity. The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change. Continuing to use or conceal non-public APIs in future submissions of this app may result in the termination of your Apple Developer account, as well as removal of all associated apps from the App Store.

Next Steps

To resolve this issue, please revise your app to provide the associated functionality using public APIs or remove the functionality using the "prefs:root" or "App-Prefs:root" URL scheme.

If there are no alternatives for providing the functionality your app requires, you can file an enhancement request.

您的应用程序使用“prefs:root=”非公共 URL 方案,这是一个私有实体。App Store 不允许使用非公共 API,因为如果这些 API 发生变化,可能会导致糟糕的用户体验。在以后提交此应用程序时继续使用或隐藏非公开 API 可能会导致您的 Apple Developer 帐户被终止,以及从 App Store 中删除所有相关应用程序。

下一步

要解决此问题,请修改您的应用以使用公共 API 提供相关功能,或使用“prefs:root”或“App-Prefs:root”URL 方案移除该功能。

如果没有其他方法可以提供您的应用程序所需的功能,您可以提交增强请求。

回答by ingconti

in ios10/ Xcode 8 in simulator:

在模拟器中的 ios10/Xcode 8 中:

UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!)

works

作品

UIApplication.shared.openURL(URL(string:"prefs:root=General")!)

does not.

才不是。

回答by niravdesai21

I have seen this line of code

我见过这行代码

UIApplication.sharedApplication() .openURL(NSURL(string:"prefs:root=General")!)

is not working, it didn't work for me in ios10/ Xcode 8, just a small code difference, please replace this with

不起作用,它在 ios10/Xcode 8 中对我不起作用,只是一个小的代码差异,请将其替换为

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=General")!)

Swift3

斯威夫特3

UIApplication.shared.openURL(URL(string:"prefs:root=General")!)

Replace with

用。。。来代替

UIApplication.shared.openURL(URL(string:"App-Prefs:root=General")!)

Hope it helps. Cheers.

希望能帮助到你。干杯。

回答by bsod

Swift 4.2, iOS 12

斯威夫特 4.2,iOS 12

The open(url:options:completionHandler:)method has been updated to include a non-nil options dictionary, which as of this post only contains one possible option of type UIApplication.OpenExternalURLOptionsKey(in the example).

open(url:options:completionHandler:)方法已更新为包含一个非 nil 选项字典,截至本文,该字典仅包含一个可能的类型选项UIApplication.OpenExternalURLOptionsKey(在示例中)。

@objc func openAppSpecificSettings() {

    guard let url = URL(string: UIApplication.openSettingsURLString),
        UIApplication.shared.canOpenURL(url) else {
            return
    }

    let optionsKeyDictionary = [UIApplication.OpenExternalURLOptionsKey(rawValue: "universalLinksOnly"): NSNumber(value: true)]

    UIApplication.shared.open(url, options: optionsKeyDictionary, completionHandler: nil)

}

Explicitly constructing a URL, such as with "App-Prefs", has, AFAIK, gotten some apps rejected from the store.

显式构建 URL,例如使用“App-Prefs”,AFAIK 已导致一些应用程序被商店拒绝。