gpt4 book ai didi

swift - 如何使用 Swift 检索地址簿联系人?

转载 作者:IT王子 更新时间:2023-10-29 05:22:36 26 4
gpt4 key购买 nike

我不明白为什么我的代码不能用 Swift 编译。

我正在尝试转换这个 Objective-C 代码:

CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

if (addressBook != nil) {
NSLog(@"Succesful.");

NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
}

这是我目前在 Swift 中的演绎:

var error:CFErrorRef
var addressBook = ABAddressBookCreateWithOptions(nil, nil);

if (addressBook != nil) {
println("Succesful.");

var allContacts:CFArrayRef = ABAddressBookCopyArrayOfAllPeople(addressBook);
}

但是,Xcode 报告:

'Unmanaged' is not convertible to 'CFArrayRef'

你们有想法吗?

最佳答案

显然,如果针对 iOS 版本 9 或更高版本,则不应使用 AddressBook框架,而是使用 Contacts框架。

所以,

  1. 导入 Contacts :

    import Contacts
  2. 确保提供 NSContactsUsageDescription在你的Info.plist .

  3. 然后,您就可以访问联系人了。例如。在 Swift 3 中:

    let status = CNContactStore.authorizationStatus(for: .contacts)
    if status == .denied || status == .restricted {
    presentSettingsActionSheet()
    return
    }

    // open it

    let store = CNContactStore()
    store.requestAccess(for: .contacts) { granted, error in
    guard granted else {
    DispatchQueue.main.async {
    self.presentSettingsActionSheet()
    }
    return
    }

    // get the contacts

    var contacts = [CNContact]()
    let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as NSString, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
    do {
    try store.enumerateContacts(with: request) { contact, stop in
    contacts.append(contact)
    }
    } catch {
    print(error)
    }

    // do something with the contacts array (e.g. print the names)

    let formatter = CNContactFormatter()
    formatter.style = .fullName
    for contact in contacts {
    print(formatter.string(from: contact) ?? "???")
    }
    }

    在哪里

    func presentSettingsActionSheet() {
    let alert = UIAlertController(title: "Permission to Contacts", message: "This app needs access to contacts in order to ...", preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Go to Settings", style: .default) { _ in
    let url = URL(string: UIApplication.openSettingsURLString)!
    UIApplication.shared.open(url)
    })
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
    present(alert, animated: true)
    }

我对 AddressBook 框架的原始回答如下。


一些观察:

  • 如果你想使用error ABAddressBookCreateWithOptions 的参数, 定义为 Unmanaged<CFError>? .

  • 如果失败,请查看错误对象(执行 takeRetainedValue 以免泄漏)。

  • 确保takeRetainedValue通讯录也一样,所以你不会泄露。

  • 您可能不应该只获取联系人,但您可能应该先请求许可。

把所有这些放在一起你会得到:

// make sure user hadn't previously denied access

let status = ABAddressBookGetAuthorizationStatus()
if status == .Denied || status == .Restricted {
// user previously denied, so tell them to fix that in settings
return
}

// open it

var error: Unmanaged<CFError>?
guard let addressBook: ABAddressBook? = ABAddressBookCreateWithOptions(nil, &error)?.takeRetainedValue() else {
print(error?.takeRetainedValue())
return
}

// request permission to use it

ABAddressBookRequestAccessWithCompletion(addressBook) { granted, error in
if !granted {
// warn the user that because they just denied permission, this functionality won't work
// also let them know that they have to fix this in settings
return
}

if let people = ABAddressBookCopyArrayOfAllPeople(addressBook)?.takeRetainedValue() as? NSArray {
// now do something with the array of people
}
}

关于swift - 如何使用 Swift 检索地址簿联系人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24852175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com