我似乎找不到这个问题的答案,所以我在这里发帖。
基本上,我有一个与 iPhone 配对的蓝牙设备,所有用户都将拥有相同的蓝牙设备。
我需要的是一种创建“服务”的方法,以便当设备进入执行特定功能的范围时。我只需要代码每天运行一次(最好)并且只需要几秒钟就可以完成,然后我的应用程序被终止就可以了。
我很难相信没有其他人尝试过这样做。任何想法或想法将不胜感激。
我也需要在 android 上做这个,但我会在谷歌搜索后发布一个单独的问题
最佳答案
这是使用 Core Bluetooth 执行此操作的一种方法:
1. Opt into Core Bluetooth's background modes 2. Create a CBPeripheralManager with an identifier (for background mode) and implement all of the CBPeripheralManagerDelegate methods 3. Once you receive the delegate callback peripheralManagerDidChangeState: and the state is CBPeripheralManagerStatePoweredOn a. Create a CBMutableCharacteristic with an app-specific UUID (use the CBUUID class method UUIDWithString:). You can generate a UUID in terminal using "uuidgen" b. Create a CBMutableService and set the characteristic (above) to the services's characteristic property c. In the CBPeripheralManagerDelegate peripheralManager:didAddService:error: method, publish the service with options passing a NSDictionary with a key-value pair being CBAdvertisementDataServiceUUIDsKey:a_UUID where a_UUID is another UUID generated from terminal or the same UUID as the characteristic. 4. Create a CBCentralManager with an identifier and implement all of the CBCentralManagerDelegate methods as well as all of the CBPeripheralDelegate methods. 5. Once you receive the delegate callback centralManagerDidChangeState: and the state is CBCentralManagerStatePoweredOn, Scan for peripherals that are advertising a service with the same UUID you used in step 3c. 6. When you discover a peripheral a. Retain the peripheral any way you want and attempt to connect. b. Once you receive the CBCentralManagerDelegate centralManager:didConnectPeripheral: method i. Set yourself as the delegate of the peripheral ii. Discover the service you created in step 3b iii. Discover the characteristic you created in step 3a using the UUID you used in step 3a. 7. At this point the two devices are able to communicate at the application layer, if you will. You could read the value of the peripheral's characteristic and in the CBPeripheralManagerDelegate peripheralManager:didReceiveReadRequest: method execute the function you mention in your question. 8. Cancel the connection from the peripheral.
**请注意,iOS + Android 蓝牙连接将不起作用。
关于iOS 蓝牙服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25149475/