简体   繁体   English

如何从Swift中的蓝牙特性中从NSData获取NSDictionary

[英]How to get NSDictionary from NSData out of bluetooth characteristic in Swift

I try to get NSDictionary from NSData of bluetooth characteristic but I got error message, "NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive". 我尝试从具有蓝牙特性的NSData获取NSDictionary,但收到错误消息“ NSKeyedUnarchiver initForReadingWithData:]:不可理解的档案”。

peripheralManager send NSDictionary like this to Central. 外周管理器将这样的NSDictionary发送到Central。

func peripheralManager(peripheral: CBPeripheralManager!, didReceiveReadRequest request: CBATTRequest!) {
    var responseDictonary: Dictionary = [
        "id" : 11111,
        "name" : "hoge"
    ]
    request.value = NSKeyedArchiver.archivedDataWithRootObject(responseDictonary)
    peripheralManager.respondToRequest(request, withResult: CBATTError.Success)
}

CentralManager recieve peripheral like this. CentralManager这样接收外围设备。

func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
    if (error != nil) {
        return
    }
    if characteristic.UUID == BLECharacteristicUUID {
        let data : NSData = characteristic.value
        if let recieveDictonary = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSDictionary {
            var id = recieveDictonary["id"] as Int
            var name = recieveDictonary["name"] as String
            Tracker.sharedInstance.debug("\(id) \(name)")
        }
    }
}

Do you have any solutions? 你有什么解决方案?

Try doing the following it might help you find the root cause. 请尝试执行以下操作,这可能有助于您找到根本原因。

  1. Just try to unarchive immediately after you archive in the first method, It will help you find if there is any issue while archiving itself. 使用第一种方法存档后,只需尝试立即取消存档,它将帮助您查找在存档时是否存在任何问题。 (your archiving code looks fine still make sure its working properly) (您的归档代码看起来还不错,请确保其正常运行)

  2. check for a nil value for "data" in the second method. 在第二种方法中检查“数据”的零值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM