2013-12-20 179 views
2

我實現的代碼,但連接到BLE裝置時,顯示警告:無法連接到BLE設備的iOS

2013-12-20 16:58:57.975 TestPeripheral[1054:60b] CoreBluetooth[WARNING] <CBPeripheral: 635 identifier = Addfew23-424-E653-8E58-424343, Name = "BLE", state = connecting> is being dealloc'ed while connecting 

我用下面的代碼:

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { 


    NSLog (@"Discovered peripheral: %@", [peripheral name]); 

    NSLog (@"UUID peripheral: %@", [peripheral UUID]); 

    NSLog (@"peripheral services before connected: %@", [peripheral services]); 


    deviceName.text = [NSString stringWithFormat:@"Device Name: %@", [peripheral name]]; 
    deviceUUID.text = [NSString stringWithFormat:@"Device UUID: %@",[peripheral UUID]]; 

    [self.manager stopScan]; 
    NSLog(@"Scanning stopped"); 

    NSLog (@"start connecting to device"); 
    [self.manager connectPeripheral:peripheral options:nil]; 
    self.activePeripheral = peripheral; 
} 

- (void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals 
{ 
    for (CBPeripheral *peripheral in peripherals) { 
     NSLog(@"Retrieved Peripheral %@", peripheral.name); 
     [foundArray addObject:peripheral.name]; 
    } 
} 

我添加外設foundarray和向他們展示如下:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [foundArray count]; 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ; 

     cell.selectionStyle = UITableViewCellSelectionStyleGray; 
    } 


    cell.textLabel.text = [foundArray objectAtIndex:indexPath.row]; 

    return cell; 
} 

當用戶選擇設備連接時,它會顯示消息等待:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     NSInteger row = indexPath.row; 
     UIAlertView *alertPair = [[UIAlertView alloc] initWithTitle:@"Connecting" message:@"Waiting to connect" delegate:nil cancelButtonTitle:@"OK", nil]; 

     [alertPair show]; 
    } 

請給我一些建議。非常感謝。

回答

2

CoreBluetooth [警告]是 而連接

被dealloc'ed時,如果未保留新連接的外圍設備,則會發生此警告。連接到外圍設備後,必須保留對它的引用(保留在mrc中或強制引用)。否則,系統會清理本地範圍,並假定您不關心外設。所以基本上,只要保持一個參考,你會很好走。

+0

我猜''self.activePeripheral = peripheral;'行會這樣做,但它可能在其他地方沒有。 – allprog

+0

我用ARC和我在.h中定義CBPeripheral爲:「@屬性(強)CBPeripheral * activePeripheral;」。我用它堅強。 – user3114750

+1

是否有可能導航離開視圖控制器?就像實驗一樣,因爲它確實是BAD DESIGN,嘗試將'activePeripheral'屬性添加到應用程序委託。 – allprog