- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_cm = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
+ (NSString*)UUIDString:(CFUUIDRef)uuid {
CFStringRef string = CFUUIDCreateString(NULL, uuid);
return (__bridge_transfer NSString*)string;
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state == CBCentralManagerStatePoweredOn) {
[self scanForPeripherals];
}
}
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
// NSLog(@"Received peripheral : \n%@", peripheral);
// NSLog(@"Adv data : %@", advertisementData);
[peripheral setDelegate:self];
[central connectPeripheral:peripheral options:nil];
[peripheral readRSSI];
}
- (int)scanForPeripherals {
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey,
nil];
[_cm scanForPeripheralsWithServices:nil options:options];
return 0;
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"didConnectPeripheral");
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@"didDisconnectPeripheral");
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@"failed to connect");
}
- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {
NSLog(@"didReadRSSI");
}
这些设备不是我自己的。我不知道它的接近度UUID,但据我所知,通过CoreBluetooth进行连接时不需要它吗?
所有设备都是在didDiscoverPeripheral:
中发现的,在我尝试连接它们的选择器中。但那之后什么都没有。
当我致电didDiscoverPeripheral:
时,我是否期望与配对密码请求对话?
如果是这样,我没有看到任何对话,为什么会这样?
从苹果文档中,它清楚地表明,在尝试连接到设备后,您应该拨打didConnectPeripheral
或didFailToConnectPeripher
,但我没有。
有什么想法?我现在已经尝试了差不多一个星期了。 感谢每一个帮助,谢谢。
答案 0 :(得分:61)
如果您不以某种方式保留传递给peripheral
的{{1}}对象,则一旦此委托方法退出并且您无法获得连接,它就会被释放。
我建议添加一个属性来跟踪发现的外围设备
didDiscoverPeripheral
在@property (strong,nonatomic) NSMutableArray *peripherals;
或viewDidLoad
init
然后在self.peripherals=[NSMutableArray new];
didDiscoverPeripheral
答案 1 :(得分:3)
var peripherals = [CBPeripheral]()
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
peripherals.append(peripheral)
bleManager.connectPeripheral(peripheral, options: nil)
}
这是Swift版本。