3

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???

Mysterious_android
  • 598
  • 2
  • 9
  • 32

2 Answers2

8

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
  • 968
  • 8
  • 19
0

To convert Data/NSData to an array of Integer

// here value is Data type which contain array of byte
let value = characteristic.value

let B0 = value[0]
let B1 = value[1]
let B2 = value[2]
let B3 = value[3]
let B4 = value[4]
let B5 = value[5]

// create a byte of array
let generationByteData: [UInt8] = [B0, B1, B2, B3, B4, B5]
print("generationByteData = \(generationByteData)")

// Result = generationByteData = [3, 17, 34, 0, 0, 0]
Yogesh Rathore
  • 147
  • 1
  • 7