Charlie
Charlie

Reputation: 1

iOS CBPeripheral connect Questions

I call method

(void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options;

to connect my device ,my device is in range , but my app still can't connect my device success, when I turn off system BT and then turn on BT ,my app will connect my device success , I don't know why ?

If I do not turn off BT and then turn on , May I call first call method

(void)cancelPeripheralConnection:(CBPeripheral *)peripheral;

then call

(void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options;

is it will be make sense ?

Upvotes: 0

Views: 253

Answers (1)

Dipesh Khandhar
Dipesh Khandhar

Reputation: 96

To check weather your device is connected or not, you can user these two delegate methods: Objective C:

1) -(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

2) -(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

@property (nonatomic, strong) CBPeripheral *heartRatePeripheral;
#define heartRateServiceCBUUID [CBUUID UUIDWithString:@"0x180D"]

-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral 
  *)peripheral
{ 
  [self.Customdelegate HRMoniterStatus:peripheral Status:@"Connected"];
  [_heartRatePeripheral discoverServices:@[heartRateServiceCBUUID]];
}

CustomDelegate:

-(void)HRMoniterStatus:(CBPeripheral *)HRMoniter Status:(NSString 
*)connectionStatus
{
  NSLog(@"HRMoniter connection status ::- %@",connectionStatus);
}

Swift :

1) func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)

2) func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?)

let heartRateServiceCBUUID = CBUUID(string: "0x180D")

let heartRatePeripheral : CBPeripheral

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)
{
    Customdelegate.hrMoniterStatus(peripheral, status: "Connected")
    heartRatePeripheral.discoverServices([heartRateServiceCBUUID])
}

Custom Delegate:

func hrMoniterStatus(_ HRMoniter: CBPeripheral?, status connectionStatus: String?) 
{
   print("HRMoniter connection status ::- \(connectionStatus ?? "")")
}

Upvotes: 1

Related Questions