2

I'm trying to get the value of advertisementData[CBAdvertisementDataManufacturerDataKey] to do an operation on it. What I need to do ?

I have already tried some solutions found on this forum like : Convert NSInlineData to Nstring in ios but this is in objective-c. I have converted it to swift but it didn't work

let manufacturerdata = advertisementData["kCBAdvDataManufacturerData"] as! NSData
print("value : \(manufacturerdata)")
let manufacturerdatastr = String(data: manufacturerdata as Data, encoding: .utf8)
print("data string  : \(manufacturerdatastr)")

I expect the value of manufacturerdata but the actual output is nil

timbre timbre
  • 12,648
  • 10
  • 46
  • 77
Fatih
  • 51
  • 8
  • 2
    It's not a UTF8 String, it's not a "word/sentence". If you want the same output, you might want that: https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift Also, use `advertisementData[CBAdvertisementDataManufacturerDataKey]` instead of `advertisementData["kCBAdvDataManufacturerData"]`. – Larme May 16 '19 at 16:31
  • WHat if you use `CBAdvertisementDataManufacturerDataKey` instead of `kCBAdvDataManufacturerData`? – timbre timbre May 16 '19 at 16:48
  • @Larme the problem is that I can print the value of 'advertisementData[CBAdvertisementDataManufacturerDataKey]' but I can't get the value of it in a variable – Fatih May 17 '19 at 06:17
  • @KirilS. I have tried both of CBAdvertisementDataManufacturerDataKey and "CBAdvertisementDataManufacturerDataKey" but it doesn't change anything – Fatih May 17 '19 at 06:18
  • Using `advertisementData[CBAdvertisementDataManufacturerDataKey]`doesn't fix your issue. It's a safer way to retrieve the value. As I said, the value is not UTF8 String valid, so you'll get nil doing `String(data: manufacturerdata as Data, encoding: .utf8)`. Question is seeing the output: `print("value : \(manufacturerdata)")`, what do you want? Did you look at the linked question? – Larme May 17 '19 at 09:00
  • @Larme what I wanted to do is to get the value in advertisementData[CBAdvertisementDataManufacturerDataKey] for example : "kCBAdvDataManufacturerData": <0fb2c231> I just wanted to get 0fb2c231 converted to decimal in a variable. – Fatih May 20 '19 at 06:38

1 Answers1

2

I have found a solution for my problem :

adData = advertisementData[CBAdvertisementDataManufacturerDataKey]
            let data : NSData = adData as! NSData
            var str1 : String = data.description
            str1 = str1.replacingOccurrences(of: "<", with: "")
            str1 = str1.replacingOccurrences(of: ">", with: "")
            if let value = Int(str1, radix: 16) {
                print(value)
                DataInt=value
            }

So I can get the value of advertisementData[CBAdvertisementDataManufacturerDataKey] with type int in decimal in the variable DataInt.

Hope it will be helpfull for you

Fatih
  • 51
  • 8