简体   繁体   中英

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".

peripheralManager send NSDictionary like this to 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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