程序內實現console控制臺打印

{
UIButton *logBtn = [UIButton buttonWithType:UIButtonTypeCustom];
logBtn.frame = CGRectMake(0, kStatusBarHeight, 100, 30);
[logBtn setTitle:@"console" forState:UIControlStateNormal];
logBtn.backgroundColor = UIColor.grayColor;
[logBtn setTitleColor:UIColor.greenColor forState:UIControlStateNormal];
[logBtn addTarget:self action:@selector(logBtnAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logBtn];

textView = [[UITextView alloc]initWithFrame:CGRectMake(0,kStatusBarHeight+30, kScreenWidth, kScreenWidth)];
textView.backgroundColor = [UIColor.yellowColor colorWithAlphaComponent:0.25];
[self.view addSubview:textView];
textView.hidden = YES;
[self redirectSTD:STDOUT_FILENO];
[self redirectSTD:STDERR_FILENO];

}
-(void)logBtnAction{
textView.hidden = !textView.hidden;
}

  • (void)redirectNotificationHandle:(NSNotification *)nf{ // 通知方法
    NSData *data = [[nf userInfo] objectForKey:NSFileHandleNotificationDataItem];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    textView.text = [NSString stringWithFormat:@"%@\n\n%@",textView.text, str];// logTextView 就是要將日志輸出的視圖(UITextView)
    NSRange range;
    range.location = [textView.text length] - 1;
    range.length = 0;
    [textView scrollRangeToVisible:range];
    [[nf object] readInBackgroundAndNotify];
    }

  • (void)redirectSTD:(int )fd{
    NSPipe * pipe = [NSPipe pipe] ;// 初始化一個NSPipe 對象
    NSFileHandle *pipeReadHandle = [pipe fileHandleForReading] ;
    dup2([[pipe fileHandleForWriting] fileDescriptor], fd) ;

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(redirectNotificationHandle:)
    name:NSFileHandleReadCompletionNotification
    object:pipeReadHandle]; // 注冊通知
    [pipeReadHandle readInBackgroundAndNotify];
    }

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容