How to write Application Logs to File and get them

前端 未结 2 911
名媛妹妹
名媛妹妹 2020-12-29 13:11

I´m taking baby steps in iOS development and searching for a method to use logging in iOS.

I found these docs about logging with swift 3 : https://developer.apple.co

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 13:34

    Swift 3.0 version

    Create a new swift file "TextLog.swift" in your project

    import Foundation
    
    struct TextLog: TextOutputStream {
    
        /// Appends the given string to the stream.
        mutating func write(_ string: String) {
            let paths = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask)
            let documentDirectoryPath = paths.first!
            let log = documentDirectoryPath.appendingPathComponent("log.txt")
    
            do {
                let handle = try FileHandle(forWritingTo: log)
                handle.seekToEndOfFile()
                handle.write(string.data(using: .utf8)!)
                handle.closeFile()
            } catch {
                print(error.localizedDescription)
                do {
                    try string.data(using: .utf8)?.write(to: log)
                } catch {
                    print(error.localizedDescription)
                }
            }
    
        }
    
    }
    

    Initialize the logger at bottom in the AppDelegate.swift file

    var textLog = TextLog()
    

    Use it anywhere in the application like below

    textLog.write("hello")
    

提交回复
热议问题