2016-01-25 6 views
0

Создание приложения для подключения к модулю bluetooth Arduino, находит устройства в порядке, но когда дело доходит до обнаружения служб, оно всегда равно нулю. Im штраф до функции обнаружения сервисов, которые я не понимаюНевозможно обнаружить службы bluetooth от периферийных устройств

Вот мой код:

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) 
      } 
     } 
    } 




    } 
+1

Не вызывайте 'discoverServices', пока не получите подтверждение того, что вы подключены к периферийному устройству с помощью метода делегирования' didConnectPeripheral' – Paulw11

ответ

0

Вы собираетесь прямо к характерному открытию без обнаружения услуг первых. Прежде чем звонить звоните discoverCharacteristics, вам необходимо позвонить по телефону discoverServices. Как только службы будут обнаружены, будет вызван метод делегата peripheral:didDiscoverServices:, и вы можете использовать его для запуска обнаружения признаков.

Для discoverServices вызова, вы можете передать ему массив CBUUID адресов, которые вы хотите открыть (рекомендуется) или, если вы не знаете, какие услуги вы хотите, вы можете передать его nil открыть для себя все услуги, которые она есть.

+0

Я пробовал 'print (peripheralArray [0] .services)' и результаты по-прежнему равны нулю? – user3533049

Смежные вопросы