2017-02-22 78 views
1

尝试获取提供联系人标识符的联系人匹配不成功。我希望返回联系人,然后使用与其关联的图像。我得到一场零比赛。谢谢。这段代码我从一个演示了,我有点新的编程Swift使用联系人框架,使用标识符进行搜索以匹配

import Contacts 

var contact = CNContact() 
var contactStore = CNContactStore() 

let foundContact = getContactFromID("94AAD3B1-E9E1-48C9-A796-F7EC1014230A") 

func getContactFromID(contactID: String) -> CNContact { 

    AppDelegate.getAppDelegate().requestForAccess { (accessGranted) -> Void in 
     if accessGranted { 

      let predicate = CNContact.predicateForContactsWithIdentifiers([contactID]) 

      let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactImageDataAvailableKey] 

      var contacts = [CNContact]() 
      var message: String! 

      let contactsStore = AppDelegate.getAppDelegate().contactStore 

      do { 
       contacts = try contactsStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: keys) 

       if contacts.count == 0 { 
        message = "No contacts were found matching the given name." 
       } 
      } 
      catch { 
       message = "Unable to fetch contacts." 
      } 


      if message != nil { 
       dispatch_async(dispatch_get_main_queue(), {() -> Void in 
        Utility.showAlert(nil, message: message) 
       }) 
      } else { 

       dispatch_async(dispatch_get_main_queue(), {() -> Void in 

        self.contact = contacts[0] 

        print("self.contact: \(self.contact)") 

       }) 
      } 
     } 
    } 

    return self.contact 
} 
+0

我解决了它:),我删除了dispatch_async的东西,现在的作品:这里是固定的代码。 – Mike

回答

2

我解决了吧:),我删除了dispatch_async的东西,现在的工作:这里是固定的代码。

func getContactFromID(contactID: String) -> CNContact { 

     AppDelegate.getAppDelegate().requestForAccess { (accessGranted) -> Void in 
      if accessGranted { 

       let predicate = CNContact.predicateForContactsWithIdentifiers([contactID]) 

       let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactImageDataAvailableKey] 

       var contacts = [CNContact]() 
       var message: String! 

       let contactsStore = AppDelegate.getAppDelegate().contactStore 

       do { 
        contacts = try contactsStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: keys) 

        if contacts.count == 0 { 
         message = "No contacts were found matching the given name." 
        } 
       } 
       catch { 
        message = "Unable to fetch contacts." 
       } 

       self.contact = contacts[0] 
      } 
     } 
     return self.contact 
    } 
+0

从firat字符serch联系起始..那种类型代码提供plz .. –