ios - 如何在IOS 9(Swift)中将选定的联系人显示到下一个 View Controller 中

标签 ios

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

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")
    }



}

最佳答案

View Controller .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;

View Controller .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/

相关文章:

ios - 设置导航栏图标的大小 ios

ios - 动画 UISwitch 'onTintColor' 属性

objective-c - 有人可以帮我改进我的代码,让它运行得更快吗?

ios - 如何在单击按钮时刷新 TableView

html - Swift 的 Web View 仅将 <head></head><body></body> 打印为 innerhtml

ios - 如何在应用启动时获取用户当前位置

ios - 对象从字典数组到数组

ios - 无法从 Twitter 登录获取电子邮件

iphone - UILocalNotification - 每天在特定时间触发并重复

ios - UIProgressView 在自定义 UITableViewCell 中自行更新