0

I am trying to read data.txt file with the help of playground. But it is returning nil. First I instantiated NSFileManager object. Than used the function fileExistsAtPath it is returning true. After instantiating NSFileHandle it is returning nil.

//: Playground - noun: a place where people can play

import UIKit



var defaultManager = NSFileManager.defaultManager()
if defaultManager.fileExistsAtPath("/Users/toshishakhand/Documents/data.txt") {
  print("File exists") // output : File Exists
} else {
  print("File not found")
}

var fileHandler: NSFileHandle ? = NSFileHandle(forReadingAtPath: "/Users/toshishakhand/Documents/data.txt")


if fileHandler == nil {
  print("File open failed") //output : nil
} else {
  print("File does not exist")
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Nishant Dongare
  • 549
  • 3
  • 16
  • 1
    the playground is sandboxed, you cannot access files outside of it. – luk2302 Jan 17 '16 at 17:53
  • 1
    Playground are sandboxed. You have to embed the file in the Playground. You can take example here: http://stackoverflow.com/questions/34616197/why-cant-i-extract-data-from-media-file-using-avurlasset-in-a-playground/34617041#34617041 – Eric Aya Jan 17 '16 at 17:53
  • 1
    http://stackoverflow.com/a/33404160/2303865 – Leo Dabus Jan 17 '16 at 17:54
  • 1
    put the file at your resource folder and use NSBundle URLForResource or pathForResource – Leo Dabus Jan 17 '16 at 17:56
  • @EricD Thanks for quick replay. I added the file to my resource folder. Now how to specify path? – Nishant Dongare Jan 17 '16 at 18:00
  • You can then drop the file *from* the Resources folder *to* the Playground in your code, it will automatically make an NSURL to the file. Otherwise you can use NSBundle. – Eric Aya Jan 17 '16 at 18:01
  • More details here: http://stackoverflow.com/a/31840630/2227743 for NSBundle. – Eric Aya Jan 17 '16 at 18:01
  • Thanks. I am not getting `NSFileManager` worked properly.Why it did't showed any error – Nishant Dongare Jan 17 '16 at 18:04
  • Oh sorry Nishant I didn't notice this comment of yours earlier. Is it working now? – Eric Aya Jan 17 '16 at 18:23
  • ya it is working fine. Thanks. But can you tell me why NSFileManger Logic is returning true i.e the file exist. It should also not work because Playground is sandboxed. :) – Nishant Dongare Jan 17 '16 at 18:37

0 Answers0