0

I'm trying to display a .log file in a textview but can't seem to access the filepath properly. When I do it returns nil. I'm using a pod called "SwiftyBeaver" to do the logging. This is what the fileURL looks like:

file:///var/mobile/Containers/Data/Application/5C92E3E6-9E45-4869-9142-AB9E70EE4FCC/Library/Caches/swiftybeaver.log

This is the function I'm using to turn the .log into a string so I can display it in a textView

private func loadTextWithFileName(_ fileName: String) -> String? {
    guard let path = Bundle.main.path(forResource: fileName, ofType: "log"),
        let contents = try? String(contentsOfFile: path) else {return nil}
    return contents
}

This is how I'm displaying the text to the textView

self.loggingTextView.text = self.loadTextWithFileName(self.file.logFileURL!.absoluteString)

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92
  • because of you put the full URL of the log file (not file name) to your function. I think you should change tie loadTextWithFileName function to loadTextFromPath – Quoc Nguyen Sep 19 '19 at 00:24

1 Answers1

0

The method that you are using Bundle.main.path() is mainly to search for files in your Bundle.

But it seems your log file is going to be in your Cache directory.

Here is how you can look for a file in your Cache directory of your app

private func loadTextWithFileName(_ fileName: String) -> String? {
        if let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first {
            let fileURL = dir.appendingPathComponent(fileName)
            guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else {
                return nil
            }
            return text
        }
        return nil
    }

You can add a catch block to your try case to check what the error is, in case you don't get the log file details.

AjinkyaSharma
  • 1,870
  • 1
  • 16
  • 26