iOS-真机调试输出NSLog到沙盒并查看

这里关于沙盒机制等相关知识介绍是没有的,有需要的可以去专门看关于沙盒的介绍博客,谢谢~

还有就是该文章是在真机调试的情况下哈

1. 写入沙盒的关键代码

- (void)redirectNSLogToDocumentFolder{
    //获取沙盒路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //获取沙盒路径下的Documents路径
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //设置文件名称,这里用的是日期时间作为文件名
    NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
    //拼接沙盒路径+文件夹名称转为文件路径
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    //stderr就是我们的NSLog,将其写入文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}
复制代码

2. 测试代码

注意⚠️:写入沙盒的函数一定要在对应的NSLog语句之前进行调用,才能正确写入沙盒,细节可看下方代码

//
//  ViewController.m
//  沙盒test01
//
//  Created by game-netease on 2021/6/16.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    //在NSLog调用前调用redirectNSLogToDocumentFolder函数
    [self redirectNSLogToDocumentFolder]; 
    NSLog(@"%@",path);
    
}

- (void)redirectNSLogToDocumentFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

@end
复制代码

3. 查看输出文件

注意⚠️:在真机调试的情况下写入沙盒,那么NSLog语句就不会在Xcode上输出了,你是看不到的

(所以不要像我一开始一样:“嗯嗯?!!为什么没有输出语句了?怎么回事?!”)

  1. 打开Devices

image.png

可以看到我们运行的App在这里
image.png

  1. 下载文件

image.png

点击Download进行下载

image.png

  1. 显示包内容打开文件

image.png

就可以看到我们的文件啦!

image.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享