将文本输入保存到设备

时间:2018-05-02 04:39:09

标签: swift

我正在尝试创建一个视图,我可以在UITextField中输入文本并将其保存到设备中。我搜索过不同的地方,到目前为止,我在下面得到了这个,但我无法通过这个错误。有人可以帮忙吗?

  

使用未解析的标识符'yyyytoss'

import UIKit

class WritestoryVC: UIViewController, UITextViewDelegate {
    @IBOutlet weak var myStory : UITextView!

    @IBAction func saveImageToDocumentDirectory(_ chosenImage: UITextField) -> Void {
        let directoryPath =  NSHomeDirectory().appending("/Documents/")
        if !FileManager.default.fileExists(atPath: directoryPath) {
            do {
                try FileManager.default.createDirectory(at: NSURL.fileURL(withPath: directoryPath), withIntermediateDirectories: true, attributes: nil)
            } catch {
                print(error)
            }
        }
        let filename = NSDate().string(withDateFormatter: yyyytoss).appending(".rtf")
        let filepath = directoryPath.appending(filename)
        let url = NSURL.fileURL(withPath: filepath)
        do {
            try UITextField(chosenImage, 1.0)?.write(to: url, options: .atomic)
            return String.init("/Documents/\(filename)")

        } catch {
            print(error)
            print("file cant not be save at path \(filepath), with error : \(error)");
            return filepath
        }
    }
}

1 个答案:

答案 0 :(得分:0)

看看是否有帮助: -

同样在你定义yyyytoss常数的地方,它应该像“yyyy-MM-dd”

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 */}
}