如何使用swift将选定的联系人存储到IOS 9中的数组中

时间:2017-11-14 09:55:15

标签: ios arrays

我获取了联系人详细信息,我想将它们存储到一个数组中。我已经尝试了但它将单个联系人存储为一个数组。但我想将它们全部存储到一个数组中。如何存储它们。请指导我。 首先它显示我们手机上的所有联系人,我选择了特定联系人。所选联系人应存储在一个数组中 谢谢

import UIKit
import ContactsUI

class ViewController: UIViewController ,CNContactPickerDelegate {
    let contactStore = CNContactStore()
    let amount = 200
    //var selectedContact:CNContact = CNContact()
    //var results:[CNContact] = []
    var res:CNContact = CNContact()
    var a = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
         perform(#selector(contactPicker(_:didSelect:)), with: nil, afterDelay: 0)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)

    }


    @IBAction func contact(_ sender: Any) {
        let cnPicker = CNContactPickerViewController()
        cnPicker.delegate = self
        self.present(cnPicker, animated: true, completion: nil)
        do {
            try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])) {
                (contact, cursor) -> Void in
                self.res = contact
                ///let data = Data(name: contact.givenName)
                //self.dataArray?.addObject(data)
            }
        }
        catch
        {
            print("Handle the error please")
        }
    }
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            //let storyboard = UIStoryboard(name:"Main",bundle:nil)
            a = [contact.givenName]
            print("name of contacts in array \(a)")
            let n = a.flatMap({$0}).count
            print(n)
            let res = amount/n
            print(res)
            for c in a {
                print ("split money \(c):\(res)")
            }
            //print(a.count)
            let displayViewController = self.storyboard?.instantiateViewController(withIdentifier: "DisplayViewControllerr")as! DisplayViewControllerr
              displayViewController.b = a
            let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.window?.rootViewController = displayViewController
            self.navigationController?.pushViewController(displayViewController, animated: true)
            //self.present(displayViewController,animated:false,completion: nil)






            }
    }


    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        print("Cancel Contact Picker")
    }



}

2 个答案:

答案 0 :(得分:0)

#import <Contacts/Contacts.h>

 CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted == YES) {
                //keys with fetching properties
                NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
                NSString *containerId = store.defaultContainerIdentifier;
                NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
                NSError *error;
                NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
                if (error) {
                    NSLog(@"error fetching contacts %@", error);
                } else {


                    NSLog(@"Contact Array %@",cnContacts.description);
                }
            }
        }];

答案 1 :(得分:0)

我得到了答案并成功将联系人存储到数组中。只修改程序中的一行。即

func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            a+= [contact.givenName]//I changed at this place 
}
print(a)

它将所有选定的联系人显示在数组中。