2

I'm having a little bit of trouble. I'm translating my App to native Swift Language. I was using AS3. What I want to accomplish is to read a file in binary mode. A snippet of what I want accomplish is this:

ba:FileStream
ba.open(someFile, readMode)
ba.endian = "littleEndian"
ba.position = 128
ba.readMultiByte(4, someVariableHere)
halfer
  • 19,824
  • 17
  • 99
  • 186
  • possible duplicate of [Read and write data from text file](http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file) – Subhash Dike Sep 17 '15 at 14:45

1 Answers1

2

NSData is the class you are looking for.

do {
    let path = "apath"
    let data = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe)
    let buffer: UInt32 = 0
    data.getBytes(&buffer, range: NSRange(location: 128,length: 4))
}
catch error {
    print(error)
}

NSData documentation. NSData Class Reference

Mr Beardsley
  • 3,743
  • 22
  • 28
  • Hmm... I like it. Two questions. 1 How do I set the endianness? 2 I was looking through the web, and I found NSFileHandle. Which do u think is better? –  Sep 17 '15 at 16:10
  • Forgot to say: Thanks! –  Sep 17 '15 at 16:13
  • The UInt types in swift have an initializer that can take different endian values. You can use this fact to convert to whatever endianness you desire. In this case you could say let value = UInt32(littleEndian: buffer) – Mr Beardsley Sep 17 '15 at 16:16