I read through these SO links for the answer
1. Read a file/URL line-by-line in Swift
2. Read and write data from text file
Link 2 Provided me the solution but the problem is directory. It is by default Document directory of the current project.
So if i want to read a file from "/Users/Prem/Desktop/File.txt", what modification i should make to that code?
How to work with custom directory to read and write 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)
}
To create a text file in Swift, call createFile() function on the file manager object, and pass the file path and contents to the function.
To read a Text File in Swift, we can prepare the file url and then use String initializer init(contentsOf: url) that returns file content as a string.
After trying out for couple of days it is clear that,
We cannot access other than the project's self contained directories, if we try 'file handling' in playground. Because it is sandboxed
But from an xcode project, we can access any directory and perform read/write operations.
credits: @robMayoff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With