2

I have a Data that I received from a characteristic in a Service

let value = characteristic.value

This "value" of type Data .

In this value there are 20 bytes that contains 5 numbers of type Uint8 or int 1,2,3,4,5.

How do I get these Integer numbers from this Data value???

1 Answers1

7

1) If you have stingyfy josn(Come from API response) then you can convert to directly to [Int] using..

do {
    let IntArray = try JSONSerialization.jsonObject(with: dataObject, options:[])
    print(IntArray)
    // print: 1,2,3,4,5,6,7,8,9
}catch{
    print("Error in Serialization")
}

2) If you want [Int] and Data conversion then use this

You can create Data from [Int] using 'archivedData' and back to '[Int]' using unarchiveObject.

var listOfInt : [Int] = [1,2,3,4,5,6,7,8,9]

let dataObject = NSKeyedArchiver.archivedData(withRootObject: listOfInt)

if let objects = NSKeyedUnarchiver.unarchiveObject(with: dataObject) as? [Int] {
    print(objects)
    // print: 1,2,3,4,5,6,7,8,9
} else {
    print("Error while unarchiveObject")
}
ERbittuu
  • 922
  • 8
  • 19