Я разрабатываю приложение, используя CoreBluetooth. Я могу обнаруживать устройства из приложения и отображать их имена в виде таблицы. Я столкнулся с проблемой с требованиями ниже:
- При первом использовании пользователь выбирает периферийное устройство из списка. Соединение с периферийным устройством должно быть установлено с использованием профиля последовательного порта Bluetooth (SPP). Обнаружение и подключение выполняются простым щелчком мыши, что сводит к минимуму взаимодействие с пользователем.
- Как только соединение между периферийным устройством и приложением установлено, приложение запоминает устройство и всегда ищет его и подключается к нему для всех последующих использований.
Я написал для этого следующий код, как показано ниже, для сканирования и обнаружения
- (void)scan
{
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
NSLog(@"options are %@",options);
[self.centralManager scanForPeripheralsWithServices:nil
options:nil];
_txtLogMessage.text = [NSString stringWithFormat:@"%@ \n %@",_txtLogMessage.text,@"Scanning started"];
NSLog(@"Scanning started");
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral
*)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
[central connectPeripheral:peripheral options:nil];
self.discoveredPeripheral = peripheral;
_logData = [NSString stringWithFormat:@"Did discover peripheral. peripheral: %@ rssi: %@, UUID: %@ advertisementData: %@ ", peripheral, RSSI, peripheral.UUID, advertisementData];
NSLog(@"%@",_logData);
[_periferalDevices addObject:peripheral.name];
[_tableView reloadData];
}
для подключения устройства
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
peripheral.delegate = self;
[self.discoveredPeripheral discoverServices:nil];
NSLog(@"Peripheral Connected");
NSLog(@" started time is %@",_timestring);
//[self.centralManager stopScan];
NSLog(@"Scanning stopped");
[self.data setLength:0];
[peripheral discoverServices:nil];
[peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
}
в ячейке представления таблицы для строки в пути индекса цель может получить данные для просмотра, но цель - столкнуться с проблемой подключения к периферийному устройству, когда конкретная строка выбрана в представлении таблицы
- (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.textLabel.text = [_periferalDevices objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_discoveredPeripheral.delegate = self;
[self.centralManager connectPeripheral:[_periferalDevices objectAtIndex:indexPath.row]
options:nil];
NSLog(@"discovered peripheral is %@",[_periferalDevices objectAtIndex:indexPath.row]);
NSString *datstr=[_discoveredPeripheral valueForKey:@"identifier"];
NSLog(@"value for key is ........%@",datstr);
}