【问题标题】:How to display selected contacts into next View Controller in IOS 9(Swift)如何在IOS 9(Swift)中将选定的联系人显示到下一个视图控制器中
【发布时间】:2017-11-04 07:04:55
【问题描述】:

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

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



}

【问题讨论】:

  • 如果有人知道答案,请帮助我
  • @Lahari Areti:选定的联系人保存在数组中并将该数组传递给下一个视图控制器。
  • 如何将选中的联系人放入iOS中的数组
  • 你能举个例子吗?
  • 请检查以下示例并告诉我

标签: ios


【解决方案1】:

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);

【讨论】:

  • 是swift还是objective-c?
  • 这是在objective-c中
  • 请你用 Swift 提供给我。
  • 好的。给我一些时间我会给你,或者你可以使用这个链接objectivec2swift.com将目标c代码转换为swift。它将 objc 转换为 swift 并且可能会有所帮助。
  • 确定你可以发帖,但是你的问题解释清楚
【解决方案2】:

试试这个:

在你的接收视图控制器中,初始化另一个结果数组:

var receivingResults:[CNContact] = []

在第一个viewController中:在prepareForSegue方法中将results数组发送到接收viewController的receiveingResults数组中:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "REPLACEWITHSEGUEIDENTIFIER" {
            if let destination = segue.destination as? REPLACEWITHNAMEOFDESTINATIONVIEWCONTROLLER {
                destination.receivingResults = self.results

            }
        }
}

如果您在@IBAction func contact(_ sender: Any) 中获取结果,您可以将 CNContacts 数组保存到结果中...

self.results = contact

for cont in contact {
    self.results.append(cont)
}

然后按照你想要的方式处理接收结果数组...

【讨论】:

  • 我在 self.results 中遇到了错误。比如无法将类型“[CNContact]”的值分配给类型“CNContact”。
  • 我看到@LahariAreti 你的self.results.append(contact) 应该是self.results = contact
  • 它不会转到另一个视图控制器。我收到类似“结果视图控制器无法访问,因为它没有入口点和运行时标识符”之类的错误。我们如何从默认的联系人视图控制器 ui 连接到结果视图控制器。每当用户在默认的 ContactView 控制器中选择联系人并按下完成按钮时,它会转到带有选定联系人的结果视图控制器。我们如何在 done 和 Result View Controller 之间建立链接?
  • 你好@Louis Leung
  • 嗨@LahariAreti 你知道如何在故事板中连接segues吗? (参见developer.apple.com/library/content/featuredarticles/…)您需要在完成按钮和ResultViewController 之间建立连接,然后设置segue 标识符并在prepareForSegue() 中使用该字符串,我在其中放置了REPLACEWITHSEGUEIDENTIFIER。一个“show”转场就足够了。
猜你喜欢
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多