-1

I am creating a binary file using few c libraries and saving the file in documents folder of app in iOS. But when i try to read it its not reading. I am using the following code to read.

let fileData = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.mappedIfSafe) as Data

But this goes always into catch block.

nuteron
  • 531
  • 2
  • 8
  • 26

2 Answers2

0

You must retrieve your Document folder first and then get the content of document.

func readDocument(file:String) -> NSData{
        var vreturn:NSData
        if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true){
            let dir = dirs[0] //documents directory
            let path = dir.stringByAppendingString(file);
            //reading
            vreturn = (try? NSData(contentsOfFile: path)) ?? NSData()
        }
        return vreturn
    }

I'm using this to get String content but it seems to work the same way using NSData. Simple way to read local file using Swift?

Robin Delaporte
  • 575
  • 5
  • 15
-1
do {
    let videoData = try Data(contentsOf: avsset.url)
    print(videoData.count)
} catch let err {
    print("Error:", err)
}

you must catch error...

  • 2
    Since it's specified that it `always goes into catch block`, I assume there is one.. – Sti Jul 05 '17 at 07:52
  • File was not getting created due to a code change, thanks for pointing out the silly mistake :) – nuteron Jul 05 '17 at 11:24