構建一個應用程序以連接到Arduino藍牙模塊,發現設備正常,但是當涉及到發現服務時,它始終爲零。 我沒事到發現服務功能,我真的不明白無法從外設發現藍牙服務
這裏是我的代碼:
import UIKit
import CoreBluetooth
class Devices: UITableViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
var devices = [String]()
var centralManager : CBCentralManager!
var peripheral: CBPeripheral!
var central: CBCentralManager!
var peripheralArray: [CBPeripheral] = []
var service : CBService!
var deviceConnected = false
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl = UIRefreshControl()
self.refreshControl!.addTarget(self, action: "scanForDevices:", forControlEvents: UIControlEvents.ValueChanged)
tableView.tableFooterView = UIView()
central = CBCentralManager(delegate: self, queue: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func centralManagerDidUpdateState(central: CBCentralManager) {
if central.state == CBCentralManagerState.PoweredOn {
print("Bluetooth On")
}
else {
print("Bluetooth off or not supported")
}
}
func scanForDevices(sender: AnyObject) {
devices.removeAll()
print("Scanning")
central.scanForPeripheralsWithServices(nil, options: nil)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
self.central.stopScan()
self.refreshControl?.endRefreshing()
print("Stopped Scanning")
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
(advertisementData as NSDictionary).objectForKey(CBAdvertisementDataLocalNameKey) as? NSString
let list = String(peripheral.name!)
if (devices.contains(list)){
} else {devices.append(list)
peripheralArray.append(peripheral)
}
tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return devices.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("device")! as UITableViewCell
cell.textLabel?.text = devices[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if(deviceConnected == false){
self.central.connectPeripheral(peripheralArray[indexPath.row], options: nil)
deviceConnected = true
}else{
self.central.cancelPeripheralConnection(peripheralArray[indexPath.row])
deviceConnected = false
}
discoverServices()
self.peripheral = peripheralArray[indexPath.row]
print(self.peripheral.services)
}
func discoverServices(){
for service in peripheral.services! {
let thisService = service as? CBService
if let thisService = thisService{
peripheral.discoverCharacteristics(nil, forService: thisService)
}
}
}
}
在你確認你通過'didConnectPeripheral'委託方法連接到外設之前,不要調用'discoverServices' – Paulw11