0

I have a string that looks like this:

ID3\x04\x00\x00\x00\x00\x00#TSSE\x00\x00\x00\x0f\x00\x00\x03Lavf57.71.100\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xf3\xc4\x00\x1a\xa2\x95\xf8\x15X\x10\x00\x16\xa0V\x18\xbb\x18\x84\x99i\x96|\xc60P\xdc\xe5\x03\xf1\xe6p\xe2Y}\xdc\xb8\xbe=\xfd\xe7OOo:\x10\x84S\x9es\xd0\x84#|\xe79\xce\xdf\xf4!\x1aw\xa9\xces\xd1\xa4$\xe79\xdf\xc8\xdf\xces\xfc\x84!\t\x90\x8d\xa9\xe8s\xd0\x8d\xff\xffS ...

How can I convert this into Data in swift?

I have tried using str as! Data but that just throws an error

The string is coming as one of the return values to a post request to a server of mine

Code

Alamofire.request(serverURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
            let responseData = (response.result.value! as! [String: Any])
            var audio = responseData["audio"]!
}

2 Answers2

1

The Alamofire docs say response.result should be serialized JSON. Do you mean to access the data via response.data?

if let json = response.result.value {
    print("JSON: \(json)") // serialized json response
}

if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
    print("Data: \(utf8Text)") // original server data as UTF8 string
}
abdulajet
  • 148
  • 7
0

The string you are providing is MP3 metadata and I'm guessing part of a larger MP3 file. Assuming you are unable to retrieve by downloading the file directly to your machine or using a remote URL, then you can convert the text string to data in the following way:

let data = str.data(using: .utf8)

Note: This returns an optional, so you need to handle that.

sketchyTech
  • 5,746
  • 1
  • 33
  • 56