I read these SO links for an answer
1. Read file / URL line by line in Swift
2. Reading and writing data from a text file
Link 2 Provided me with a solution, but the problem is the directory. This is the default directory for the current project.
So, if I want to read the file from "/Users/Prem/Desktop/File.txt", what modification should I make to this code?
How to work with a custom directory for reading and writing data in a text file?
let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] if ((dirs) != nil) { var dir = dirs![0]; //documents directory //println(dir) //dir = "/Users/Prem/Desktop" ----> If i give this path, its not creating the file //Current Value in dir //dir ----> "/Users/Prem/Library/Containers/com.apple.dt.playground.stub.OSX.FileIO-2159807F-CC21-4545-AC34-AD9F9898796B/Data/Documents" let path = dir.stringByAppendingPathComponent("File.txt"); println(path) let text = "Rondom Text" //writing text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil); //reading let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) }
source share