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

时间秒杀一切 提交于 2019-11-30 04:37:30

问题


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)
}

回答1:


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



来源:https://stackoverflow.com/questions/28463453/how-to-read-and-write-data-to-a-text-file-in-swift-using-playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!