How to Read and Write Data to a Text File in Swift Using Playground

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

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

How can I read a file in a swift playground

This works for me. The only thing I changed was to be explicit about the file name (which is implied in your example) - perhaps you have a typo in the off-screen definition of the "file" variable?

let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String]

let file = "trial.txt" // My change to your code - yours is presumably set off-screen
if let directories = dirs {
let dir = directories[0]; //documents directory
let path = dir.stringByAppendingPathComponent(file);

//read
let content = NSString(contentsOfFile: path, usedEncoding: nil, error: nil)
// works...
}

Update Swift 4.2

As @raistlin points out, this would now be

let dirs = NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true)

or, more tersely:

let dirs = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask, true)

Read and write a String from text file

For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

Swift 3.x - 5.x

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

let fileURL = dir.appendingPathComponent(file)

//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}

//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}

Swift 2.2

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}

//reading
do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}

Swift 1.x

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file);
let text = "some text"

//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

How writeToFile in a .playground?

modifying files in the main bundle doesn't appear to be possible, see earlier question. What you can do is to save to the sandboxed application folders, the URLs for which can be retrieved like this:

 func applicationDirectory(directory:NSSearchPathDirectory) -> NSURL? {

var appDirectory:String?
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(directory, NSSearchPathDomainMask.UserDomainMask, true);
if paths.count > 0 {
if let pathString = paths[0] as? String {
appDirectory = pathString
}
}
if let dD = appDirectory {
return NSURL(string:dD)
}
return nil
}



func applicationTemporaryDirectory() -> NSURL? {

if let tD = NSTemporaryDirectory() {
return NSURL(string:tD)
}

return nil

}

applicationTemporaryDirectory()

applicationDirectory(NSSearchPathDirectory.DocumentDirectory)

The urls will display in the righthand side of the playground, then simply copy and paste into the Finder -> Go -> Go to Folder dialogue box.

GitHub Repo: For a full working example see this GitHub repo.

How can I read a text file in the Resources directory using Swift 3 Playground?

Each Playground has its own Resources folder, and the actual path is hidden.

In Swift 3, you can get the files in the Resources folder by using Bundle:

let url = Bundle.main.url(forResource: "file", withExtension: "txt")

The path of this Bundle URL contains the path to the current Resources folder.


You can also avoid using Bundle and drag & drop the file from the Resources folder to the Playground itself, creating a file literal.

For example, type let url = and drop the file, from the Resources folder, into the Playground just after the = sign.

Text file to Array of Strings code is working in Playground but not in Xcode project

Please check that num.txt file is added in the Copy Bundle Resources, To check that go here ProjectModule->Build Phases->Copy Bundle Resources. For getting more idea check image.

Sample Image



Related Topics



Leave a reply



Submit