3

I want to write every print() content into a text file in Swift 3.0. It was working fine in Objective-C but not worked in Swift 3.0. I am using the code as below,

    func redirectLogToDocuments() {

    let docDirectory: NSString = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
    let logpath = docDirectory.appendingPathComponent("Logfile.txt")

    freopen(logpath.cString(using: String.Encoding.utf8)!, "a+", stdin)
    freopen(logpath.cString(using: String.Encoding.utf8)!, "a+", stdout)
    freopen(logpath.cString(using: String.Encoding.utf8)!, "a+", stderr)                
}

Please help me.

Gautam Sareriya
  • 1,833
  • 19
  • 30
  • Works for me (but compare https://stackoverflow.com/a/41680336/1187415). – What is the concrete problem? And you really want to redirect **stdin** to/from the same file? – Martin R Jul 18 '17 at 11:10

1 Answers1

6
 func redirectLogToDocuments() {
    let allPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = allPaths.first!
    let pathStringComponent = "/" + LoggingConstants.LogFileName + "." + LoggingConstants.LogFileType
    let pathForLog = (documentsDirectory as NSString).appending(pathStringComponent)
    freopen(pathForLog.cString(using: String.Encoding.ascii)!, "a+", stderr)
}

Use the above method in didFinishLaunching() and after that use NSLog() statements instead of print() and you will get what you want.

Reckoner
  • 1,041
  • 2
  • 13
  • 29