2016-12-23 5 views
0
func getContacts() { 
    let store = CNContactStore() 

    if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined { 
     store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: NSError?) -> Void in 
      if authorized { 
       self.retrieveContactsWithStore(store: store) 
      } 
     } as! (Bool, Error?) -> Void) 
    } else if CNContactStore.authorizationStatus(for: .contacts) == .authorized { 
     self.retrieveContactsWithStore(store: store) 
    } 
} 

func retrieveContactsWithStore(store: CNContactStore) { 
    do { 
     let groups = try store.groups(matching: nil) 
     let predicate = CNContact.predicateForContactsInGroup(withIdentifier: groups[0].identifier) 
     //let predicate = CNContact.predicateForContactsMatchingName("John") 
     let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey] as [Any] 

     let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch as! [CNKeyDescriptor]) 
     self.objects = contacts 
     DispatchQueue.main.async(execute: {() -> Void in 
      self.myTableView.reloadData() 
     }) 
    } catch { 
     print(error) 
    } 
} 

주소록에서 주소록을 검색하려고했지만 getContacts()를 호출하는보기로 갈 때마다 응용 프로그램이 정지합니다. 더 이상 진행하지 않지만 충돌을 일으키지 않았습니다. 나는 여기서 무엇이 잘못되었는지 궁금합니다.주소록에 대한 액세스를 요청할 때 응용 프로그램이 작동하지 않습니다.

답변

1

requestAccess에 대한 전화 코드가 올바르지 않습니다. 완료 핸들러의 구문이 유효하지 않습니다. 다음이 필요합니다.

func getContacts() { 
    let store = CNContactStore() 

    let status = CNContactStore.authorizationStatus(for: .contacts) 
    if status == .notDetermined { 
     store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: Error?) in 
      if authorized { 
       self.retrieveContactsWithStore(store: store) 
      } 
     }) 
    } else if status == .authorized { 
     self.retrieveContactsWithStore(store: store) 
    } 
} 

변수가 status 인 변경에 유의하십시오. 이것은보다 깨끗하고 읽기 쉽도록 authorizationStatus을 계속해서 호출하는 것보다 쉽습니다. 한 번 호출 한 다음 필요에 따라 값을 반복해서 확인하십시오.

+0

이 코드는 else status == .authorized 부분에 오류가 있습니다. "fix it insert", "" –

+0

죄송합니다. 나는 편집했다. 거기에'if'를 추가하십시오. 업데이트를 참조하십시오. – rmaddy

+0

그리고 다른 하나의 오타가 닫는 괄호를 놓쳤습니다. – rmaddy