10

How can I get the console logs with all the print/Nslog contents and display it on a textview? Thank you very much for your answer.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user3205472
  • 175
  • 1
  • 1
  • 7
  • "How can I get the console logs" You can't. If you could, there would be apps that display the console logs, and there are no such apps nowadays. – matt Aug 10 '16 at 16:19

4 Answers4

3

To accomplish this I modified the OutputListener Class described in this article titled "Intercepting stdout in Swift" by phatblat:

func captureStandardOutputAndRouteToTextView() {
    outputPipe = Pipe()

    // Intercept STDOUT with outputPipe
    dup2(self.outputPipe.fileHandleForWriting.fileDescriptor, FileHandle.standardOutput.fileDescriptor)
    
    outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
    
    NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outputPipe.fileHandleForReading , queue: nil) {
      notification in
      
      let output = self.outputPipe.fileHandleForReading.availableData
      let outputString = String(data: output, encoding: String.Encoding.utf8) ?? ""
      
      DispatchQueue.main.async(execute: {
        let previousOutput = self.outputText.string
        let nextOutput = previousOutput + outputString
        self.outputText.string = nextOutput
        
        let range = NSRange(location:nextOutput.count,length:0)
        self.outputText.scrollRangeToVisible(range)
      })
      
      self.outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
    }
  }
}
Mikeumus
  • 3,570
  • 9
  • 40
  • 65
2

If you do not want to change existing code, you can;

1 - redirect the output of print to a known file. see instructions here; How to redirect the nslog output to file instead of console ( answer 4, redirecting)

2 - monitor the file for changes and read them in to display in your textView.

Community
  • 1
  • 1
john elemans
  • 2,578
  • 2
  • 15
  • 26
  • HI I have manage to implement this code in swift but my other NSLogs or in swift is print is not registering to my text file – user3205472 Aug 12 '16 at 13:20
0

You cannot do that.

You can use some logger, witch allow you to add custom log destination. You will have to change all print/NSLog calls to e.g. Log.verbose(message).

I'm using SwiftyBeaver. It allows you to define your custom destination. You can later read it and present in some text field.

Daniel Sumara
  • 2,234
  • 20
  • 25
0

You can totally do that! Check this out: https://stackoverflow.com/a/13303081/1491675

Basically you create an output file and pipe the stderr output to that file. Then to display in your textView, just read the file and populate your textView.

Community
  • 1
  • 1
Chris
  • 955
  • 15
  • 20