AI智能
改变未来

ios真机运行时保存日志并输出

(断开xcode进行真机测试时,无法通过xcode看到运行日志)

方法:

1、在AppDelegate.m中,当app启动时加入redirectNSLogToDocumentFolder方法:该方法具体实现:

- (void)redirectNSLogToDocumentFolder{//如果已经连接Xcode调试则不输出到文件if(isatty(STDOUT_FILENO)) {return;}UIDevice *device = [UIDevice currentDevice];if([[device model] hasSuffix:@\"Simulator\"]){ //在模拟器不保存到文件中return;}//获取Document目录下的Log文件夹,若没有则新建NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@\"Log\"];NSFileManager *fileManager = [NSFileManager defaultManager];BOOL fileExists = [fileManager fileExistsAtPath:logDirectory];if (!fileExists) {[fileManager createDirectoryAtPath:logDirectory  withIntermediateDirectories:YES attributes:nil error:nil];}NSDateFormatter *formatter = [[NSDateFormatter alloc] init];[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@\"zh_CN\"]];[formatter setDateFormat:@\"yyyy-MM-dd HH:mm:ss\"]; //每次启动后都保存一个新的日志文件中NSString *dateStr = [formatter stringFromDate:[NSDate date]];NSString *logFilePath = [logDirectory stringByAppendingFormat:@\"/%@.txt\",dateStr];// freopen 重定向输出输出流,将log输入到文件freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], \"a+\", stdout);freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], \"a+\", stderr);}

2、修改配置文件 修改项目下的Info.plist , 添加UIFileSharingEnabled键,并将键值设置为YES,添加之后, 添加之后会变成 Application supports iTunes file sharing YES:

3、查看可使用itunes:

选中Log文件夹,点“存储”,默认以.txt格式保存在“文稿”下

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » ios真机运行时保存日志并输出