方法connectPeripheral在具有CBCentralManagerDelegate的类中定义。当选择didSelectRowAtIndexPath时,我需要从表视图控制器调用connectPeripheral。连接外设后,它应继续在视图控制器中执行剩余的代码行。我能够连接外围设备。但在连接完成之前,它会执行代码的剩余部分。由于外围设备尚未连接,因此无法完成必要的工作。
我使用dispatch_sync来确保建立连接,然后执行剩余的代码,但它不起作用。我怎样才能解决这个问题?我对IOS编程比较陌生。任何投入都受到高度赞赏。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
CBPeripheral *peripheral = nil;
NSArray *devices = [[NSArray alloc] init];
switch (indexPath.section) {
case 0: {
devices = [[BTLECentralManager sharedInstance] foundPeripherals];
peripheral = (CBPeripheral *)[devices objectAtIndex:indexPath.row];
dispatch_sync(syncConnection, ^{
[[BTLECentralManager sharedInstance] connectPeripheral:peripheral];
activePeripheral = [self serviceForPeripheral:peripheral];
NSLog(@"Active Peripheral %@",activePeripheral);
[activePeripheral getTimeDate];
});
break;
}
default:
break;
}
}
答案 0 :(得分:0)
连接外设的请求是一个异步过程。您不能将其包装在dispatch_sync
中以使其同步。 (无论如何,你并不想让它同步。)
connectPeripheral
的同步调度仅仅是同步调度连接到该外设的请求,但并未改变连接过程本身的固有异步性质。实际上,您通常不希望将这些异步请求分派给您自己的后台队列。 Apple提供了一个很好的异步接口,所以你继续从主线程中使用它。
虽然从理论上讲,您可以为此连接过程创建同步接口,但您不应该这样做。相反,您应该拥抱接口的异步特性。实现委托,或者可能将CBCentralManager
包装在提供基于块的接口的某个对象中。