我想编写一个 iOS 应用程序,列出所有附近的蓝牙设备以及它们的名称、UUID、RSSI 以及与我当前位置的大致距离。我探索了 CoreBlueTooth API 并创建了一个中央管理器,但这并没有帮助。以下是我到目前为止所做的。扫描 30 秒后,我没有在我附近找到任何设备,但是当我转到设备设置和蓝牙部分时,它会显示设备列表。知道这里可能有什么问题吗?
- (void)viewDidAppear:(BOOL)animated {
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state != CBCentralManagerStatePoweredOn) {
return;
}
[self scan];
}
- (void)scan
{
self.anAcivityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.anAcivityIndicator.center = self.view.center;
[self.anAcivityIndicator startAnimating];
[self.view addSubview:self.anAcivityIndicator];
[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(stopScanning) userInfo:nil repeats:NO];
[self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
NSLog(@"Scanning started");
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
NSString *aBeaconName = peripheral.name;
NSUUID *anIdentifier = peripheral.identifier;
if (aBeaconName && anIdentifier) {
[self.beaconUUID setObject:anIdentifier forKey:aBeaconName];
}
}
- (void)stopScanning {
[self.centralManager stopScan];
if ([self.beaconUUID count] > 0) {
[self.tableView reloadData];
} else {
UIAlertView *anAlertView = [[UIAlertView alloc] initWithTitle:@"No Data" message:@"No beacon found!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[anAlertView show];
}
}
- (void)alertView:(UIAlertView *)iAlertView clickedButtonAtIndex:(NSInteger)iButtonIndex {
[self.navigationController popToRootViewControllerAnimated:YES];
}