【问题标题】:My app works fine in iOS12.4 but crashes in iOS 11我的应用在 iOS12.4 中运行良好,但在 iOS 11 中崩溃
【发布时间】: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


【解决方案1】:

任何时候你使用强制解包,当值不是你期望的值时,你正在寻找崩溃,所以避免它:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)
{
    if characteristic == rxCharacteristic
    {
        if let value = characteristic.value, let ASCIIstring = NSString(data: value, encoding: String.Encoding.utf8.rawValue)
        {
            characteristicASCIIValue = ASCIIstring
            print("Value Recieved: \((characteristicASCIIValue as String))")
            NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Notify"), object: nil)

        }
    }
}

【讨论】:

  • 谢谢您一百万次,您的回答是正确的,为我节省了数小时的研究时间。
  • 我很好奇为什么在 IOS 11 之前一切正常
  • 不确定,但我想说,在某些时候,您会从 CoreBluetooth 获得比以前更多的特性更新。其中一些没有实际值,这就是您的应用崩溃的原因。
猜你喜欢
  • 1970-01-01
  • 2014-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
相关资源
最近更新 更多