需要创建像ABPeoplePickerNavigationController这样的自定义视图

时间:2015-04-17 11:14:20

标签: ios xcode contacts whatsapp abpeoplepickerview

我想创建一个自定义视图,就像iPhone中的联系人一样。有没有可用于制作自定义视图的教程,就像ABPeoplePickerNavigationController一样?

请注意,我不想打开AddressBookUI框架提供的默认人员选取器控制器。另外,我确实希望将此导航控制器绑定到我的主视图中。

为了参考我想要的东西,你可以在iOS设备上推荐Whatsapp的联系人标签。

编辑:我已经有了一个联系人列表,并在表格视图中显示了人员的姓名。现在,我想从A-Z创建一个字母索引,并在点击该索引时,表视图应该滚动到那些联系人。另外,如何通过他/她的姓或名来实现搜索功能以查找用户?

2 个答案:

答案 0 :(得分:3)

我在目前正在构建的应用程序中完全相同,我们也从Whatsapp这样的应用程序中获得了灵感。

我使用了一个简单的桌面视图,其中包含用于视觉效果的自定义单元格,只需使用名称&图片。

我的流程如下:

  • 在coredata中创建contact对象(或另一种保持数据的持久方式)
  • 通过ABAddressbook框架,您可以浏览所有联系人,并在新的联系人对象中对其进行转换。在ABPerson对象中保留Contact的引用,这样您以后只需使用引用即可查找和更新您的联系人。如果您不这样做,则每次要更新联系人时都必须浏览所有ABPersons。 你可以直接使用ABPersons,但代码真的很痛苦。

  • 一旦您提取了所有联系人,请确保在使用核心数据时保存上下文,或将其存储在.sqlite中。

  • 然后,您可以在联系人数组中简单地提取它们,并在您选择的自定义单元格中显示它们。

This appcoda tutorial是一个适合tableview教程的自定义单元格。你可以通过谷歌搜索找到一千多个" tableview定制单元ios"并找到你可能喜欢的不同的东西。最后,您只需要一个带有标签和图片的单元格,您可以使用我用于"联系人"的另一个桌面视图的简单UITableViewCell。类型。

使该联系人列表保持最新(获取正确的数字,图片,名称等)并确保它们在更新之前存在,检查联系人是否已被删除,添加等等。所有必须按顺序完成为了让你的清单准确,这是一个非常漫长/烦人的过程。

我可以分享我的Contact类,但它包含了许多不相关的代码,可能会让您感到困惑,因为: - 我还要检查这些联系人是否已经是我的应用的用户,以便在我的桌面视图的特定部分中移动它们 - 我将我的tableview分成27个部分(用户,然后是字母)。

另外,我会用最后一条通用编程建议来阻止它:首先写下你需要的东西和你需要的东西,获得所有的可能性是个好主意。我碰到了许多简单的问题,我花了一段时间才解决,要么是因为我没有正确计划,要么是因为它被隐藏了。

例如:

  • 您的某些联系人根本没有名字。
  • 您的某些联系人在"标题"字段(你在哪里写医生或先生)
  • 您的某些联系人没有电话号码(如果您使用电话号码作为标识符)
  • 您的某些联系人具有国际格式,而某些联系人则没有(+32 46556555或0032 46556555)
  • 您的某些联系人使用相机拍摄照片,其他一些来自Gmail,其格式不同
  • 由于来自用户的同步效果不佳,您可能会有重复的联系人(同名,相同的所有内容)
  • 您需要确保firstname / lastname在右侧部分,区分大小写的编码可能会导致问题
  • 您需要为以笑脸或非字母数字字符开头的联系人找到解决方案
  • 您的用户需要侧面的索引列表
  • 当然,您需要添加搜索栏,因为有些人的联系方式超过1000个。
  • 还有更多,我保证。

因为这是非常特定于应用程序的,所以我不会重复我所遇到的每一个问题以及我为此所做的事情,但是你明白了:)尽管我可以随意提出任何非常具体的问题。已经有一个非常具体的解决方案,因为我几乎不得不从头开始复制whatsapp的联系人,而且,我做到了。 (我实际上和Anonymess和iOS完全相同)

编辑:以下是我的ABPerson提取方法的一些方法; ContactDAO主要与我的持久模型(CoreData)进行交互,我相信他们的名字足够清晰,可以让您了解发生了什么。我对评论和变量名感到满意,所以你应该毫不费力地阅读它。

这里有一大堆代码。

- (NSMutableArray *)getAllRecordsWithPeople:(CFArrayRef)allPeople andAddressBook:(ABAddressBookRef)addressbook{
    NSMutableArray *newRecords = [[NSMutableArray alloc]init];
    CFIndex nPeople = ABAddressBookGetPersonCount(addressbook);

    for (int i=0;i < nPeople;i++){

        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
        ABRecordID refId = ABRecordGetRecordID(ref);
        NSNumber *recId = [NSNumber numberWithInt:refId];
        [newRecords addObject:recId];
    }

    return newRecords;
}

- (void)getValidContactsFromAddressBookWithCompletionBlock:(void (^)(NSError *error))completion{

    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, nil);

    __block BOOL accessGranted = NO;

    if (&ABAddressBookRequestAccessWithCompletion != NULL) {
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(semaphore);
        });

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    }

    if (accessGranted) {

        NSMutableArray *newRecords       = [[NSMutableArray alloc]init];
        NSMutableArray *updatedRecords   = [[NSMutableArray alloc]init];
        NSMutableArray *unchangedRecords = [[NSMutableArray alloc]init];

        CFArrayRef allPeople  = ABAddressBookCopyArrayOfAllPeople(addressBook);
        CFIndex nPeople       = ABAddressBookGetPersonCount(addressBook);

        //Checking the last time we updated
        NSTimeInterval lastSyncTime;
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"LastSyncTime"] == nil){
            //This is the first time we update.
            lastSyncTime = 0;
        }else{
            //Setting the last update in variable
            lastSyncTime = [[[NSUserDefaults standardUserDefaults]objectForKey:@"LastSyncTime"]doubleValue];
        }

        if (lastSyncTime == 0){
            //We have to insert everyone, this is the first time we do this.
            newRecords = [self getAllRecordsWithPeople:allPeople andAddressBook:addressBook];
        }else{
            //We have to manually compare everyone to see if something has changed.

            for (int i=0;i < nPeople;i++) {

                ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
                ABRecordID refId = ABRecordGetRecordID(ref);
                NSNumber *recId = @(refId);

                CFDateRef recordCreation = ABRecordCopyValue(ref, kABPersonCreationDateProperty);
                NSDate *recCreDate = (__bridge NSDate *)(recordCreation);
                NSTimeInterval creDateInterval = [recCreDate timeIntervalSince1970];

                if(creDateInterval > lastSyncTime){
                    //This object was created after my lastSync, this must be a new record
                    [newRecords addObject:recId];

                }else{

                    //Checking the last update of the given record
                    CFDateRef recordUpdate = ABRecordCopyValue(ref, kABPersonModificationDateProperty);
                    NSDate *recUpDate = (__bridge NSDate*)(recordUpdate);

                    if ([recUpDate timeIntervalSince1970] > lastSyncTime){
                        //The record was somehow updated since last time, we'll update it
                        [updatedRecords addObject:recId];

                    }else{
                        //The record wasn't updated nor created, it is therefore unchanged.
                        //We still need to keep it in a separate array to compare deleted contacts
                        [unchangedRecords addObject:recId];
                    }
                }

            }
            if(allPeople)
                CFRelease(allPeople);
        }

        [self manageNewContacts:newRecords updatedContacts:updatedRecords andUnchangedContacts:unchangedRecords inAddressBook:addressBook andBlock:^(NSError *error) {
            completion(error);
        }];
    }else{
        NSError *error = [NSError errorWithDomain:@"ABAccess access forbidden" code:403 userInfo:nil];
        completion(error);
    }
}

- (void)manageNewContacts:(NSMutableArray*)newRecords updatedContacts:(NSMutableArray*)updatedRecords andUnchangedContacts:(NSMutableArray*)unchangedRecords inAddressBook:(ABAddressBookRef)addressbook andBlock:(void (^)(NSError *error))completion{

    AppDelegate *app = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = app.managedObjectContext;

    //Getting all the CoreData contacts IDs to have something to compare
    NSArray *coreDataContactsIds = [ContactDAO getAllContactIdsInManagedObjectContext:context];

    for (NSDictionary *rec in coreDataContactsIds){
        NSNumber *recId = rec[@"record_id"];
        if (![unchangedRecords containsObject:recId]){
            //The unchanged record doesn't exist locally

            if (![updatedRecords containsObject:recId]){
                //The updated record doesn't exist locally

                if (![newRecords containsObject:recId]){
                    //The new record doesn't exist locally
                    //That means the ongoing record has been deleted from the addressbook,
                    //we also have to delete it locally

                    [ContactDAO deleteContactWithID:recId inManagedObjectContext:context];

                }

            }
        }

    }

    for (NSNumber *recId in updatedRecords){
        ABRecordID recordID = (ABRecordID)recId.intValue;
        ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressbook, recordID);

        NSDictionary *personDict = [self getPersonDictionaryFromABRecordRef:person];
        if (personDict){
            [ContactDAO updateContactWithFirstName:personDict[@"firstName"] lastName:personDict[@"lastName"] compositeName:personDict[@"compositeName"] picture:personDict[@"picture"] phoneNumbers:personDict[@"phoneNumbers"] recordID:recId inManagedObjectContext:context];
        }
    }

    for (NSNumber *recId in newRecords){
        ABRecordID recordID = (ABRecordID)recId.intValue;
        ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressbook, recordID);

        NSDictionary *personDict = [self getPersonDictionaryFromABRecordRef:person];
        if (personDict){
            [ContactDAO createContactWithFirstName:personDict[@"firstName"] lastName:personDict[@"lastName"] compositeName:personDict[@"compositeName"] picture:personDict[@"picture"] phoneNumbers:personDict[@"phoneNumbers"] recordID:recId inManagedObjectContext:context];
        }

    }

    NSError *dbError;
    [context save:&dbError];

    NSTimeInterval lastSyncTime = [[NSDate date]timeIntervalSince1970];

    [[NSUserDefaults standardUserDefaults]setObject:@(lastSyncTime) forKey:@"LastSyncTime"];
    completion(dbError);
}


- (NSDictionary*)getPersonDictionaryFromABRecordRef:(ABRecordRef)person{

    //Get name
    NSString * firstName, *lastName;
    firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    lastName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));

    firstName =  (firstName == nil) ? @"" : firstName;
    lastName  =  (lastName == nil)  ? @"" : lastName;
    NSString *compositeName;

    if ([firstName isEqualToString:@""] && [lastName isEqualToString:@""]){
        return nil;
    }

    if ([lastName isEqualToString:@""]){
        compositeName = [NSString stringWithFormat:@"%@", firstName];
    }
    if ([firstName isEqualToString:@""]){
        compositeName = [NSString stringWithFormat:@"%@", lastName];
    }
    if (![lastName isEqualToString:@""] && ![firstName isEqualToString:@""]){
        compositeName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
    }

    //Get picture
    CFDataRef imageData = ABPersonCopyImageData(person);
    NSData *data = CFBridgingRelease(imageData);

    //Get phone numbers
    NSMutableSet *phoneNumbers = [[NSMutableSet alloc]init];

    ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {

        CFStringRef str = ABMultiValueCopyValueAtIndex(phones, i);
        NSString *num = CFBridgingRelease(str);
        [phoneNumbers addObject:num];
        /*if(str)
         CFRelease(str);*/
    }

    //Save it in dictionary
    NSDictionary *personDict = [[NSDictionary alloc]initWithObjectsAndKeys:firstName, @"firstName",lastName , @"lastName",phoneNumbers,@"phoneNumbers", compositeName, @"compositeName", data, @"picture", nil];

     //Release everything.
     if(phones)
     CFRelease(phones);

    return personDict;

}

说到索引,this tutorial应该没问题。

答案 1 :(得分:0)

看看这个:http://www.appcoda.com/ios-programming-index-list-uitableview/

表格视图的方法有助于提供您想要的结果:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title