2014-07-07 43 views
4

我試圖將coreBluetooth集成到我的應用程序中。這裏是我的代碼:調用discoverService後CBPeripheral connection保持斷開連接

@interface Central() <CBCentralManagerDelegate> 
@property (strong, nonatomic) CBPeripheral * activePeripheral; 
@property (strong, nonatomic) CBCentralManager * centralManager; 
@end 

@implementation Central 

- (id) init 
{ 
    self = [super init]; 
    if (self) 
    { 
     NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey: @YES}; 
     self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:defaultGlobalQueue options:options]; 
    } 
    return self; 
} 

- (void) startScanning:(NSInteger)timeout 
{ 
    self.activePeripheral = nil; 
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]] options:nil]; 
} 

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI 
{ 
    if (self.activePeripheral != nil) 
    { 
     return; 
    } 
    self.activePeripheral = peripheral; 
    [self.centralManager connectPeripheral:peripheral options:nil]; 

} 

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral 
{ 
    [self.activePeripheral discoverServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]]]; 
} 

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error 
{ 
// dispatch_async(dispatch_get_main_queue(), ^{ 
    NSLog(@"Disconnected from peripheral : %@",peripheral); 
    if (error) 
    { 
     NSLog(@"Error disconnecting peripheral: %@", error.localizedDescription); 
     //[self didErrorDelegateWithPeripheral:peripheral andError:error andCode:BLE_FAILED_TO_CONNECT]; 
    } 
} 
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error 
{ 
    //Logic here 
} 

我一個viewcontroller內調用startScanning,它始終在(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error回調調用[self.activePeripheral discoverServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]]];

這裏後進入的錯誤我經常看到:

Error Domain=CBErrorDomain Code=7 "The specified device has disconnected from us." UserInfo=0x175b8810 {NSLocalizedDescription=The specified device has disconnected from us.} 

任何人都知道我錯過了什麼?

感謝您的幫助。

回答

9

我終於想通了這個問題,我們需要設置外圍發現的代表試圖發現服務

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral 
{ 
peripheral.delegate = self; 
    [self.activePeripheral discoverServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]]]; 
} 
+0

順便說一下這是不是CoreBluetooth有關前。在做任何需要處理的事情之前總是插入事件處理程序 - 在其他語言中也是如此。 – Etan

相關問題