【发布时间】:2020-02-24 02:01:24
【问题描述】:
我的应用在 iOS 12.4 中运行良好,但在 iOS 11 中崩溃。
以下代码在 iOS 11 中返回 nil。
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)
{
if characteristic == rxCharacteristic
{
if let ASCIIstring = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue)
{
characteristicASCIIValue = ASCIIstring
print("Value Recieved: \((characteristicASCIIValue as String))")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Notify"), object: nil)
}
}
}
【问题讨论】:
-
请edit您的问题更具体。 `nil 到底是什么?哪条线?哪个值?
-
不要强制展开。不要在 Swift 中使用
NSString。您使用if let...,但通过强制解开characteristic.value来撤消它。使用类似if let data=characteristic.value, let ASCII = String(data:data, encoding:.utf8) {的东西。另请注意,不同的 iOS 设备具有不同的 BLE MTU,在旧设备上只有 20 个字节,因此您可能需要处理传入字符串的分段和重组。
标签: ios swift core-bluetooth