我目前正与CBPeripheralDelegate
合作,在iOS设备和蓝牙低功耗USB加密狗之间交换消息。我必须实现使用串行仿真服务写入数据字节的sendMessage:
方法。此方法必须在此时发送一个15字节(或更少)的帧,在发送下一个之前等待来自加密狗的确认。
以下是我的代码:
- (void)sendMessage:(NSData *)message {
NSArray *chuncks = [self splitMessage:message];
for (NSUInteger i = 0; i < chunks.count; i++) {
NSData *chunk = [chunks objectAtIndex:i];
[self sendChunk:chunk withId:i ofChunks:chances.count];
// Wait for the ack to be received
}
}
- (void)sendChunk:(NSData *)chunk withId:(NSInteger)id ofChunks:(NSInteger)count {
NSMutableData *frame = [NSMutableData new];
// Here I build my frame, adding header, current chunk ID and total number of chunks, then I call...
[serialEmulationService writeValue:frame forCharacteristic:serialEmulationServiceCharacteristic type:CBCharacteristicWriteWithResponse];
}
现在问题是:for
方法中的sendMessage:
循环必须被阻止,直到外围设备无法收到确认,可能会超时。这个ack是在委托方法- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
中收到的,所以在这里我必须重新启动之前被阻止的for
循环。
这种特殊情况的最佳做法是什么?我想使用GCD的信号量,但我无法弄清楚如何实现同步调用,无法理解解释这种技术的许多在线示例。
有人可以帮我一把吗?
答案 0 :(得分:1)
如何完全跳过for
循环...
@property (nonatomic) NSMutableArray *chunks;
@property (nonatomic) NSInteger chunkId;
- (void)sendMessage:(NSData *)message {
self.chunks = [[self splitMessage:message] mutableCopy];
self.chunkId = 0;
[self sendNextChunk];
}
- (void sendNextChunk {
NSData * chunk = self.chunks.firstObject;
if chunk == nil {
return
}
[self.chunks removeObjectAtIndex: 0];
[self sendChunk:chunk withId:chunkId++ ofChunks:chances.count];
}
- (void)sendChunk:(NSData *)chunk withId:(NSInteger)id ofChunks:(NSInteger)count {
NSMutableData *frame = [NSMutableData new];
// Here I build my frame, adding header, current chunk ID and total number of chunks, then I call...
[serialEmulationService writeValue:frame forCharacteristic:serialEmulationServiceCharacteristic type:CBCharacteristicWriteWithResponse];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {
[self sendNextChunk];
}
答案 1 :(得分:0)
方法是使用Notification
。创建separate method
以运行for loop
。此方法将Notification
delegate
内部的Notification
方法观察sendMessage:
。在linecache.checkcache('outS.txt')
继续将消息添加到属性。