ABAddressBookRequestAccessWithCompletion iOS 7和信号量
这个代码之前已经发布了,并且已经被使用,从我可以收集。 我在这种情况下,我需要的代码不会继续,直到我知道我是否有权访问联系人。
在Xcode 5.0.2和iOS 6上,这工作得很好。 在iOS 7上,它永远挂起,然后当我杀了应用程序的对话框出现要求允许访问联系人。
ABAddressBookRef addressBook = ABAddressBookCreate(); __block BOOL accessGranted = NO; if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6 dispatch_semaphore_t sema = dispatch_semaphore_create(0); ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { accessGranted = granted; dispatch_semaphore_signal(sema); }); dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); } else { // we're on iOS 5 or older accessGranted = YES; }
在试图玩这个,然后我简单地设置BOOL为NO,然后在块内设置为YES。 在块之后,我把一个while循环检查variables是YES,然后睡1秒。 在6上工作得非常好,7日我从来没有达到块中的NSLog语句,我永远卡在while循环打印日志语句。
我在这里做了些什么蹩脚的事情? 或者是这种方法在7?
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error); ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { if (granted) { self.myAddressBook = addressBook; } done = YES; NSLog(@"in block, done is %@", done ? @"YES" : @"NO"); didGrant = granted; //dispatch_semaphore_signal(sema); }); while (!done) { NSLog(@"done is %@", done ? @"YES" : @"NO"); sleep(1); }
我有同样的问题,我意识到请求访问联系人的对话框无论如何封锁了应用程序,所以也许有一个死锁。 所以我只是放弃了信号量,做了这样的事情(经过testing,在iOS 7.1.1上运行):
ABAddressBookRef addressBook = ABAddressBookCreate(); MyController * __weak weakSelf = self; if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6 if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) { ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf accessGrantedForAddressBook]; }); }); } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized); //Maybe add something here to handle kABAuthorizationStatusRestricted [self accessGrantedForAddressBook]; } } else // we're on iOS 5 or older [self accessGrantedForAddressBook];
这与苹果在其文档中所做的很相似(searchABAddressBookRequestAccessWithCompletion)。 另外,ABAddressBookRequestAccessWithCompletion是asynchronous的,等待它(见这里 )..