Scan peripheral when app in background (ex. when screen locked)

自作多情 提交于 2020-06-23 14:08:12

问题


I have an app which is working in background. I use CBPeripheralManager to Advertising and CBCentralManager to scan. I use two ıos (IOS 11.3 and IOS 13.4.1) device. First one is advertising foreground and background. Second one is scan foreground and background. I can scan;

App in the background, phone is unlocked - Works perfect

App in background, phone is locked, screen is lighted - Works perfect

App in background, phone locked, screen is off - Doesn't work!

/* I check it Advertising app which run background show in Android Device */

What is the problem. Please let me know. How can solve this problem? I want to scan both in background. My code is given bellow;

let scanOptions = [
        CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: true)
    ]

let services = [CBUUID(string: "e2c56db5-dffb-48d2-b060-d0f5a71096e0")]

let advertisingData = [
        CBAdvertisementDataLocalNameKey: "xxx",
        CBAdvertisementDataServiceUUIDsKey:[CBUUID(string: "e2c56db5-dffb-48d2-b060-d0f5a71096e0")]
        ] as [String : Any]

func initLocal() {

        peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
        cbCentralManager = CBCentralManager(delegate: self, queue: nil,options: nil)

    }

func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {

        if peripheral.state == .poweredOn {
            peripheralManager.startAdvertising(advertisingData)
        }
       else if peripheral.state == .poweredOff {
            peripheralManager.stopAdvertising()
        }
    }

func centralManagerDidUpdateState(_ central: CBCentralManager) {

        if central.state == .poweredOn{

            central.scanForPeripherals(withServices: services,options:scanOptions)
            print("scanning...")

        }
        else {
            print("Bluetooth is not active")
        }
    }

func centralManager(_ central: CBCentralManager,didDiscover peripheral: CBPeripheral,advertisementData: [String : Any],
                        rssi RSSI: NSNumber)
    {

        print("RSSI   : \(RSSI)")

    }

This is my info.plist;


回答1:


You seem to be expecting duplicates since you've set CBCentralManagerScanOptionAllowDuplicatesKey. That key is ignored in the background. If you're expecting to see the same device more than once via advertising, that's impossible. Discovering new devices that you haven't seen before should work, however. Are you having trouble with that? (You should explain the details of exactly how you're testing this, what precise behaviors you see, and what you expect to see. Bluetooth is very subtle. The details matter quite a lot, and "not working" is far too vague.)



来源:https://stackoverflow.com/questions/61666657/scan-peripheral-when-app-in-background-ex-when-screen-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!