Thursday, February 21, 2019

Swift write file

We want to save a text string in to user phone. Copy in to viewDidLoad.
let file = "write.txt"
let text = "This is example text"
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
                    let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)       
                    do {
                        try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
                    }
                    catch {/* error handling here */}
                }
To check if data write or not, we read file and set to a textview.
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
        let path = documentsPath.stringByAppendingPathComponent("write.txt")
        var read : String = ""
     do {
            try read = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
            gi.text = read
            gi.font = UIFont.italicSystemFontOfSize(17)
            gi.textColor = UIColor.blueColor()
            gi.textAlignment = NSTextAlignment.Center
             }
        catch let error as NSError {
            // print("ERROR : reading from file \(fileName) : \(error.localizedDescription)")
        }
Run to see result.

When practical, we use to write to lines, new line will below old line, that easy to read for use.
This function below write data in to new line.
func write(content: String, _ fileName: String) {
     let contentToAppend = content+"\n"
     let filePath = NSHomeDirectory() + "/Documents/" + fileName
   if let fileHandle = NSFileHandle(forWritingAtPath: filePath) {
 fileHandle.seekToEndOfFile()
fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!)
   }
        else {    
            do {
                try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
            } catch {
                print("Error creating \(filePath)")
            }
        }

    }

No comments:

Post a Comment