<coreBluetooth>peripheralとしてアドバタイズする
swift、coreBluetoothともに初心者です。
coreBluetoothの理解のために、まずperipheralでサービスUUIDを指定してそれをcentralで検索するというシステムを作っています。
色々調べながら作成してcentralの方は完成したのですが、peripheralの方でエラーが出てしまい、詰まってしまっています。
central、peripheralはそれぞれ別のプロジェクトで作成して、2端末で実験しています。
発生している問題・エラーメッセージ
*** Terminating app due to uncaught exception 'Invalid Object', reason: 'Object <CBMutableService: xxxx Primary = YES, UUID = xxxx, Included Services = (null), Characteristics = ( "<CBMutableCharacteristic: xxxx UUID = xxxx, Value = (null), Properties = xxxx, Permissions = xxxx, Descriptors = (null), SubscribedCentrals = (\n)>" )> is invalid' *** First throw call stack: (xxxx) libc++abi: terminating with uncaught exception of type NSException *** Terminating app due to uncaught exception 'Invalid Object', reason: 'Object <CBMutableService: xxxx Primary = YES, UUID = xxxx, Included Services = (null), Characteristics = ( "<CBMutableCharacteristic: xxxx UUID = xxxx, Value = (null), Properties = xxxx, Permissions = xxxx, Descriptors = (null), SubscribedCentrals = (\n)>" )> is invalid' terminating with uncaught exception of type NSException
該当のソースコード
class ViewController: UIViewController, CBPeripheralManagerDelegate{ var manager: CBPeripheralManager! var service: CBMutableService! var characteristic: CBMutableCharacteristic! override func viewDidLoad() { super.viewDidLoad() self.manager = CBPeripheralManager(delegate : self, queue : nil, options: nil) } func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { switch peripheral.state { case .poweredOn: service = CBMutableService(type: CBUUID(string: "xxxx"), primary: true) let properties: CBCharacteristicProperties = [.notify, .read, .write] let permissions: CBAttributePermissions = [.readable, .writeable] characteristic = CBMutableCharacteristic(type: CBUUID(string: "xxxx"),properties: properties, value: nil, permissions: permissions) self.service.characteristics = [self.characteristic] self.manager.add(self.service) case .unknown: print("bluetooth error") case .resetting: print("bluetooth error") case .unsupported: print("bluetooth error") case .unauthorized: print("bluetooth error") case .poweredOff: print("bluetooth error") @unknown default: print("bluetooth error") } } func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) { if error != nil { print("Service Add Failed...") return } print("Service Add Success!") if (self.manager.isAdvertising == false) { //アドバタイズ開始 print("start") manager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [service], CBAdvertisementDataLocalNameKey: "TestPeripheralDevice"]) } } func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { if let error = error { print("Failed... error: (error)") return } print("Succeeded!") }
開発環境
・Xcode Version 12.5.1
・swift
・実装端末:iPhone12、iPhone6s
あなたの回答
tips
プレビュー