我有一个请求访问联系人的简单代码
override func viewDidLoad() {
super.viewDidLoad()
fetchContacts()
}
func fetchContacts()
{
let allowedCharset = CharacterSet
.decimalDigits
let store = CNContactStore()
store.requestAccess(for: .contacts) { (granted, err) in
if let error = err
{
print("failed to access",error)
return
}
if (granted)
{
///// after we get access to fetch contacts //// we reload table view data ///
print("access granted")
let keys = [CNContactGivenNameKey,CNContactPhoneNumbersKey,CNContactFamilyNameKey,CNContactMiddleNameKey]
let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
do {
try store.enumerateContacts(with: request, usingBlock: { (contact, stopPointerIfYouWantToStopEnumerating) in
let array = contact.phoneNumbers
for number in array
{
let fullName = contact.givenName + contact.middleName
let lastName = contact.familyName
let value = number.value.stringValue
let number = String(value.unicodeScalars.filter(allowedCharset.contains))
print (number)
/////////// 4 cases we just need the phone not to be zero ///////
if (fullName != "SPAM")
{
self.firstName.append(fullName)
self.lastName.append(lastName)
self.numberArray.append(number)
}
}
})
//self.table()
}
catch let err2 {
print ("failer to enurmerate",err2)
}
}
}
}
此代码在模拟器上运行良好。当我在模拟器上删除应用程序并清理然后再次构建并运行应用程序时,它工作正常,弹出视图会出现权限请求,但是在真实设备上,当我从手机中删除应用程序并清理时,权限会在第一次弹出构建并运行我没有再次收到弹出权限请求