Swift使用Contacts Framework,使用电话号码搜索以获取名称和用户图像

Mat*_*son 10 ios swift cncontact contacts-framework

我有一个返回格式为电话号码的API:+ 1415xxxxxxx(E164)

现在这些数字被放入UITableView的Cell中并按预期显示,但是我希望能够搜索手机上的用户联系人以查看是否存在匹配 - 如果是这样也会传回名字,姓氏和已知照片.

看看Apple页面(https://developer.apple.com/library/watchos/documentation/Contacts/Reference/Contacts_Framework/index.html)我需要

 import ContactsUI
Run Code Online (Sandbox Code Playgroud)

但是我不确定,我是否将contactDB加载到字典中然后进行搜索?我可以通过名称找到很多东西,而不是通过数字搜索:

  let predicate = CNContact.predicateForContactsMatchingName("Sam") 
Run Code Online (Sandbox Code Playgroud)

我试图找到一个我可以调用的函数,使用PhoneNumber进行搜索并返回FirstName,FamilyName和Image.

  func searchForContactUsingNumber(PhoneNumber: String)
 {

 // Search Via phoneNumber
  let store = CNContactStore()
  let contacts = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingPhoneNumber(PhoneNumber), keysToFetch:[CNContactGivenNameKey, CNContactFamilyNameKey,CNContactImageData])

  return FirstName, GivenName,UIImage

 }
Run Code Online (Sandbox Code Playgroud)

我觉得我正在倒退但不确定前进的方向..任何想法?

Rob*_*Cat 11

为了让这个例子快速启动并运行,我使用了以下信息来源:

从字符串中过滤非数字

/sf/answers/2289023761/

http://www.appcoda.com/ios-contacts-framework/

下面的代码块包括授权检查,因为我必须让它工作才能在模拟器中进行测试.代码只是单视图应用程序视图控制器,您可以将UIButton故事板中的a连接到findContactInfoForPhoneNumber:方法以获取是否运行.输出到控制台 - 您需要print用其他东西替换这些语句.

如果您对完整视图控制器代码不感兴趣,那么只需查看该searchForContactUsingPhoneNumber(phoneNumber: String)方法即可.我在文档中遵循Apple的建议,以CNContact异步方式运行框架.

代码条所有+,-(符号可能是一个电话号码,只是这样的电话号码,你传递给匹配必须完全相同匹配的数字.

//
//  ViewController.swift
//  ContactsTest
//
//  Created by Robotic Cat on 13/04/2016.
//

import UIKit
import Contacts

class ViewController: UIViewController {

    // MARK: - App Logic
    func showMessage(message: String) {
        // Create an Alert
        let alertController = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.Alert)

        // Add an OK button to dismiss
        let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (action) -> Void in
        }
        alertController.addAction(dismissAction)

        // Show the Alert
        self.presentViewController(alertController, animated: true, completion: nil)
    }

    func requestForAccess(completionHandler: (accessGranted: Bool) -> Void) {
        // Get authorization
        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)

        // Find out what access level we have currently
        switch authorizationStatus {
        case .Authorized:
            completionHandler(accessGranted: true)

        case .Denied, .NotDetermined:
            CNContactStore().requestAccessForEntityType(CNEntityType.Contacts, completionHandler: { (access, accessError) -> Void in
                if access {
                    completionHandler(accessGranted: access)
                }
                else {
                    if authorizationStatus == CNAuthorizationStatus.Denied {
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
                            self.showMessage(message)
                        })
                    }
                }
            })

        default:
            completionHandler(accessGranted: false)
        }
    }

    @IBAction func findContactInfoForPhoneNumber(sender: UIButton) {

        self.searchForContactUsingPhoneNumber("(888)555-1212)")
    }

    func searchForContactUsingPhoneNumber(phoneNumber: String) {

        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), { () -> Void in
            self.requestForAccess { (accessGranted) -> Void in
                if accessGranted {
                    let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactImageDataKey, CNContactPhoneNumbersKey]
                    var contacts = [CNContact]()
                    var message: String!

                    let contactsStore = CNContactStore()
                    do {
                        try contactsStore.enumerateContactsWithFetchRequest(CNContactFetchRequest(keysToFetch: keys)) {
                            (contact, cursor) -> Void in
                            if (!contact.phoneNumbers.isEmpty) {
                                let phoneNumberToCompareAgainst = phoneNumber.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
                                for phoneNumber in contact.phoneNumbers {
                                    if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
                                        let phoneNumberString = phoneNumberStruct.stringValue
                                        let phoneNumberToCompare = phoneNumberString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
                                        if phoneNumberToCompare == phoneNumberToCompareAgainst {
                                            contacts.append(contact)
                                        }
                                    }
                                }
                            }
                        }

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

                    if message != nil {
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            self.showMessage(message)
                        })
                    }
                    else {
                        // Success
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            // Do someting with the contacts in the main queue, for example
                            /*
                             self.delegate.didFetchContacts(contacts) <= which extracts the required info and puts it in a tableview
                             */
                            print(contacts) // Will print all contact info for each contact (multiple line is, for example, there are multiple phone numbers or email addresses)
                            let contact = contacts[0] // For just the first contact (if two contacts had the same phone number)
                            print(contact.givenName) // Print the "first" name
                            print(contact.familyName) // Print the "last" name
                            if contact.isKeyAvailable(CNContactImageDataKey) {
                                if let contactImageData = contact.imageData {
                                    print(UIImage(data: contactImageData)) // Print the image set on the contact
                                }
                            } else {
                                // No Image available

                            }
                        })
                    }
                }
            }
        })
    }

}
Run Code Online (Sandbox Code Playgroud)