在Swift中,我已经使用联系人UI框架显示了手机中的联系人,并选择了特定联系人。选择后,需要在下一个View Controller中显示所选的联系人。
此代码属于contactUI框架的显示联系人。当我们运行此代码时,它会显示电话中的所有联系人,并带有2个按钮,例如完成或取消。当我选择联系人并按完成按钮时,它应该导航到另一个视图Controller Plz为我提供解决方案。

enter code here
//
//  ViewController.swift
//  Spliting
//
//  Created by Vijayasrivudanti on 01/11/17.
//  Copyright © 2017 Vijayasrivudanti. All rights reserved.
//

import UIKit
import ContactsUI

class ViewController: UIViewController ,CNContactPickerDelegate{
    let contactStore = CNContactStore()
    var results:[CNContact] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        // 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.
    }

    @IBAction func contact(_ sender: Any) {
        //let dataArray = NSMutableArray()
        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.results.append(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
            for number in contact.phoneNumbers {

                print("The number of \(contact.givenName) is: \(number.value)")

        }
      }
    }

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



}

最佳答案

ViewController.h

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
    IBOutlet UITableView*listTblView;
}

@property(nonatomic,strong)IBOutlet UITableView*listTblView;
@property(nonatomic,strong)IBOutlet UIButton*selectAll;


-(IBAction)addButtonPressed:(UIButton *)sender;
-(IBAction)selectAndDeselectAll:(id)sender;

ViewController.m
    #import <Contacts/Contacts.h>
    #import "ViewController.h"
    #import "TableViewCell.h"
    #import "secondViewController.h"


    @interface ViewController ()
    {
        NSMutableArray *titleArr;
        NSMutableArray  *selectedBtnArray;

    }

    @end

    @implementation ViewController
    @synthesize listTblView,selectAll;

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        titleArr = [NSMutableArray array];
        [self fetchContactsandAuthorization];
        selectedBtnArray = [[NSMutableArray alloc] init];

    }



    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
    {
        return titleArr.count;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

        static NSString *identifier = @"Cell";
        TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
         }

        cell.title.text = titleArr[indexPath.row];
        cell.selectBitton.tag = indexPath.row ;
         [cell.selectBitton addTarget:self action:@selector(addButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

        for(NSString *name in titleArr)
        {
            if([selectedBtnArray containsObject:name])
            {
               cell.selectBitton.selected = YES;

            }else{
                cell.selectBitton.selected = NO;
            }
        }

    return cell;

    }



    //For fetching contact list from phone call this one

    -(void)fetchContactsandAuthorization
            {
                // Request authorization to Contacts
                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
                        {
                            NSString *phone;
                            NSString *fullName;
                            NSString *firstName;
                            NSString *lastName;
                            UIImage *profileImage;
                            NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
                            for (CNContact *contact in cnContacts) {
                                // copy data to my custom Contacts class.
                                firstName = contact.givenName;
                                lastName = contact.familyName;
                                if (lastName == nil) {
                                    fullName=[NSString stringWithFormat:@"%@",firstName];
                                }else if (firstName == nil){
                                    fullName=[NSString stringWithFormat:@"%@",lastName];
                                }
                                else{
                                    fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
                                }
                                UIImage *image = [UIImage imageWithData:contact.imageData];
                                if (image != nil) {
                                    profileImage = image;
                                }else{
                                    profileImage = [UIImage imageNamed:@"person-icon.png"];
                                }
                                for (CNLabeledValue *label in contact.phoneNumbers) {
                                    phone = [label.value stringValue];
                                    if ([phone length] > 0) {
                                        [contactNumbersArray addObject:phone];
                                    }
                                }
                                NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage,@"userImage",phone,@"PhoneNumbers", nil];
                                [titleArr addObject:[NSString stringWithFormat:@"%@",[personDict objectForKey:@"fullName"]]];
                                NSLog(@"The contactsArray are - %@",titleArr);
                            }
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [listTblView reloadData];
                            });
                        }
                    }
                }];
            }

对于选择特定项目,请调用此方法
-(IBAction)addButtonPressed:(UIButton *)sender
{

    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.listTblView];
    NSIndexPath *indexPath = [self.listTblView indexPathForRowAtPoint:buttonPosition];
    TableViewCell *cell = [self.listTblView cellForRowAtIndexPath:indexPath];

    NSString *tagString  = [NSString stringWithFormat:@"%@",cell.title.text];
    NSLog(@"title is : %@",tagString);


    if(!sender.selected)
    {
        sender.selected = YES;
        [selectedBtnArray addObject:tagString];
    }else{
         sender.selected = NO;
         [selectedBtnArray removeObject:tagString];
    }

    NSLog(@"%@",selectedBtnArray);

    if (selectedBtnArray. count == titleArr.count)
        selectAll.selected = YES;
    else
        selectAll.selected = NO;

}
For select all and de select all call this method



     -(IBAction)selectAndDeselectAll:(id)sender
        {
            if(!selectAll.selected)
            {
             [selectedBtnArray removeAllObjects];
                selectAll.selected = YES;

                for(NSString *name in titleArr)
                [selectedBtnArray addObject:name];

            }else{
                selectAll.selected = NO;
                 [selectedBtnArray removeAllObjects];
            }

             NSLog(@"%@",selectedBtnArray);
            [listTblView reloadData];
        }

将所选的内容保存在用户默认设置中
 [[NSUserDefaults standardUserDefaults]setObject:selectedBtnArray forKey:@"test"];
 [[NSUserDefaults standardUserDefaults]synchronize];

在NextViewController中,在viewDidLoad中检索用户默认值
NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"test"];
     NSLog(@"comtactList :>>>>%@",arr);

关于ios - 如何在iOS 9(Swift)中将选定的联系人显示到下一个View Controller中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47108357/

10-15 08:31