1
我正在嘗試創建一個應用程序,它將掃描外圍BLE設備。我使用的是BLE Mini,我可以在LightBlue和RedBear iPhone應用程序中看到它。我已經確認掃描在BLE開機時開始,但是當我運行我的程序時,沒有發現BLE設備。我已經瀏覽了很多在iOS中實現Corebluetooth的例子,看起來我擁有所有必需的功能。我哪裏錯了?感謝您的幫助。iOS藍牙不發現設備
// BlueToothVC.swift
import UIKit
import CoreBluetooth
class BlueToothVC: UIViewController, UITableViewDataSource, UITableViewDelegate, CBCentralManagerDelegate
{
@IBOutlet weak var tableView: UITableView!
var centralManager: CBCentralManager!
var peripherals: Array<CBPeripheral> = Array<CBPeripheral>()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//CoreBluetooth methods
func centralManagerDidUpdateState(_ central: CBCentralManager)
{
if (central.state == CBManagerState.poweredOn)
{
print("scanning")
self.centralManager?.scanForPeripherals(withServices: nil, options: nil)
}
else
{
// do something like alert the user that ble is not on
}
}
private func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber)
{
peripherals.append(peripheral)
tableView.reloadData()
print("saw something")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peripherals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "BTCell")! as! BTCell
let peripheral = peripherals[indexPath.row]
cell.label.text = peripheral.name
return cell
}
@IBAction func touchCancel(_ sender: AnyObject) {
self.navigationController?.popViewController(animated: true)
}
}
非常感謝你之前!這解決了我的問題。 – KaplanAlex