美文网首页
程序内实现console控制台打印

程序内实现console控制台打印

作者: seventhboy | 来源:发表于2019-11-18 17:43 被阅读0次

    {
    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];
      }

    相关文章

      网友评论

          本文标题:程序内实现console控制台打印

          本文链接:https://www.haomeiwen.com/subject/olvbictx.html