Comment puis-je ouvrir les paramètres de téléphone quand un bouton est cliqué?
j'essaie d'implémenter une fonctionnalité dans une application qui affiche une alerte lorsque la connexion internet n'est pas disponible. L'alerte a deux actions (OK et paramètres), chaque fois qu'un utilisateur clique sur les paramètres, Je veux les emmener aux paramètres du téléphone de façon programmée.
J'utilise Swift et Xcode.
14 réponses
utilisant UIApplicationOpenSettingsURLString
mise à jour de Swift 3
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)
}
Swift 2.x
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)
}
Swift 4
UIApplication.shared.open(URL.init(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
NOTE: la méthode suivante fonctionne pour toutes les versions inférieures à iOS 11, pour les versions supérieures l'application pourrait être rejetée car il s'agit d'une API privée
parfois, nous voulons amener un utilisateur à des paramètres autres que ceux de notre application. La méthode suivante vous aidera à y parvenir:
tout d'abord, configurez les schémas D'URL de votre projet. Vous trouverez il dans le schéma cible -> Info - > URL. cliquez sur + Bouton et tapez des préfs dans les schémas D'URL
Swift 3
UIApplication.shared.open(URL(string:"App-Prefs:root=General")!, options: [:], completionHandler: nil)
Swift
UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=General")!)
objectif-c
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];
et suivants sont toutes les URLs disponibles
- 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=Luminosité
- prefs: root=Bluetooth
- prefs: root=General&path=DATE_AND_TIME
- prefs: root=FACETIME
- prefs:root=Général
- prefs: root=General&path =Keyboard
- préfs: root=CASTLE
- prefs: root=CASTLE&path=STORAGE_AND_BACKUP
- prefs: root=General&path =INTERNATIONAL
- prefs: root=LOCATION_SERVICES
- prefs: root=ACCOUNT_SETTINGS
- préfs: root=MUSIC
- prefs: root=MUSIC&path =EQ
- préfs: root=MUSIC&path=VolumeLimit
- prefs: root=General&path =Network
- prefs: root=NIKE_PLUS_IPOD
- prefs: root=NOTES
- prefs: root=NOTIFICATIONS_ID
- préfs: root = Phone
- préfs: root=Photos
- prefs: root=General&path=ManagedConfigurationList
- prefs: root=General&path =Reset
- préfs: root=Sounds&path =Ringtone
- prefs: root=Safari
- prefs: root=General&path =Assistant
- préfs: root=Sounds
- prefs: root=General&path=SOFTWARE_UPDATE_LINK
- prefs: root=STORE
- préfs: root=TWITTER
- préfs: root=FACEBOOK
- prefs: root=General&path=USAGE prefs :root=VIDEO
- prefs: root=General&path = Network /VPN
- préfs: root=Wallpaper
- préfs: root=WIFI
- prefs: root=INTERNET_TETHERING
- préfs: root=Phone&path =Blocked
- prefs: root=DO_NOT_DISTURB
Note: le réglage du réseau va ne pas être ouvert dans un simulateur, mais le lien fonctionnera sur un véritable appareil.
dans iOS 8+ Vous pouvez faire ce qui suit:
func buttonClicked(sender:UIButton)
{
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString))
}
Swift 4
let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)!
UIApplication.shared.open(settingsUrl)
en utilisant l'indice de @vivek je développe une classe utils basée sur Swift 3 , j'espère que vous appréciez!
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)
}
}
}
c'est très utile car cette API va changer à coup sûr et vous pouvez changer une fois et très vite!
la première réponse de applications-Specific URL Schemes a fonctionné pour moi sur iOS 10.3.
if let appSettings = URL(string: UIApplicationOpenSettingsURLString + Bundle.main.bundleIdentifier!) {
if UIApplication.shared.canOpenURL(appSettings) {
UIApplication.shared.open(appSettings)
}
}
App-Prefs:root=Privacy&path=LOCATION
m'a permis de me rendre à des emplacements généraux. Remarque: ne fonctionne que sur un appareil.
dans ios10/ Xcode 8 en simulateur:
UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!)
œuvres
UIApplication.shared.openURL(URL(string:"prefs:root=General")!)
ne fonctionne pas.
j'ai vu cette ligne de code
UIApplication.sharedApplication() .openURL(NSURL(string:"prefs:root=General")!)
ne fonctionne pas, il ne fonctionne pas pour moi dans ios10 / Xcode 8, juste une petite différence de code, s'il vous plaît remplacer par
UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=General")!)
Swift3
UIApplication.shared.openURL(URL(string:"prefs:root=General")!)
remplacer par
UIApplication.shared.openURL(URL(string:"App-Prefs:root=General")!)
J'espère que ça aidera. Acclamation.
ajoute à @Luca Davanzo
iOS 11, certains paramètres de permissions ont été déplacés vers le chemin de l'application:
iOS 11 Support
static func open(_ preferenceType: PreferenceType) throws {
var preferencePath: String
if #available(iOS 11.0, *), preferenceType == .video || preferenceType == .locationServices || preferenceType == .photos {
preferencePath = UIApplicationOpenSettingsURLString
} else {
preferencePath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
}
if let url = URL(string: preferencePath) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
throw PreferenceExplorerError.notFound(preferencePath)
}
}
mot d'avertissement: les schémas D'URL prefs:root
ou App-Prefs:root
sont considérés comme des API privées. Apple peut rejeter votre application si vous utilisez ceux-ci, voici ce que vous pouvez obtenir en soumettant votre application:
votre application utilise le schéma D'URL" prefs:root= " non-public, qui est une entité privée. L'utilisation d'API non publiques n'est pas autorisée sur L'App Store car elle peut entraîner une mauvaise expérience utilisateur si ces API changent. Continuer à utiliser ou à dissimuler les API non publiques dans les soumissions futures de cette application peuvent entraîner la résiliation de votre compte de développeur Apple, ainsi que le retrait de toutes les applications associées de L'App Store.
Prochaines Étapes
pour résoudre ce problème, veuillez réviser votre application pour fournir la fonctionnalité associée en utilisant les API publiques ou supprimer la fonctionnalité en utilisant le schéma D'URL" prefs:root "ou" App-Prefs:root".
S'il n'y a pas d'alternative pour en fournissant les fonctionnalités dont votre application a besoin, vous pouvez déposer une demande d'amélioration.
Swift 4.2, iOS 12
la méthode open(url:options:completionHandler:)
a été mise à jour pour inclure un dictionnaire d'options non-nil, qui à partir de ce post ne contient qu'une option possible de type UIApplication.OpenExternalURLOptionsKey
(dans l'exemple).
@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)
}
construire explicitement une URL, comme avec" App-Prefs", a, AFAIK, obtenu quelques applications rejetées par le magasin.
dans iOS 10 et Swift 3, Utilisez le code ci-dessous:
UIApplication.shared.open(URL.init(string: "App-Prefs:root=General")!, options: [:]) { (success) in
}
SWIFT 4
cela pourrait prendre les paramètres spécifiques de votre application, si c'est ce que vous recherchez.
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
comme ci-dessus @niravdesai dit App-prefs.
J'ai trouvé que App-Prefs:
fonctionne à la fois pour iOS 9, 10 et 11. appareils testés.
où as prefs:
ne fonctionne que sur iOS 9.