0

Here's the code:

let jsonData = NSData(contentsOfFile: "/Users/7stud/xcode_projects/iOS/my_json.json")

That code is in a playground, and I get nil for jsonData. I didn't type the path: I dragged the file from Finder to a Terminal window, which enters the full path of the file at the point of the cursor. Then I copied that absolute path and pasted it into my code--so no typo.

According to the docs:

NSData

+ dataWithContentsOfFile:

Creates and returns a data object by reading every byte from the file specified by a given path.

Declaration OBJECTIVE-C
+ (instancetype)dataWithContentsOfFile:(NSString *)path

Parameters
path | The absolute path of the file from which to read data.

Return Value
A data object by reading every byte from the file specified by path. Returns nil if the data object could not be created.

There's no Swift definition.

luk2302
  • 55,258
  • 23
  • 97
  • 137
7stud
  • 46,922
  • 14
  • 101
  • 127

1 Answers1

0

Faced the same issue and as a quick workaround I placed my file directly at the location returned by the NSFileManager and later accessed the file to read the contents.

Here is the snipped:

var fileManager = NSFileManager.defaultManager()
var path:String! = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
var data = fileManager.contentsAtPath(path+"/a.txt")
try NSString(data: data!, encoding: NSUTF8StringEncoding)

I placed my file a.txt at the path returned by NSSearchPathForDirectoriesInDomains method and was able to retrieve it in a string.

HAK
  • 2,023
  • 19
  • 26