Saving log to file line by line in iOS

I received a line of bluetooth data (from a Cycle Analyst computer) a few time a second. I put the data in an array and add some calculated one to it.


A typical usage of the app last a couple of hour but can be continu a few day in a row.

So I don't want to keep all this data in memory, I just need to log it to the file,

I would like to append those data to a file one line at the time

The file will be ascii string separated with tab.

The user will be able to export this file to use In other app.


I look UIDocument example from CS193P of Stanford and I am not sure it will work for me.

I could not find anything on the Append i need to do.


Do you have a direction I should look to for a solution.

Where in the doc can I find information on that ?

Keep it in memory until it exceeds a large size then add it to a file. You only need to do that every few hours and you can just read the entire file, append it and store it. Look at NSFileManager methods. No need to add a single line to any file.

oh, i found the interval. I receive one line of data about every second but like you said I can easily wait a while before writing


Thank you, I looked at FileManager


I am very bad at reading Apple Documentation -> There should be a tutorial for me, on this task alone :-)

but I dont see anything in file manager on how to write to a file. A search on Write on the page give me this line

isWritableFile(atPath: String) -> Bool


I did find with the help of DuckDuckGo about FileHandle and was able to build a small

playground where i tested it, and it seems to work


I am will continu to read on FileManager


import UIKit
var currentPath = FileManager.default.currentDirectoryPath
print("Current path: \(currentPath)")
currentPath = currentPath + "/myFile.txt"

let path = URL(fileURLWithPath: currentPath)
let str = "test string\n"

do {
    try str.write(to: path, atomically: true, encoding:
        .ascii)
    print("Worked !!")
}
catch let error {
    print("Failed: \(error)")
}

let myFileHandle = FileHandle(forUpdatingAtPath: currentPath)
myFileHandle?.seekToEndOfFile()
let mydata = str.data(using: String.Encoding.utf8)
myFileHandle?.write(mydata!)
myFileHandle?.write(mydata!)

let mydata2 = "Franco".data(using: String.Encoding.utf8)
myFileHandle?.write(mydata2!)
myFileHandle?.closeFile()

// result in myFile.txt 
//test string
//test string
//test string
//Franco

Unfortunately I don’t do Swift. I’d be glad to give you code in Objective-C next week when I return from vacation.

Ohh, i just found a Guide from Apple

https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/DocumentBasedAppPGiOS/CreateCustomDocument/CreateCustomDocument.html#//apple_ref/doc/uid/TP40011149-CH8-SW1


i think i can do my file with UIDocument which would give me a lot of almost free stuff like icloud sync.

i will try to looked into that

Saving log to file line by line in iOS
 
 
Q