就像SO上的答案一样,我试图附加一个文本文件。我的代码是这样的:
if countdownTimer > 0 {
let dir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first!
let fileurl = dir.URLByAppendingPathComponent(fileName)
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let hour = calendar.component(.Hour, fromDate: date)
let minutes = calendar.component(.Minute, fromDate: date)
let seconds = calendar.component(.Second, fromDate: date)
newLine = "\(hour):\(minutes):\(seconds),\(someValue),\(someValue)\n"
let data = newLine.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if NSFileManager.defaultManager().fileExistsAtPath(fileurl!.path!) {
do {
let fileHandle = try NSFileHandle(forWritingToURL: fileurl!)
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
fileHandle.closeFile()
} catch {
print("Can't open fileHandle \(error)")
}
} else {
}
countdownTimer -= 1
}
我的实现的不同之处在于我在单独的事件上创建文件(并且我确定文件在附加之前存在)并且附加文本文件在每秒循环的计时器内。我究竟做错了什么?感谢。
答案 0 :(得分:1)
我编写的代码可以帮助您了解可能出错的地方。
首先创建Error
类型和文件名,我们将记录我们的信息。
let file = "logger1.txt"
enum Throwing: Error {
case impossibleToWrite
case impossibleToRead
}
比writeToFile
和readFromFile
两个函数。
func writeToFile(file:String, log: String) throws {
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent(file)
do {
let writer = try FileHandle(forWritingTo: path)
writer.seekToEndOfFile()
writer.write(log.data(using: String.Encoding.utf8)!)
writer.closeFile()
}
catch {
throw Throwing.impossibleToWrite
}
}
}
func readFromFile(file:String) throws {
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent(file)
do {
let text = try String(contentsOf: path, encoding: String.Encoding.utf8)
print(text)
}
catch {
throw Throwing.impossibleToRead
}
}
}
比将循环并使用日期创建日志的小循环。用法试试!是不好的做法,但为了测试目的,这是可以的。
func logTimeInLoop() {
for _ in 0..<10 {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
let text = formatter.string(from: Date()) + "\n"
try! writeToFile(file: file, log: text)
}
try! readFromFile(file: file)
}
这是文件中数据的输出。