2016-08-24 54 views
0

我已經成功的iOS應用程序連接到我的BLE HM-10設備和發送它的特性的字符串。然而,我不知道如何使用@IBAction函數按下按鈕後發送字符串。將數據寫入特性的按鈕點擊 - 斯威夫特

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error:NSError?) 
{ 
    print("Found \(service.characteristics!.count) characteristics!: \(service.characteristics)") 
    _peripheral = peripheral 
    _characteristics = service.characteristics 
    let string = "off" 

    let data = string.dataUsingEncoding(NSUTF8StringEncoding) 


    for characteristic in service.characteristics as [CBCharacteristic]! 
    { 

     if(characteristic.UUID.UUIDString == "FFE1") 
     { 
      print("sending data") 
      peripheral.writeValue(data!, forCharacteristic: characteristic,type: CBCharacteristicWriteType.WithoutResponse) 
     } 
    } 

} 

@IBAction func onButtonTouch(sender: UIButton) 
{ 
    let string = "on" 

    let data = string.dataUsingEncoding(NSUTF8StringEncoding) 

    _peripheral.writeValue(data!, forCharacteristic: _characteristics, type: CBCharacteristicWriteType.WithoutResponse) 

} 

當我把這個代碼成它不作爲工作底部顯示的@IBAction功能「特徵」是一個未解決的識別符。有沒有辦法將它鏈接到外設功能?我在Swift編碼方面比較新,所以任何幫助都會非常感謝。謝謝。

+0

您需要保存的特點。在'onButtonTouch(sender:)'它沒有聲明! – Larme

+0

爲什麼不能將'peripheral'和'characteristic'設置爲全局變量? – D4ttatraya

+0

@Larme感謝您快速回答。真的很抱歉聽起來像這樣的新手,但你能向我解釋如何做到這一點?謝謝! – DanB

回答

0
class viewController: UIViewController { 

    var _peripheral: CBPeripheral? 
    var _characteristics: [CBCharacteristic]? 

    func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error:NSError?) 
    { 
    print("Found \(service.characteristics!.count) characteristics!: \(service.characteristics)") 
    _peripheral = peripheral 
    _characteristics = service.characteristics 
    let string = "off" 

    let data = string.dataUsingEncoding(NSUTF8StringEncoding) 


     for characteristic in service.characteristics as [CBCharacteristic]! 
     { 

      if(characteristic.UUID.UUIDString == "FFE1") 
      { 
       print("sending data") 
       peripheral.writeValue(data!, forCharacteristic: characteristic,type: CBCharacteristicWriteType.WithoutResponse) 
      } 
     } 

    } 

    @IBAction func onButtonTouch(sender: UIButton) 
    { 
    let string = "on" 

    let data = string.dataUsingEncoding(NSUTF8StringEncoding) 

    let characteristic = //get right on out of _characteristics! array 
    _peripheral!.writeValue(data!, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithoutResponse) 

    } 
} 
+0

這固定我與特性標識符問題現在得到關於viewController錯誤說「類viewController沒有初始化器」和CharacteristicsDataType/Class?一節說「連續的聲明在一條線上必須分開」。對不起是一個痛苦。 – DanB

+0

@DanB什麼錯誤? '視圖控制器'我只是舉了一個例子。顯示包含您的代碼的整個班級。 – D4ttatraya

+0

@DanB你有與'[CBCharacteristic]'實際數據類型來代替'CharacteristicsDataType/Class'。檢查已更新的答案 – D4ttatraya