Search code examples
objective-ccore-bluetooth

Core-bluetooth - Is it possible to do a synchronous read?


I'm building a IoT device and I have asynchronous reads working great, but I need to perform a synchronous read. I've been told this is possible on Android as there is a method that basically reads the buffer as it comes in.

I'm wondering if Core-bluetooth supports something similar or if anyone has a clever approach to this?


Solution

  • Any asynchronous operation can be made synchronous by blocking until the operation completes. You can use a queue or a lock to block.

    NSLock *lock = [[NSLock alloc] init];
    [thing doSomethingAsynchronousWithCompletion:^{
         [lock unlock];
     }];
    
     [lock lock];
    

    Do not do this. Not ever.

    You shouldn't block. Your asynchronous code's completion handler should trigger an event that causes your code to continue.

    [thing doSomethingAsynchronousWithCompletion:^(NSData *readData){
         [dataProcessor processData:readData];
     }];