-1
Output:    
({
    "Client Characteristic Configuration" = <41424344 45463132 31323334 35363738 45324441>;
})

Code : 
print("localName4", localName4)

if (localName4 != nil) {
    print("exists")

    if localName4 is Dictionary<AnyHashable,Any> {
        print("Yes, it's a Dictionary")

        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: localName4 as! Data, options: []) as? NSDictionary {
                print(jsonResult)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

I am trying get value <41424344 45463132 31323334 35363738 45324441> from result. When I try to parse the value getting exception:

Could not cast value of type 'NSDictionaryM' to 'NSData'

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
arun
  • 1
  • 6
  • 1
    What are you trying to archive? `localName4` is a dictionary already and you're trying to cast the dict to `Data` and then through JSONSerialization back to a Dictionary? – Lukas Würzburger Mar 13 '19 at 08:54
  • i am trying get <41424344 45463132 31323334 35363738 45324441> value – arun Mar 13 '19 at 08:55
  • What's "Output" exactly? From which print is it from? – Larme Mar 13 '19 at 09:37
  • func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){ let localName4 = advertisementData[CBAdvertisementDataServiceDataKey] } – arun Mar 13 '19 at 09:41
  • `localName4` is a `(NS)Data` object, not a `(NS)Dictionary`. That's expected behaviour (It's in the doc of `CBAdvertisementDataServiceDataKey`). I don't understand what you want (why JSON?)? Your code doesn't make sense. – Larme Mar 13 '19 at 13:01
  • Please use this https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift with `localName4` which is a `Data` object. – Larme Mar 13 '19 at 15:03

1 Answers1

0

There is no need to cast it to Data and serialize it back to a Dictionary. To access values from dictionaries just call them by the key:

let configuration = localName4["Client Characteristic Configuration"]

If the declaration type of localName4 is not [AnyHashable : Any] change the declaration if possible or cast it like this:

if let dict = localName4 as? [AnyHashable : Any] {
    let configuration = dict["Client Characteristic Configuration"]
    ...
}
Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75