字节串作为Swift 4中的数据

时间:2018-05-21 15:42:00

标签: swift string audio types byte

我有一个看起来像这样的字符串:

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

如何在swift中将其转换为数据?

我尝试使用str as! Data,但这只会引发错误

该字符串作为对我的服务器的发布请求的返回值之一

代码

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 个答案:

答案 0 :(得分:1)

Alamofire docs说response.result应该是序列化的JSON。您的意思是通过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
}

答案 1 :(得分:0)

您提供的字符串是MP3 metadata,我猜测更大的MP3文件的一部分。假设您无法通过downloading the file directly to your machine或使用远程URL进行检索,则可以通过以下方式将文本字符串转换为数据:

split

注意:这会返回一个可选项,因此您需要处理它。