【问题标题】:How to get the console logs and display in a textview [Swift]如何获取控制台日志并在文本视图中显示 [Swift]
【发布时间】:2016-08-10 15:33:59
【问题描述】:

如何获取包含所有打印/Nslog 内容的控制台日志并将其显示在文本视图上?非常感谢您的回答。

【问题讨论】:

  • "我怎样才能得到控制台日志" 你不能。如果可以的话,会有显示控制台日志的应用程序,而现在没有这样的应用程序。

标签: ios swift debugging


【解决方案1】:

为了实现这一点,我修改了 phatblat 题为“Intercepting stdout in Swift”的这篇文章中描述的 OutputListener 类:

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()
    }
  }
}

【讨论】:

    【解决方案2】:

    如果您不想更改现有代码,可以;

    1 - 将 print 的输出重定向到已知文件。 请参阅此处的说明; How to redirect the nslog output to file instead of console(答案 4,重定向)

    2 - 监视文件的更改并将其读入以显示在您的 textView 中。

    【讨论】:

    • 嗨,我已经设法在 swift 中实现此代码,但我的其他 NSLogs 或在 swift 中打印未注册到我的文本文件
    【解决方案3】:

    你不能那样做。

    您可以使用一些记录器,允许您添加自定义日志目的地。 您必须将所有 print/NSLog 调用更改为例如Log.verbose(message).

    我正在使用SwiftyBeaver。它允许您定义您的自定义目的地。您可以稍后阅读它并在某些文本字段中显示。

    【讨论】:

      【解决方案4】:

      你完全可以做到!看看这个:https://stackoverflow.com/a/13303081/1491675

      基本上,您创建一个输出文件并将标准错误输出通过管道传输到该文件。然后在你的 textView 中显示,只需读取文件并填充你的 textView。

      【讨论】:

        猜你喜欢
        • 2020-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        • 2013-09-16
        • 1970-01-01
        相关资源
        最近更新 更多