2016-09-19 63 views
3

因此,我剛更新到Xcode 8並將Swift 2.3代碼轉換爲Swift 3,並且在Swift 2.3中沒有這行代碼中的錯誤:ABAddressBook從Swift 3中的不透明(_ :)

func populateFrom(_ addressBook:ABAddressBook) 
{ 
    let allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() 
    let nPeople = ABAddressBookGetPersonCount(addressBook) 
    for index in 0..<nPeople 
    { 
     let person:ABRecord = Unmanaged<ABRecord>.fromOpaque(OpaquePointer(CFArrayGetValueAtIndex(allPeople, index))).takeUnretainedValue() 
    } 
} 

現在的問題是一致let person:ABRecord = Unmanaged<ABRecord>.fromOpaque(OpaquePointer(CFArrayGetValueAtIndex(allPeople, index))).takeUnretainedValue()

的Xcode告訴我,'fromOpaque' is unavailable: use 'fromOpaque(_:UnsafeRawPointer)' instead。但是我找不到Xcode告訴我使用的功能,我只能找到fromOpaque(value: UnsafeRawPointer)這是我目前使用的功能。

我該如何做這項工作?

+1

無關,但如果在Swift 3中編程,您可能只想使用Contacts框架,這比舊的ABAddressBook更容易... – Rob

回答

3

可以簡化這個有點,消除所有的不透明指針引用,例如:

func populate(from addressBook: ABAddressBook) { 
    let allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as [ABRecord] 
    for person in allPeople { 
     let name = ABRecordCopyCompositeName(person).takeRetainedValue() 
     print(name) 
    } 
} 

或者,考慮到地址簿框架中的iOS 9棄用,你可以使用聯繫人框架:

let store = CNContactStore() 
store.requestAccess(for: .contacts) { granted, error in 
    guard granted else { 
     print(error) 
     return 
    } 

    self.populate(from: store) 
} 

而且

func populate(from store: CNContactStore) { 
    let formatter = CNContactFormatter() 
    formatter.style = .fullName 

    let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: formatter.style)]) 
    do { 
     try store.enumerateContacts(with: request) { contact, stop in 
      print(formatter.string(from: contact)) 
     } 
    } catch { 
     print(error) 
    } 
} 
+0

第一個答案是這樣做的,謝謝! –