0

我需要创建一个常规计时器来读取蓝牙外设的 RSSI 值。我的代码有一个 ViewController 是一个对象的委托,而该对象又是蓝牙的委托:

在我的视图控制器中:

@property (weak, nonatomic) ioeBLE *bleControllerOfDiscoveredGateway;

在 ioeBLE 类 (ioeBLE.h) 中:

@protocol ioeBLEDelegate <NSObject>
@optional
-(void) responseFromBLEController:(NSString *)sw;
@required
@end


@interface ioeBLE : NSObject <CBCentralManagerDelegate, CBPeripheralDelegate>

@property (nonatomic,assign) id <ioeBLEDelegate> delegate;
@property (strong, nonatomic) NSMutableArray *peripherals;
@property (strong, nonatomic) CBCentralManager *CM;
@property (strong, nonatomic) CBPeripheral *activePeripheral;

@end

在 ioeBLE.m 中实现了 CBPeripheralDelegate 的委托方法之一:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{

// Code Here 

}

在我的 ViewController - 我正在尝试创建一个常规计时器来使用计时器选择器读取 RSSI 值,这是计时器创建的代码:

// Schedules a new timer, adds it to the current run loop and waits forever.
- (void) startTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval: 10.0
                                              target:self
                                            selector:@selector(request)
                                            userInfo:nil
                                             repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
//    [[NSRunLoop mainRunLoop] runUntilDate:[NSDate distantFuture]];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
}

我在 viewDidAppear 中调用了 Timer:

[self startTimer]

我遇到的问题很简单 - 当我如上所述设置计时器时,didUpdateValueForCharacterstic不会调用/调用。我注释掉上面的计时器,它开始工作。我已经确认数据到达连接到 iPhone 的 activePeripheral,并且连接是活动的,但是从 Peripheral 返回的响应永远不会返回,因为没有调用委托方法。

4

1 回答 1

0

Found the FIX. All right, my bad - I should NOT have been calling [self startTimer], I needed to have this:

- (void) start
{
    @autoreleasepool {
        [NSThread detachNewThreadSelector:@selector(startTimer)
                                 toTarget:self
                               withObject:nil];
    }
}

And then in viewDidAppear:

[self start]
于 2013-09-04T01:43:28.333 回答