2016-12-23 71 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

此代碼在其他狀態== .authorized部分上有錯誤,它表示「修復了它插入」,「」 –

+0

糟糕。我經過編輯。在那裏添加一個「if」。查看更新。 – rmaddy

+0

還有一個錯字 - 錯過了右括號。 – rmaddy

相關問題