繁体   English   中英

Swift:在文档目录中创建一个 csv 文件

[英]Swift: Creating a csv file in Documents Directory

我正在创建一个注册表单应用程序。 注册表单数据将保存在 CSV 文件中。 我需要在文档目录中创建一个 csv 文件并能够写入它。 我对 Swift 很陌生,所以我遇到了一些麻烦。 这是我到目前为止所得到的。

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 = ...
    }

}

显然,我遇到问题的代码是 FileHandle,它允许修改文件。 在objective-c中它看起来像这样:

fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];

显然,如果我想写入文件,我可以执行以下操作:

[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

所以我真的只在这一部分上挣扎。 谢谢您的帮助!

在 Swift 中, fileHandleForUpdatingAtPath已经成为NSFileHandle的初始化器,采用了避免重复的 Swift 命名约定,并采用了 Objective-C 方法名称的结尾,使其成为参数名称:

let fileHandle = NSFileHandle(forUpdatingAtPath: yourPath)

确保在 info.plist 中添加这两个键并将它们设置为“ YES

支持打开文件到位

应用程序支持iTunes文件共享

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM