Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the console logs and display in a textview [Swift]

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.

like image 204
user3205472 Avatar asked Aug 10 '16 15:08

user3205472


People also ask

How do I see console in Xcode?

Go to Xcode → Preferences → Debugging → On Start → "Show Console".

How do I view logs in Xcode?

In the Xcode menu hit Run - Console. This is where NSLog / print / printf etc statements output. The key command is Command + Shift + R.


1 Answers

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()
    }
  }
}
like image 190
Mikeumus Avatar answered Sep 19 '22 16:09

Mikeumus