Hi All.
I'm new to SwiftUI, l'll write an app that need access contacts.
How can I ask permission in swiftui ?
someone can help me ?
thanks
Hi All.
I'm new to SwiftUI, l'll write an app that need access contacts.
How can I ask permission in swiftui ?
someone can help me ?
thanks
Generally speaking, permissions are requested when you attempt to use the API. In the case of Contacts, you explicitly request them by importing the Contacts framework, creating an instance of
CNContactStore
, and calling requestAccess(for:completionHandler:)
, passing an entity type of .contacts
(the only type available at present). Doing so will automatically present a dialog asking the user to approve access. You can check whether you need to request access by calling CNContactStore.authorizationStatus(for:)
directly; that way, if the user selects temporary authorization (for one hour, for example), you can determine if you need to re-request authorization as soon as you launch, or (better) as soon as you enter an area of your app that wants to access the user's contacts.Here's a more tangible example:
import Contacts
let authStatus = CNContactStore.authorizationStatus(for: .contacts)
switch authStatus {
case restricted:
print("User cannot grant permission, e.g. parental controls in force.")
exit(1)
case denied:
print("User has explicitly denied permission.")
print("They have to grant it via Preferences app if they change their mind.")
exit(1)
case notDetermined:
print("You need to request authorization via the API now.")
case authorized:
print("You are already authorized.")
}
let store = CNContactStore()
if authStatus == notDetermined {
store.requestAccess(for: .contacts) { success, error in
if !success {
print("Not authorized to access contacts. Error = \(String(describing: error))")
exit(1)
}
print("Authorized!")
}
}
// Access contacts API here.