How to read and write data to a text file in Swift using the playground?

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) } 
+6
source share
1 answer

After a couple of days, it’s clear that

We cannot access other offline project directories if we try to β€œprocess files” on the playground. Because it's a sandbox

But from the xcode project, we can access any directory and perform read / write operations.

credits: @robMayoff

+7
source

Source: https://habr.com/ru/post/982344/


All Articles