【发布时间】:2019-05-27 10:24:32
【问题描述】:
我在 Xcode IDE 下使用 Swift 为 iPhone 创建了一个 iOS 应用程序。出于调试目的,我希望将 print(和 C 代码中的 printf)正常打印到 Xcode 控制台的所有内容都重定向到 UItextView。我的代码(主要来源于here)如下:
//
// ViewController.swift
// Scroll View Demo
//
//
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var writeButton: UIButton!
var pipe = Pipe()
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// dup2() makes newfd (new file descriptor) be the copy of oldfd (old file descriptor), closing newfd first if necessary.
openConsolePipe()
print("\npipe started")
}
@IBAction func buttonPressed(_ sender: Any) {
print("\(count). Hello world")
count += 1
}
public func openConsolePipe () {
dup2(pipe.fileHandleForWriting.fileDescriptor,
STDOUT_FILENO)
// listening on the readabilityHandler
pipe.fileHandleForReading.readabilityHandler = {
[weak self] handle in
let data = handle.availableData
let str = String(data: data, encoding: .ascii) ?? "<Non-ascii data of size\(data.count)>\n"
DispatchQueue.main.async {
self?.textView.text += str
}
}
}
}
代码在物理设备和虚拟 iPhone 上的模拟模式下工作。但是,当我使用 Xcode cut 的电源线本地运行它时, pipe() 不起作用。 目前我不知道为什么 pipe() 在独立应用程序中不起作用。
【问题讨论】:
-
我无法重现此问题。将此文件放入一个新项目并连接一个文本视图(注释掉按钮),在文本视图中打印“管道启动”。
-
在 iPhone 上原生运行? (iOS 10.1.2)、Xcode 10.1、Swift 4.2.1、mojawe 10.14.2。在 Xcode IDE 中,该应用程序也可以在我身上运行。
-
我重复了测试,没有任何按钮。只是带有初始文本的 UItextView。当应用程序在设备上物理运行时,不会出现 print("pipe started") ..
-
我的意思是在物理上和本机上,准确地说是没有连接到 Xcode。
-
如果您断开与 Xcode 的连接,我看到了您的行为。我认为这是因为操作系统在该配置中关闭或捕获了这些文件句柄,但我记不清了。我曾经尝试按照这些思路在 ObjC 中编写一个 NSLog 捕获系统,但因为无法使其工作而放弃了它,但那是很久以前的事了,我不记得确切的症状了。
标签: ios swift xcode pipe simulator