代码之家  ›  专栏  ›  技术社区  ›  hfossli

在iPhone Objective-C的通讯录中添加联系人

  •  4
  • hfossli  · 技术社区  · 15 年前

    在通讯簿中设置街道地址等并让用户将其保存在iPhone上的正确方法是什么?

    编辑:删除了特定的代码问题,使其更通用

    2 回复  |  直到 13 年前
        1
  •  17
  •   hfossli    13 年前

    这是一个完整的工作示例,演示了如何通过创建AbrecordRef并使用ViewController将其推送到视图中来显示人员。

    ///////////////////////////// 连接到自定义操作。

    -(IBAction)addToAddressbook:(id)sender{  
        ABUnknownPersonViewController *unknownPersonViewController = [[ABUnknownPersonViewController alloc] init];
        unknownPersonViewController.displayedPerson = (ABRecordRef)[self buildContactDetails];
        unknownPersonViewController.allowsAddingToAddressBook = YES;
        [self.navigationController pushViewController:unknownPersonViewController animated:YES];
        [unknownPersonViewController release]; 
    }
    

    //////////////////////////// 这是建造AbrecordRef的人

    - (ABRecordRef)buildContactDetails {
        NSLog(@"building contact details");
        ABRecordRef person = ABPersonCreate(); 
        CFErrorRef  error = NULL;  
    
        // firstname
        ABRecordSetValue(person, kABPersonFirstNameProperty, @"Don Juan", NULL);
    
        // email
        ABMutableMultiValueRef email = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(email, @"expert.in@computer.com", CFSTR("email"), NULL);
        ABRecordSetValue(person, kABPersonEmailProperty, email, &error);
        CFRelease(email); 
    
        // Start of Address
        ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);  
        NSMutableDictionary *addressDict = [[NSMutableDictionary alloc] init];
        [addressDict setObject:@"The awesome road numba 1" forKey:(NSString *)kABPersonAddressStreetKey];   
        [addressDict setObject:@"0568" forKey:(NSString *)kABPersonAddressZIPKey];  
        [addressDict setObject:@"Oslo" forKey:(NSString *)kABPersonAddressCityKey]; 
        ABMultiValueAddValueAndLabel(address, addressDict, kABWorkLabel, NULL);
        ABRecordSetValue(person, kABPersonAddressProperty, address, &error); 
        [addressDict release];
        CFRelease(address); 
        // End of Address
    
        if (error != NULL) 
            NSLog(@"Error: %@", error);
    
        [(id)person autorelease];
        return person;
    }
    

    //////////////////////////// 连接收割台:

    请记住导入这些框架:

    #import <AddressBook/AddressBook.h>
    #import <AddressBookUI/AddressBookUI.h> 
    

    设置委托

    ABNewPersonViewControllerDelegate
    

    并将其添加到界面

    ABNewPersonViewController *newPersonController;
    
        2
  •  0
  •   Josh Bleecher Snyder    15 年前

    我想,从眼睛里看出来,而不是

    ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    

    你想要

    ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABDictionaryPropertyType);