监听手机通讯录的变化减少每次进入程序重新获取通讯录信息。主要使用了AddressBook
和CNContact
来完成
有两种实现方式:
1.使用框架AddressBook
//监听通讯录变化
void addressBookChanged(ABAddressBookRef addressBook, CFDictionaryRef info, void *context)
{
NSLog(@"AddressBook Changed");
// VC1 *myVC = (__bridge VC1 *)context;
// [myVC getPersonOutOfAddressBook];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
ABAddressBookRef addresBook = ABAddressBookCreateWithOptions(NULL, NULL);
ABAddressBookRegisterExternalChangeCallback(addresBook, addressBookChanged, (__bridge void *)(self.viewcontrller));
}
```
调用此方法需要放在-application:didFinishLaunchingWithOptions:
2.使用CNContact框架,
**Obj-C code:**
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressBookDidChange:) name:CNContactStoreDidChangeNotification object:nil];
然后
-(void)addressBookDidChange:(NSNotification*)notification{
}
**Swift code:**
NSNotificationCenter.defaultCenter().addObserver( self, selector: "addressBookDidChange:", name: CNContactStoreDidChangeNotification, object: nil)
然后
@objc func addressBookDidChange(notification: NSNotification){
}