【问题标题】:scan bluetooth device once appearing the uicontroller出现 uicontroller 后扫描蓝牙设备
【发布时间】:2016-06-14 01:48:15
【问题描述】:

我是编程新手,可能无法用恰当的术语来描述。

我正在编写一个应用程序,一旦它出现在屏幕上,我就想要它。它会自动扫描设备 5 秒并放在表格视图上以显示详细信息。

我还写了一个动作方法来响应 UIBarButtonItem 的重新加载。 操作方法工作正常。它将设备信息放在单元格上。

所以,我将此操作方法放入 viewDidLoad 块中,以便在视图加载后扫描蓝牙设备。 但它不起作用。但是我知道当控制器弹出时,动作方法正在运行。但它没有显示有关单元格的任何信息。我需要按重新加载来扫描并在单元格上列出。

override func viewDidLoad() {
    super.viewDidLoad()

    btCentralManager = CBCentralManager(delegate: self, queue: nil)
    btCentralManager.delegate = self

    actionScan(navigationItem.rightBarButtonItem!)
}

重新加载按钮:

@IBAction func actionScan(sender: UIBarButtonItem) { // works fine.
    sender.enabled = false
    navigationItem.title = "Scanning..."
    btConnectable.removeAll()
    btPeripherals.removeAll()
    btRSSIs.removeAll()
    NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(ScanTableViewController.stopScan), userInfo: nil, repeats: false)
    btCentralManager.scanForPeripheralsWithServices(nil, options: nil)
}

控制器弹出后如何在桌面上扫描和列出?

谢谢。

【问题讨论】:

    标签: ios swift bluetooth


    【解决方案1】:

    尝试添加CBCentralManagerDelegate方法:

    func centralManagerDidUpdateState(central: CBCentralManager) {
            if central.state == CBCentralManagerState.PoweredOn {
                startScan()
            }
    }
    

    并添加这样的方法:

    func startScan() {
            self.timer?.invalidate()
            self.centralManager?.scanForPeripheralsWithServices(nil, options: nil)
            self.timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "stopScan", userInfo: nil, repeats: false)
        }
    
        func stopScan() {
            self.centralManager?.stopScan()
        }
    

    如果您想在每次视图控制器出现在屏幕上时运行任何方法 - 从 viewWillAppear 或 viewDidAppear 调用这些方法。 viewDidLoad 仅在加载视图控制器时调用一次。

    【讨论】:

    • 我有这个 centralManagerDidUpdateState 方法。我跟着你并将扫描操作方法放入此块中。它有效。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2020-06-03
    • 2022-01-04
    相关资源
    最近更新 更多