1

I am using this answer to log messages in my app.

import Foundation

class Log: TextOutputStream {

    func write(_ string: String) {
        let fm = FileManager.default
        let log = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("log.txt")

        if let handle = try? FileHandle(forWritingTo: log) {
            handle.seekToEndOfFile()
            handle.write(string.data(using: .utf8)!)
            handle.closeFile()
        } else {
            do {
                try string.data(using: .utf8)?.write(to: log)
            } catch {
                print(error)
            }
        }
    }
    static var log: Log = Log()
    private init() {}
}

Used as follows using the Singleton pattern,

print("\(#function) Test Log", to: &Log.log)

This would append the String to the log.txt file. I cannot see the file being created in the Files.app and it doesn't produce an error either. If I print the path of the file where it's being saved it shows,

file:///var/mobile/Containers/Data/Application/00EBA5E5-7132-495E-B90E-E6CF32BA3EA7/Documents/

Where should it be saved? Do I have to do any prior setup? I can't seem to make this work. Do I have to do do something before to create the folder? Nothing shows up in the Files.app.

EDIT: I am not using the Simulator, I need to use a real device.

javierdemartin
  • 595
  • 6
  • 24

1 Answers1

1

Okay I got confused and I totally forgot this document is not supposed to show up in the Files.app. It's stored inside the app's container. If you want to share it from the documents sheet and send it to another device via AirDrop or whatever add this action to trigger when you tap a button intended to share the document.

let fm = FileManager.default
let fileUrl = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("log.txt")

var filesToShare = [Any]()

filesToShare.append(fileUrl)

let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)

self.present(activityViewController, animated: true, completion: nil)
javierdemartin
  • 595
  • 6
  • 24