【问题标题】:Swift: Creating a csv file in Documents DirectorySwift:在文档目录中创建一个 csv 文件
【发布时间】:2016-04-26 22:37:58
【问题描述】:

我正在创建一个注册表单应用程序。注册表单数据将保存在 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];

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

【问题讨论】:

  • 我不明白你的问题是什么?你想把这个 Objective-C 翻译成 Swift 吗?
  • 基本上是的。不太清楚它是如何在 Swift 中编程的。
  • 你的“formData”对象是什么类型的?

标签: ios swift csv nsfilemanager nsfilehandle


【解决方案1】:

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

支持原地打开文档

应用程序支持 iTunes 文件共享

【讨论】:

    【解决方案2】:

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

    let fileHandle = NSFileHandle(forUpdatingAtPath: yourPath)
    

    【讨论】:

    • 啊好吧!所以它是用于更新AtPath!太感谢了。我一直在寻找永远啊哈
    猜你喜欢
    • 1970-01-01
    • 2013-08-06
    • 2015-12-23
    • 1970-01-01
    • 2020-10-06
    • 2014-09-21
    • 1970-01-01
    • 2014-04-26
    • 2017-11-10
    相关资源
    最近更新 更多