iOS Swift - CoreBluetooth 无法发送数据

标签 ios iphone swift xcode core-bluetooth

我正在尝试使用我实现的 slider 发送我的数据,但我无法这样做。但是我要接收数据。

我正在使用两个写入/输出数据“writeData”和“writeValue”的函数。

这是完整的项目 https://github.com/brandonmaiwin/Raspberrypi-bluetooth

 //
 //  speed2ViewController.swift
 //  Raspberrypi
 //
 //  Created by Brandon Mai Nguyen on 10/14/18.
 //  Copyright © 2018 Brandon Mai Nguyen. All rights reserved.
 //

 import UIKit
 import CoreBluetooth

 class speedtwoViewController: UIViewController, CBPeripheralManagerDelegate, UITextViewDelegate, UITextFieldDelegate
{
//Initialize values
@IBOutlet weak var baseTextView: UITextView!
@IBOutlet weak var Speedometerdisplay: UILabel!
@IBOutlet weak var sliderOutlet: UISlider!
//Data in and Data out
@objc var peripheralManager: CBPeripheralManager?
@objc var peripheral: CBPeripheral!
private var consoleAsciiText:NSAttributedString? = NSAttributedString(string: "")

override func viewDidLoad()
{
    super.viewDidLoad()
    //Create and start the peripheral manager
    peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    //-Notification for updating the text view with incoming text
    updateIncomingData()
}

//this function recieves data from the arudino and displays it.
@objc func updateIncomingData ()
{
    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "Notify"), object: nil , queue: nil)
    {
        notification in
        let appendString = "\n"
        let myFont = UIFont(name: "Helvetica Neue", size: 15.0)
        let myAttributes2 = [NSAttributedStringKey.font: myFont!, NSAttributedStringKey.foregroundColor: UIColor.red]
        let attribString = NSAttributedString(string: "[Incoming]: " + (characteristicASCIIValue as String) + appendString, attributes: myAttributes2)
        let newAsciiText = NSMutableAttributedString(attributedString: self.consoleAsciiText!)
        self.baseTextView.attributedText = NSAttributedString(string: characteristicASCIIValue as String , attributes: myAttributes2)

        newAsciiText.append(attribString)

        self.consoleAsciiText = newAsciiText
        self.baseTextView.attributedText = self.consoleAsciiText
    }
}

//this function sends data out
func outgoingData (data: String)
{
    let appendString = "\n"

    let inputText = String(data)

    let myFont = UIFont(name: "Helvetica Neue", size: 15.0)
    let myAttributes1 = [NSAttributedStringKey.font: myFont!, NSAttributedStringKey.foregroundColor: UIColor.blue]

    writeValue(data: inputText)

    let attribString = NSAttributedString(string: "[Outgoing]: " + inputText + appendString, attributes: myAttributes1)
    let newAsciiText = NSMutableAttributedString(attributedString: self.consoleAsciiText!)
    newAsciiText.append(attribString)

    consoleAsciiText = newAsciiText
    baseTextView.attributedText = consoleAsciiText

}

// Write functions
func writeValue(data: String)
{
    let data = data
    let valueString = (data as NSString).data(using: String.Encoding.utf8.rawValue)
    //change the "data" to valueString
    if let blePeripheral = blePeripheral
    {
        if let txCharacteristic = txCharacteristic
        {
            blePeripheral.writeValue(valueString!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)
        }
    }
}

//slider changes the speed and sends a integer value
@IBAction func Speed(_ sender: UISlider)
{

    Speedometerdisplay.text = String(Int(sliderOutlet.value))

    outgoingData(data: String(Int(sliderOutlet.value)))


    writeCharacteristic(val: Int8(Int(sliderOutlet.value)))
}

//send the slider value out using "writeCharacteristic"
func writeCharacteristic(val: Int8)
{
    var val = val
    let ns = NSData(bytes: &val, length: MemoryLayout<Int8>.size)
    blePeripheral?.writeValue(ns as Data, for: txCharacteristic!, type: CBCharacteristicWriteType.withResponse)
}



//prints out an error if not detected
func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?)
{
    if let error = error
    {
        print("\(error)")
        return
    }
}

//Prints a message stating that the device is on and connected
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager)
{
    if peripheral.state == .poweredOn
    {
        return
    }
    print("Peripheral manager is running")
}

//Check when someone subscribe to our characteristic, start sending the data
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic)
{
    print("Device subscribe to characteristic")
}

}

最佳答案

由于 UISlider 的 UIControlEventValueChanged 非常敏感,它可能会产生蓝牙开销。你可以试试这个:

slider.isContinuous = false

只有在编辑结束后才会发送新值。如果你想要一些连续且不太敏感的东西,你可以在 @IBAction func Speed(_ sender: UISlider) 中处理它。

关于iOS Swift - CoreBluetooth 无法发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52885371/

相关文章:

ios - 更新 Xcode 12.5 和 ios 14.5 时出现抖动问题

ios - 如何根据键盘高度快速更新 y 的文本输入位置

ios - 在 swift : Sum variable not retaining value? 中的 for 循环中对对象数组的元素求和

swift - 如何限制用户文本输入并禁用 JSQMessagesViewController 中的发送按钮

objective-c - UIStutsbar SetHidden 在 ios 5 中不起作用?

ios - 如何单击控制中心中的按钮?

android - 在 flutter 中如何使带有平移手势的内部小部件不会与PageView冲突

ios - CoreData 一次又一次地向数据库中添加数据

iphone - 暂停申请

iphone - 我可以在应用程序再次激活后重新启动它吗?