我正在用 Objective C 中当前的 CNContact 框架替换我过时的 ABAdressBook 代码。我可以整理出大部分代码,除了 Home City 部分,所以让我们专注于此。目前我有这个代码:
-(NSArray *)getLandAddressesForContactIOS6:(ABRecordRef)recordRef {
ABMultiValueRef addresses = ABRecordCopyValue(recordRef, kABPersonAddressProperty);
NSMutableArray *formattedAddressesResponse = [NSMutableArray array];
for(CFIndex i = 0; i < ABMultiValueGetCount(addresses); i++) {
NSString *label = (__bridge NSString *)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(addresses, i));
NSDictionary *addressComponents = (__bridge NSDictionary*)ABMultiValueCopyValueAtIndex(addresses, i);
NSString *street = [addressComponents objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [addressComponents objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *formattedAddress = ABCreateStringWithAddressDictionary(addressComponents, YES);
NSMutableDictionary *currentAddressResponse = [NSMutableDictionary dictionaryWithObjectsAndKeys:
label, @"type",
label, @"label",
nil];
if (street != nil) {
[currentAddressResponse setObject:street forKey:@"street"];
}
if (city != nil) {
[currentAddressResponse setObject:city forKey:@"city"];
}
if (formattedAddress != nil) {
[currentAddressResponse setObject:formattedAddress forKey:@"formattedAddress"];
}
[formattedAddressesResponse addObject:currentAddressResponse];
}
return formattedAddressesResponse;
}
该代码在 iOS 9+ 中已被弃用,因此使用新的联系人框架最接近家乡城市的是:
-(NSArray *)getLandAddressesForContactIOS10:(CNContact*)recordRef {
NSArray <CNLabeledValue<CNPostalAddress *> *> *addresses = recordRef.postalAddresses;
NSMutableArray *formattedAdressResponse = [NSMutableArray array];
for(CFIndex i = 0; i < addresses.count; i++) {
CNLabeledValue *addressi = [addresses objectAtIndex:i];
//NSString *city = addressi.??????; //Stuck here, don't know what else to do
如何从 CNContact 中提取城市名称?