ABAddressBookRequestAccessWithCompletion线程安全

来源:互联网 发布:网络群组信息管理规定 编辑:程序博客网 时间:2024/06/05 15:02

1、访问通讯录

iOS在第一次访问用户通讯录时,需要调用ABAddressBookRequestAccessWithCompletion然后在CallBack中调用UI模块进行联系人数据展示。
一般的形式如下:
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {                    if (granted)                    {                        //展示联系人数据                    }                    else                    {                        //提示用户设置访问权限                    }});

2、线程安全

用于回调的block是在子线程被调用,可以在block中添加如下代码:

 ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted,CFErrorRef error) {                   if ([[NSThreadcurrentThread]isMainThread]) {                       NSLog(@"main thread");                    }                   else                    {                       NSLog(@"child thread");                    });

运行会发现,最后是子线程回调该block的,如果在子线程中直接操作UI模块是不被允许的,UI的操作应该放在主线程中:

ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {//                    if ([[NSThread currentThread] isMainThread]) {//                        //NSLog(@"main thread");//                    }//                    else//                    {//                        //NSLog(@"child thread");//                    }                    dispatch_async(dispatch_get_main_queue(), ^{                        if (granted)                        {                            TKContactsMultiPickerController *contactMultiController = [[TKContactsMultiPickerController alloc] initWithGroup:nil];                            contactMultiController.addressBook = self.addressBook;                            contactMultiController.delegate = self;                            [self.navigationController pushViewController:contactMultiController animated:YES];                                                   }                        else                        {                            [self.view makeToast:NSLocalizedString(@"your system Settin", nil)                                        duration:1.0                                        position:@"center"];                        }                    });                });


0 0
原创粉丝点击