我是Swift新手,花了几天时间搜索stackoverflow,并在Google上找到了一个工作示例,将数据附加到csv / text文件中。有几个示例/质量检查,但我找不到确切的解决方案。最初的问题是系统无法在iPhone中找到本地文件。然后我发现在创建文件路径和最后附加值时出错。
创建一个文件名:
let fileName = "file"
查找文档目录的URL:
let DocumentDirURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
附加文件名和扩展名以创建绝对文件路径:
let fileURL = DocumentDirURL.URLByAppendingPathComponent(fileName).URLByAppendingPathExtension("csv")
使用NSFileHandle打开文件:
let file: NSFileHandle? = NSFileHandle(forUpdatingAtPath: fileURL.path!)
在文件末尾写入数据:
if file == nil {
NSLog("File open failed")
} else {
// assuming data contains contents to be written
let fileData = data.dataUsingEncoding(NSUTF8StringEncoding)
// seek to end of the file to append at the end of the file.
file?.seekToEndOfFile()
file?.writeData(fileData!)
file?.closeFile()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句