0

I'm wondering how I can save the content of an int8 array to a file. I found that if the "actual content" represented by the int8 array is an String, then my code runs fine. 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).

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~

4
  • "int8 array is the raw data from a HTTP response (HTTP part is written in C)" Could I ask why you are doing that? It sounds like the Int8 is getting in your way. If you just let the system do the download, it will be NSData from the start, and you can just save it. Commented Jan 16, 2015 at 3:49
  • By the way, this should not be Int8 so I hope you don't really mean that. It should be UInt8. Raw data is an unsigned char[]. If you've been collecting this data as Int8, that could be the source of the trouble. Commented Jan 16, 2015 at 4:02
  • Thanks matt, yeah it should be UInt8 instead, my bad :-D . So how can i append an unsigned char array to another unsigned char array? Ive tried strcat but that doesnt seem to give me correct result? Thanks a lot~ Commented Jan 19, 2015 at 1:49
  • Sorry, that's above my pay grade. :) What I do is just use NSURLSession. The data comes in as NSData, I keep appending it to an NSMutableData, and there we are. In fact, if I use a download task, I don't have to collect the data; it just goes into a file and I save it off at the end. Commented Jan 19, 2015 at 2:54

1 Answer 1

3

Swift 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"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.