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.

1
  • "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. Commented Aug 10, 2016 at 16:19

3 Answers 3

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()
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.