[英]Swift: Creating a csv file in Documents Directory
I am creating a registration form application.我正在创建一个注册表单应用程序。 The registration form data will be saved in a CSV file.注册表单数据将保存在 CSV 文件中。 I need to create a csv file in the documents directory and be able to write to it.我需要在文档目录中创建一个 csv 文件并能够写入它。 I'm pretty new to Swift so I'm having a bit of trouble.我对 Swift 很陌生,所以我遇到了一些麻烦。 This is what I've got so far.这是我到目前为止所得到的。
var fileManager = NSFileManager.defaultManager()
var fileHandle: NSFileHandle
@IBAction func submitForm(sender: AnyObject) {
mySingleton.filename = mySingleton.filename + ".csv"
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let filePath = documentsPath + mySingleton.filename
if !fileManager.fileExistsAtPath(mySingleton.filename) {
fileManager.createFileAtPath(filePath, contents: nil, attributes: nil)
fileHandle = ...
}
}
Obviously the code I'm having trouble with is the FileHandle which is what allows to to modify the file.显然,我遇到问题的代码是 FileHandle,它允许修改文件。 In objective-c it would look something like this:在objective-c中它看起来像这样:
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];
Then obviously if I wanted to write to the file I could do something like this:显然,如果我想写入文件,我可以执行以下操作:
[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
So I'm really only struggling with that one part.所以我真的只在这一部分上挣扎。 Thanks for the help!谢谢您的帮助!
在 Swift 中, fileHandleForUpdatingAtPath
已经成为NSFileHandle
的初始化器,采用了避免重复的 Swift 命名约定,并采用了 Objective-C 方法名称的结尾,使其成为参数名称:
let fileHandle = NSFileHandle(forUpdatingAtPath: yourPath)
Make sure to add these two keys in info.plist and set them to " YES "确保在 info.plist 中添加这两个键并将它们设置为“ YES ”
Supports opening documents in place支持打开文件到位
Application supports iTunes file sharing应用程序支持iTunes文件共享
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.