2016-02-27 51 views
0

由於某些原因,我一直在重複使用我可以通過我的代碼訪問的許多聯繫人。任何理由?重複訪問地址簿

var error: Unmanaged<CFError>? 
addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue() 


    if let people = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(self.addressBook, nil, ABPersonSortOrdering(kABPersonSortByFirstName)).takeRetainedValue() as? NSArray { 
     for record in people { 
      //var contactPerson: ABRecordRef = record 
      var contactName: String = ABRecordCopyCompositeName(record).takeRetainedValue() as String 


      var number = "" 

      var phones: ABMultiValueRef = ABRecordCopyValue(record, kABPersonPhoneProperty).takeRetainedValue() 

      for j in 0..<ABMultiValueGetCount(phones) { 
       number = ABMultiValueCopyValueAtIndex(phones, j).takeRetainedValue() as! String 
       break 
      } 

      if (number != "") { 
       var newPerson = personInfo(name: contactName, number: number) 
       allContacts.append(newPerson) 
      } 


      self.tableView.reloadData() 
     } 
    } 

回答

0

James Richards請使用聯繫人框架而不是使用地址簿。

首先你768,16添加聯繫人框架,通過建立Phases->鏈接二進制與Libraries->添加(點擊+) - >選擇聯繫人框架

import Contacts 

然後

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

// open it 

let store = CNContactStore() 
store.requestAccessForEntityType(.Contacts) { granted, error in 
     guard granted else { 
      dispatch_async(dispatch_get_main_queue()) { 
       // user didn't grant authorization, so tell them to fix that in settings 
       print(error) 
      } 
      return 
} 

// get the contacts 

var contacts = [CNContact]() 
let request = CNContactFetchRequest(keysToFetch:[CNContactIdentifierKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]) 
    do { 
     try store.enumerateContactsWithFetchRequest(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.stringFromContact(contact)) 
     } 
} 

輸出結果

Optional("John Appleseed") 
Optional("Kate Bell") 
Optional("Anna Haro") 
Optional("Daniel Higgins Jr.") 
Optional("David Taylor") 
Optional("Hank M. Zakroff") 

Link 1

Apple Document

Contacts

+0

不幸的是我需要與iOS 8兼容的應用程序,以及 –