首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在背景iOS中重新连接无刷电子设备

在背景iOS中重新连接无刷电子设备
EN

Stack Overflow用户
提问于 2017-11-21 09:03:56
回答 1查看 2.2K关注 0票数 1

我的应用程序可以在前台连接到BLE设备。但是,当应用程序处于后台时,BLE设备在断开设备后不会重新连接。我在info.plist中添加了必需的权限:

代码语言:javascript
复制
<key>UIBackgroundModes</key>
    <array>
        <string>bluetooth-central</string>
        <string>bluetooth-peripheral</string>
    </array>

我在HomeViewController中创建了用于扫描的中央管理器对象:

代码语言:javascript
复制
   let centralManager = CBCentralManager(delegate: self, queue: nil)
   centralManager.delegate = self
   let options  = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
   centralManager.scanForPeripherals(withServices:nil, options: options)

我在后台的应用程序中尝试了scanForPeripherals,但是它不起作用:

代码语言:javascript
复制
 let backgroundScanOptions  = [CBCentralManagerScanOptionSolicitedServiceUUIDsKey : true]
 centralManager.scanForPeripherals(withServices: [customServiceUUIDs], options: backgroundScanOptions)

在后台我能为重新连接设备做些什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-21 10:47:07

swift 4

代码语言:javascript
复制
import UIKit
import CoreBluetooth

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CBCentralManagerDelegate, CBPeripheralDelegate{

var window: UIWindow?

        //MARK:- all variables...
var bleCentralManager: CBCentralManager!
var selectedPeripheral: CBPeripheral!
let serviceUUIDForBackgroundScanning: [CBUUID] = [CBUUID(string: "07A2715C-3B28-4F7F-8824-BA18255B2344")

func bleCentralManagerfunc(){

    self.bleCentralManager = CBCentralManager(delegate: self, queue: nil)
}

        //MARK:- CBCentralManagerDelegate methods...
func centralManagerDidUpdateState(_ central: CBCentralManager) {

    switch central.state{

        case .poweredOn:    central.scanForPeripherals(withServices: nil, options: nil)

        default: print("Please turn on Bluetooth")
    }
}

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

    if !(self.arrayPeripheralList.contains(peripheral)){

            self.arrayPeripheralList.append(peripheral)
    }
}

func applicationDidEnterBackground(_ application: UIApplication) {

    self.bleCentralManager.scanForPeripherals(withServices: serviceUUIDForBackgroundScanning, options: nil)
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47409097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档