沙盒文件瀏覽

站在巨人的肩膀上實現(xiàn)實時瀏覽log文件方案

iOS本地寫log方案,如下,就可以把通過NSLog打印的東東,寫入文件。(我們一般使用NSLog記錄錯誤的比較多)!

// 將NSlog打印信息保存到Document目錄下的文件中
- (void)redirectNSlogToDocumentFolder
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"xxxxx.log"];
    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
    // 先刪除已經(jīng)存在的文件
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    [defaultManager removeItemAtPath:logFilePath error:nil];
    
    // 將log輸入到文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}

這里是把 stdout 寫入文件中,通過定義,我們就可以發(fā)現(xiàn),stdout也是個文件句柄。但是如何查看這個文件呢。除了使用pc工具之外,我們可以手動擼一個小公舉

提供一個思路:拉大神的代碼改造一番:

代碼解釋:循環(huán)遍歷沙盒目錄,如果是路徑就深入遍歷,如果是文件,就提供查看的功能。

@interface PAirSandbox : NSObject

+ (instancetype)sharedInstance;

- (void)enableSwipe;
- (void)showSandboxBrowser;

@end

實現(xiàn)文件如下:

#import "PAirSandbox.h"
#import <UIKit/UIKit.h>

#import "Masonry.h"

#import "AppDelegate.h"

@interface __logVC : UIViewController
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIButton *backButton;
@end


@implementation __logVC

- (UITextView *)textView {
    if (!_textView) {
        _textView = [UITextView new];
        _textView.backgroundColor = [UIColor blackColor];
        _textView.textColor = [UIColor whiteColor];
        _textView.editable = NO;
        _textView.font = [UIFont fontWithName:@"Menlo-Regular" size:15];
    }
    return _textView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self.view addSubview:self.textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.offset(80);
    }];
    _backButton = [UIButton new];
    [_backButton setTitle:@"返回"
                 forState:(UIControlStateNormal)];
    [_backButton addTarget:self
                    action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backButton];
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.top.offset(20);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    [_backButton setBackgroundColor:[UIColor grayColor]];
    
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)back {
    [self dismissViewControllerAnimated:YES
                             completion:nil];
}

@end


#define ASThemeColor [UIColor colorWithWhite:0.2 alpha:1.0]
#define ASWindowPadding 20

#pragma mark- ASFileItem

typedef enum : NSUInteger {
    ASFileItemUp,
    ASFileItemDirectory,
    ASFileItemFile,
} ASFileItemType;

@interface ASFileItem : NSObject
@property (nonatomic, copy) NSString*                 name;
@property (nonatomic, copy) NSString*                 path;
@property (nonatomic, assign) ASFileItemType          type;
@end

@implementation ASFileItem
@end

#pragma mark- ASTableViewCell
@interface PAirSandboxCell : UITableViewCell
@property (nonatomic, strong) UILabel*                 lbName;
@end

@implementation PAirSandboxCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        int cellWidth = [UIScreen mainScreen].bounds.size.width - 2*ASWindowPadding;
        
        _lbName = [UILabel new];
        _lbName.backgroundColor = [UIColor clearColor];
        _lbName.font = [UIFont systemFontOfSize:13];
        _lbName.textAlignment = NSTextAlignmentLeft;
        _lbName.frame = CGRectMake(10, 30, cellWidth - 20, 15);
        _lbName.textColor = [UIColor blackColor];
        [self addSubview:_lbName];
        
        UIView* line = [UIView new];
        line.backgroundColor = ASThemeColor;
        line.frame = CGRectMake(10, 47, cellWidth - 20, 1);
        [self addSubview:line];
    }
    return self;
}

- (void)renderWithItem:(ASFileItem*)item
{
    _lbName.text = item.name;
}

@end

#pragma mark- ASViewController
@interface ASViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView*                 tableView;
@property (nonatomic, strong) UIButton*                    btnClose;
@property (nonatomic, strong) NSArray*                     items;
@property (nonatomic, copy) NSString*                      rootPath;
@end

@implementation ASViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self prepareCtrl];
    [self loadPath:nil];
}

- (void)prepareCtrl
{
    self.view.backgroundColor = [UIColor whiteColor];

    _btnClose = [UIButton new];
    [self.view addSubview:_btnClose];
    _btnClose.backgroundColor = ASThemeColor;
    [_btnClose setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnClose setTitle:@"Close" forState:UIControlStateNormal];
    [_btnClose addTarget:self action:@selector(btnCloseClick) forControlEvents:UIControlEventTouchUpInside];
    
    _tableView = [UITableView new];
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;

    _items = @[];
    _rootPath = NSHomeDirectory();
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    int viewWidth = [UIScreen mainScreen].bounds.size.width - 2*ASWindowPadding;
    int closeWidth = 60;
    int closeHeight = 28;
    
    _btnClose.frame = CGRectMake(viewWidth-closeWidth-4, 4, closeWidth, closeHeight);
    
    CGRect tableFrame = self.view.frame;
    tableFrame.origin.y += (closeHeight+4);
    tableFrame.size.height -= (closeHeight+4);
    _tableView.frame = tableFrame;
}

- (void)btnCloseClick
{
    self.view.window.hidden = true;
}

- (void)loadPath:(NSString*)filePath
{
    NSMutableArray* files = @[].mutableCopy;
    
    NSFileManager* fm = [NSFileManager defaultManager];
    
    NSString* targetPath = filePath;
    if (targetPath.length == 0 || [targetPath isEqualToString:_rootPath]) {
        targetPath = _rootPath;
    }
    else
    {
        ASFileItem* file = [ASFileItem new];
        file.name = @"..";
        file.type = ASFileItemUp;
        file.path = filePath;
        [files addObject:file];
    }
    
    NSError* err = nil;
    NSArray* paths = [fm contentsOfDirectoryAtPath:targetPath error:&err];
    for (NSString* path in paths) {
        
        if ([[path lastPathComponent] hasPrefix:@"."]) {
            continue;
        }

        BOOL isDir = false;
        NSString* fullPath = [targetPath stringByAppendingPathComponent:path];
        [fm fileExistsAtPath:fullPath isDirectory:&isDir];
        
        ASFileItem* file = [ASFileItem new];
        file.path = fullPath;
        if (isDir) {
            file.type = ASFileItemDirectory;
            file.name = [NSString stringWithFormat:@"%@ %@", @"", path];
        }
        else
        {
            file.type = ASFileItemFile;
            file.name = [NSString stringWithFormat:@"%@ %@", @"", path];
        }
        [files addObject:file];
        
    }
    _items = files.copy;
    [_tableView reloadData];
}

#pragma mark- UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > _items.count-1) {
        return [UITableViewCell new];
    }
    
    ASFileItem* item = [_items objectAtIndex:indexPath.row];
    
    static NSString* cellIdentifier = @"PAirSandboxCell";
    PAirSandboxCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[PAirSandboxCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    [cell renderWithItem:item];
    
    return cell;
}

#pragma mark- UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > _items.count-1) {
        return;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:false];
    
    ASFileItem* item = [_items objectAtIndex:indexPath.row];
    if (item.type == ASFileItemUp) {
        [self loadPath:[item.path stringByDeletingLastPathComponent]];
    }
    else if(item.type == ASFileItemFile) {
        [self sharePath:item.path];
    }
    else if(item.type == ASFileItemDirectory) {
        [self loadPath:item.path];
    }
}

- (void)sharePath:(NSString*)path
{
    NSURL *url = [NSURL fileURLWithPath:path];
    
    //彈出框
    UIAlertController *actionController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *actionPushToRoom = [UIAlertAction actionWithTitle:@"瀏覽文件" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        if (!str) {
            str = @"暫時沒log || 文件不是文本內(nèi)容";
        }
        __logVC *vc = [__logVC new];
        vc.textView.text = str;
        UIViewController *rvc = (UIViewController *)GetAppDelegate.window.rootViewController;
        [rvc presentModalViewController:vc animated:YES];
        self.view.window.hidden = true;
    }];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"分享文件" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSArray *objectsToShare = @[url];
        
        UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
        NSArray *excludedActivities = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
                                        UIActivityTypePostToWeibo,
                                        UIActivityTypeMessage, UIActivityTypeMail,
                                        UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
                                        UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
                                        UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
                                        UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
        controller.excludedActivityTypes = excludedActivities;
        
        if ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"]) {
            controller.popoverPresentationController.sourceView = self.view;
            controller.popoverPresentationController.sourceRect = CGRectMake([UIScreen mainScreen].bounds.size.width * 0.5, [UIScreen mainScreen].bounds.size.height, 10, 10);
        }
        [self presentViewController:controller animated:YES completion:nil];
    }];
    
    [actionController addAction:actionPushToRoom];
    [actionController addAction:actionCancel];
    
    [self presentViewController:actionController animated:YES completion:nil];
}

@end

#pragma mark- PAirSandbox
@interface PAirSandbox ()
@property (nonatomic, strong) UIWindow*                         window;
@property (nonatomic, strong) ASViewController*                 ctrl;

@end

@implementation PAirSandbox

+ (instancetype)sharedInstance
{
    static PAirSandbox* instance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [PAirSandbox new];
    });

    return instance;
}

- (void)enableSwipe
{
    UISwipeGestureRecognizer* swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipeDetected:)];
    swipeGesture.numberOfTouchesRequired = 1;
    swipeGesture.direction = (UISwipeGestureRecognizerDirectionLeft);
    [[UIApplication sharedApplication].keyWindow addGestureRecognizer:swipeGesture];
}

- (void)onSwipeDetected:(UISwipeGestureRecognizer*)gs
{
    [self showSandboxBrowser];
}

- (void)showSandboxBrowser {
    if (_window == nil) {
        _window = [UIWindow new];
        CGRect keyFrame = [UIScreen mainScreen].bounds;
        keyFrame.origin.y += 64;
        keyFrame.size.height -= 64;
        _window.frame = CGRectInset(keyFrame, ASWindowPadding, ASWindowPadding);
        _window.backgroundColor = [UIColor whiteColor];
        _window.layer.borderColor = ASThemeColor.CGColor;
        _window.layer.borderWidth = 2.0;
        _window.windowLevel = UIWindowLevelStatusBar;
        
        _ctrl = [ASViewController new];
        _window.rootViewController = _ctrl;
    }
    _window.hidden = false;
}

@end

如圖:

[圖片上傳中...(000002.png-c1266f-1525945990445-0)]
000002.png
000003.png

END

圖片瀏覽的功能還沒實現(xiàn)。但是應(yīng)付平常的查看log功能,綽綽有余了!!

使用

如下代碼就可以彈出了:

[[PAirSandbox sharedInstance] showSandboxBrowser];

改進

git 上有個開源庫,叫 ICTextView,支持 文本編輯,支持搜索文字以及高亮顯示

ICTextView支持字符串/正則表達式搜索以及高亮
可定制化
沒有使用委托方法

我們可以拿過來直接改造展示的textView,效果如圖:

支持搜搜

這樣我們的沙盒瀏覽工具就支持搜索功能了!

要引入的文件就相對多了點:


文件目錄
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、環(huán)境準備 安裝node.js 進入官網(wǎng):https://nodejs.org/en/download/。 網(wǎng)站...
    古早人說說閱讀 3,160評論 1 3
  • 人臉檢測是目前所有目標檢測子方向中被研究的最充分的問題之一,它在安防監(jiān)控,人證比對,人機交互,社交和娛樂等方面有很...
    玲小喵閱讀 484評論 0 0
  • 今天登陸本地跳板機顯示所有服務(wù)器列表時發(fā)現(xiàn),跳板機所在物理機上的虛擬機顯示的ip是192.168.110.31這樣...
    五大RobertWu伍洋閱讀 658評論 0 0
  • 區(qū)塊鏈的誕生,推動了一場旨在顛覆整個科技行業(yè)的運動,區(qū)塊鏈和加密貨幣的粉絲們稱之為Web 3.0。它將顛覆整個傳統(tǒng)...
    玲小喵閱讀 128評論 0 0
  • 控制臺 文檔 備案 郵箱 登錄 中國站 全部導(dǎo)航 最新活動 產(chǎn)品 解決方案 定價 ET大腦 數(shù)據(jù)智能 安全 云市場...
    玲小喵閱讀 152評論 0 0

友情鏈接更多精彩內(nèi)容