简体   繁体   English

如何在Swift中将int8数组保存到文件

[英]How to save an int8 array to file in Swift

I'm wondering how I can save the content of an int8 array to a file. 我想知道如何将int8数组的内容保存到文件中。 I found that if the "actual content" represented by the int8 array is an String, then my code runs fine. 我发现如果int8数组表示的“实际内容”是字符串,那么我的代码运行良好。 But if the content is actually an image, the saved file cannot be opened (says it's damaged). 但是,如果内容实际上是图像,则无法打开已保存的文件(例如已损坏)。

I tried to open the image using the text editor and found that the content is different from what was expected (I have the "good" image which can be used for comparison). 我尝试使用文本编辑器打开图像,发现内容与预期的有所不同(我有“好”图像可用于比较)。 I'm wondering if it's something to do with encoding ? 我想知道这是否与编码有关?

The int8 array is the raw data from a HTTP response (HTTP part is written in C). int8数组是来自HTTP响应的原始数据(HTTP部分用C编写)。

I'm not sure if i'm on the right track, any ideas ? 我不确定我是否走对了,有什么想法吗?

var response: NSData! = NSData(bytes: myArray, length: contentLength)
var writeOutput: Bool = response.writeToURL(thePath, atomically: false)

How can I modify the code so that it saves the content properly no matter if the content is text or image. 我如何修改代码,以便无论内容是文本还是图像,它都能正确保存内容。

Thanks a lot~ 非常感谢〜

Swift 3: 斯威夫特3:

let myArray:[Int8] = [ 0x4d, 0x2a, 0x41, 0x2a, 0x53, 0x2a, 0x48]
let pointer = UnsafeBufferPointer(start:myArray, count:myArray.count)
let data = Data(buffer:pointer)
try! data.write(to: URL(fileURLWithPath: "myFile.data"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM