您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 讀取手機通訊錄並按漢字首字母分組排序

編輯:iOS 開發綜合

一、讀取本地通訊錄

使用 AddressBook 框架讀取時,iOS 6 之後必須先向使用者申請權限,且要判斷授權結果,否則會拿到空資料。

/** 載入本地聯絡人 */
- (void)loadLocalContacts {
    ABAddressBookRef addressBooks = nil;
    if (DeviceVersion < 6.0) {
        addressBooks = ABAddressBookCreate();
    } else {
        addressBooks = ABAddressBookCreateWithOptions(NULL, NULL);
        // 同步等待授權結果
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBooks, ^(bool granted, CFErrorRef error) {
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }

    // 未授權直接返回
    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) {
        return;
    }

    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);
    NSMutableArray *persons = [[NSMutableArray alloc] init];

    for (int i = 0; i < nPeople; i++) {
        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
        NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
        NSMutableString *name = [[NSMutableString alloc] init];
        if (firstName == nil && lastName == nil) {
            name = nil; // 沒有名字的聯絡人
        }
        if (lastName) [name appendString:lastName];
        if (firstName) [name appendString:firstName];

        ABMultiValueRef tmlphone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        NSString *telphone = (NSString *)ABMultiValueCopyValueAtIndex(tmlphone, 0);
        if (telphone != nil) {
            telphone = [telphone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSString *title = [NSString stringWithFormat:@"%@(%@)", name, telphone];
            [persons addObject:title];
        }
    }

    // 分組排序
    UILocalizedIndexedCollation *theCollation = [UILocalizedIndexedCollation currentCollation];
    NSInteger highSection = [[theCollation sectionTitles] count]; // 中文環境為 27:A~Z 加符號
    _indexArray = [[NSMutableArray alloc] initWithArray:[theCollation sectionTitles]];

    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:highSection];
    for (NSInteger index = 0; index < highSection; index++) {
        [newSectionsArray addObject:[NSMutableArray array]];
    }

    for (NSString *p in persons) {
        // 例如「林丹」首字母 L,在 A~Z 中排位 11,就放進第 11 個陣列
        NSInteger sectionNumber = [theCollation sectionForObject:p collationStringSelector:@selector(getFirstLetter)];
        [[newSectionsArray objectAtIndex:sectionNumber] addObject:p];
    }

    // 移除空分組,索引陣列要同步移除
    for (int i = 0; i < newSectionsArray.count; i++) {
        if ([newSectionsArray[i] count] == 0) {
            [newSectionsArray removeObjectAtIndex:i];
            [_indexArray removeObjectAtIndex:i];
            i--;
        }
    }

    self.contacts = newSectionsArray;
    [self.tableView reloadData];
}

二、Table View 的資料源與索引列

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.contacts.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.contacts[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"contactCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.imageView.image = [UIImage imageNamed:@"default_head"];
    cell.textLabel.text = self.contacts[indexPath.section][indexPath.row];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [_indexArray objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return _indexArray;
}

// 點擊右側索引列
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

三、兩個關鍵輔助方法

第一個是 sectionForObject:collationStringSelector: 會呼叫的挑字方法。這裡的 p 是 NSString,若你的模型是自訂的 Person 物件,就在那個類別中實作同名方法回傳首字母即可。

- (NSString *)getFirstLetter {
    NSString *ret = @"";
    if (![self canBeConvertedToEncoding:NSASCIIStringEncoding]) {
        // 中文:取轉拼音後的第一個字母
        NSArray *temA = makePinYin2([self characterAtIndex:0]);
        if ([temA count] > 0) {
            ret = [temA objectAtIndex:0];
        }
    } else {
        ret = [NSString stringWithFormat:@"%c", [self characterAtIndex:0]];
    }
    return ret;
}

第二個是 NSString 的分類方法,負責把整串文字中的中文轉成拼音字母:

- (NSString *)letters {
    NSMutableString *letterString = [NSMutableString string];
    NSInteger len = [self length];
    for (NSInteger i = 0; i < len; i++) {
        NSString *oneChar = [[self substringFromIndex:i] substringToIndex:1];
        if (![oneChar canBeConvertedToEncoding:NSASCIIStringEncoding]) {
            NSArray *temA = makePinYin2([oneChar characterAtIndex:0]);
            if ([temA count] > 0) {
                oneChar = [temA objectAtIndex:0];
            }
        }
        [letterString appendString:oneChar];
    }
    return letterString;
}

幾點實務提醒

第一,ABAddressBookRef 與 CFArrayRef 都是 Core Foundation 物件,用完記得 CFRelease;ABRecordCopyValue 回傳的字串同樣需要釋放,否則讀一次通訊錄就洩漏一批記憶體。

第二,這裡用 dispatch_semaphore 同步等待授權結果,若呼叫位置在主線程,可能短暫卡住 UI。更穩妥的寫法是用非同步回調,在回呼中再繼續處理資料。

第三,AddressBook 系列 API 在 iOS 9 之後已被標記為廢棄,新專案應改用 Contacts 框架(CNContactStore),它執行緒安全性更好,也不必手動管理這麼多 CF 物件。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved