{
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];
}
网友评论