我在应用程序上工作,当我触摸iPhone上的按钮时,我需要添加一个新行。 我做了这一切,但每次写下我写的东西。
每次按下按钮保存时如何追加新行。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myAge: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// get the documents folder url
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func writeNow(sender: UIButton) {
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let fileDestinationUrl = documentDirectoryURL.URLByAppendingPathComponent("fileForIphoneAbdulla.txt")
var text = myAge.text
do {
try text!.writeToURL(fileDestinationUrl, atomically: true, encoding: NSUTF8StringEncoding)
print("file is saved succefully")
do {
let mytext = try String(contentsOfURL: fileDestinationUrl, encoding: NSUTF8StringEncoding)
print(mytext) // "some text\n"
} catch let error as NSError {
print("error loading from url \(fileDestinationUrl)")
print(error.localizedDescription)
}
} catch let error as NSError {
print("error writing to url \(fileDestinationUrl)")
print(error.localizedDescription)
}
}
}
答案 0 :(得分:0)
使用高级文件方法来编写整个文件。
要附加,您可以使用NSFileHandle。它有像seekToEndOfFile这样的方法将文件指针移动到结尾,然后使用writeData将数据添加到文件的末尾。
BTW,您的示例代码在Swift中,但您使用的是jquery标记。我假设你在Swift寻求帮助?