Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read and Write data to a text file in Swift using playground? [duplicate]

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)
}
like image 617
iamprem Avatar asked Feb 11 '15 20:02

iamprem


People also ask

How do I create and write to a file in Swift?

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.

How do I read a text file in Swift?

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.


1 Answers

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

like image 191
iamprem Avatar answered Sep 22 '22 06:09

iamprem