我是目标C的新手,我正处于需要紧急创建应用程序的位置。我正在使用XCode 4.2
在应用程序的一部分中,我将检测QR码并获得NSString格式的VCard: 我使用以下代码完成了该功能: -I将以下内容导入框架:
AddressBookUI.framework
AddressBook.framework
在我写的.h文件中:
#import <addressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
@interface HellowWorld : UIViewController<ABPeoplePickerNavigationControllerDelegate>{
}
-(IBAction)saveContacts;
@end
我写的.m文件中的:
-(IBAction)saveContacts{
NSString *vCardString = test //where the data will be comming from
CFDataRef vCardData = (CFDataRef)[vCardString dataUsingEncoding:NSUTF8StringEncoding]; ABAddressBookRef book = ABAddressBookCreate();
ABRecordRef defaultSource = ABAddressBookCopyDefaultSource(book);
CFArrayRef vCardPeople = ABPersonCreatePeopleInSourceWithVCardRepresentation(defaultSource, vCardData);
for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {
ABRecordRef person = CFArrayGetValueAtIndex(vCardPeople, index);
ABAddressBookAddRecord(book, person, NULL);
CFRelease(person);
}
CFRelease(vCardPeople);
CFRelease(defaultSource);
ABAddressBookSave(book, NULL);
CFRelease(book);
}
我使用了这段代码,但它无效。
首先它没有编译这一行:
CFDataRef vCardData = (CFDataRef)[vCardString dataUsingEncoding:NSUTF8StringEncoding];
我不得不改变它:
CFDataRef vCardData = (__bridge CFDataRef)[vCardString dataUsingEncoding:NSUTF8StringEncoding];
并且在编译之后它在此行崩溃:
for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {
它会出现以下绿色错误:Thread1: Program Received Signal "EXC_BAD_ACCESS"
。
有什么理由吗?
这也是在地址簿中保存VCard(NSString格式)的唯一方法吗?还有其他建议吗?
答案 0 :(得分:1)
我假设您已启用ARC。
使用它时CFRetain
vCardData
对象会阻止崩溃吗?数据对象可能只存在直到范围结束。
或者可能更好,请使用__bridge_retained
答案 1 :(得分:1)
将Vcard数据导入Iphone联系人列表。
添加AddressbookUi.framework
添加Addressbook.framework
包含此标题:
#include AddressBook/ABAddressBook.h>
#include AddressBook/ABRecord.h>
#include AddressBook/ABSource.h>
并调用此函数:
-(void)importVcard {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *startPath = [paths objectAtIndex:0];
NSString *filename = @"contacts.vcf";
NSString *filePath = [NSString stringWithFormat:@"%@/%@",startPath,filename];
NSLog(@"File Path is %@",startPath);
NSString *vCardString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
CFDataRef vCardData = (CFDataRef)[vCardString dataUsingEncoding:NSUTF8StringEncoding]; ABAddressBookRef book = ABAddressBookCreate();
ABRecordRef defaultSource = ABAddressBookCopyDefaultSource(book);
CFArrayRef vCardPeople = ABPersonCreatePeopleInSourceWithVCardRepresentation(defaultSource, vCardData);
for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {
ABRecordRef person = CFArrayGetValueAtIndex(vCardPeople, index);
ABAddressBookAddRecord(book, person, NULL);
CFRelease(person);
}
CFRelease(vCardPeople);
CFRelease(defaultSource);
ABAddressBookSave(book, NULL);
CFRelease(book);
}