À la base, on sait que l'usager est authentifié sur son appareil mobile s'il peut accéder aux applications. Cependant, certaines applications qui manipulent des informations sensibles peuvent augmenter la sécurité en demandant une nouvelle authentification lors de leur ouverture.
La fonctionnalité Face ID est disponible pour déverrouiller l'appareil depuis iPhone X et iPad 2018.
Si Face ID n'est pas disponible ou s'il a été désactivé, le code que je vous propose demandera à l'usager d'entrer le mot de passe de son téléphone.
Pour que votre application demande une authentifiation lors de son ouverture, suivez ces étapes :
J'aime lui donner la valeur « $(PRODUCT_NAME) a besoin d'utiliser Face ID pour valider votre identité. » ou encore « Vous devez vous authentifier pour accéder à cette application. ».

Une fois que l'authentification sera codée, la valeur que vous donnez à la clé NSFaceIDUsageDescription apparaîtra sous le message « Souhaitez-vous autoriser " Mon Projet " à utiliser Face ID? » la première fois que l'application sera lancée sur le iPhone.

import Foundation
import LocalAuthentication
enum Statut {
case authentifie, nonAuthentifie
}
@Observable
class Authentification {
var statut: Statut = .nonAuthentifie
var demandeFaite: Bool = false // permet au programme de réagir différemment avant que authentifier() ait été appelée
let context = LAContext()
var error: NSError?
func authentifier() {
// Avec .deviceOwnerAuthentication (plutôt que .deviceOwnerAuthenticationWithBiometrics), demandera une authentification par code si Face ID n'est pas disponible.
if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
let justificationSiFaceIDNonDisponible = "Vous devez vous authentifier pour accéder à cette application."
context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: justificationSiFaceIDNonDisponible ) { success, error in
if success {
// Retourne au fil d'exécution principal
DispatchQueue.main.async {
self.statut = .authentifie
self.demandeFaite = true
}
} else {
print(error?.localizedDescription ?? "L'authentification a échoué.")
DispatchQueue.main.async {
self.demandeFaite = true
}
}
}
}
}
}
struct ContentView: View {
@State private var authentification: Authentification = Authentification()
...
var body: some View {
NavigationStack {
VStack {
if authentification.statut == .nonAuthentifie {
if !authentification.demandeFaite {
ProgressView()
}
else {
// arrivera ici si l'usager clique sur Annuler sur l'écran Face ID ou sur l'écran de saisie de son code
Text("Vous devez être authentifié pour accéder à cette application.")
.padding()
}
}
else {
...
}
}
.onAppear(perform: {
// ne refera pas l'authentification si on passe à une autre vue puis qu'on revient à celle-ci
if authentification.statut == .nonAuthentifie {
authentification.authentifier()
}
})
}
}
}




▼Publicité