美文网首页
RN获取缓存

RN获取缓存

作者: MasterPaul | 来源:发表于2020-09-30 13:49 被阅读0次
需求如图 2471601438292_.pic.jpg

封装一个缓存的工具类

import { NativeModules } from 'react-native';
const native = NativeModules.HttpCache;

export const clearHttpCache = native.clearCache;

export const getHttpCacheSize = native.getHttpCacheSize;

export const clearImageCache = native.clearImageCache;

export const getImageCacheSize = native.getImageCacheSize;

export async function getCacheSize(){
    const arr = await Promise.all([getHttpCacheSize(), getImageCacheSize()]);

    console.log(arr.join(','));
    // Get sum of all cache type.
    return arr.reduce((a,b)=>a+b, 0);
}

export async function clearCache(){
    await Promise.all([clearHttpCache(), clearImageCache()]);
}



const formatCache = cache => {
    let cacheSize = Math.floor(cache / 1024);
    console.log(cacheSize, 'cacheSize');
    switch (true) {
        case cacheSize / 1024 > 1: {
            cacheSize = `${Math.floor(cacheSize / 1024)} MB`;
            break;
        }
        default: {
            cacheSize = `${cacheSize} KB`;
            break;
        }
    }
    console.log('cache-size =>', cacheSize);
    return cacheSize;
};

export default class CacheUtil {
    static getCacheSize = async () => { // 获取缓存大小,注意getCacheSize()返回的是promise
        const cache = await getCacheSize();
        return formatCache(cache);
    };

    static clearCache = async () => { // 清除缓存
        const res = await clearCache(); // clearCache()返回的也是promise
        console.log('清除缓存的返回值 =>', res);
        return res;
    };
}

调用

import {Modal, Toast} from '@ant-design/react-native';

function getCache() {
        CacheUtil.getCacheSize().then(cache=>{
            console.log('获取缓存大小',cache)
            setCacheSize(cache)
        })
    }

function clearCache() {
        Modal.alert('提示','清除缓存?',
            [
                {
                    text:'取消',onPress:()=>{

                    },style:{color:'#333'}
                },{
                text:'确定',onPress:()=>{
                    CacheUtil.clearCache().then(res=>{
                        getCache()
                    })
                },style:{color:colors.red}}
            ]
        )
    }
  • 安卓代码
package com.fengmishequ.tbk.modules;

import com.facebook.cache.disk.DiskStorageCache;
import com.facebook.cache.disk.FileCache;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.network.OkHttpClientProvider;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import okhttp3.Cache;

/**
 * Created by tdzl2_000 on 2015-10-10.
 */
public class HttpCacheModule extends ReactContextBaseJavaModule {
    public HttpCacheModule(ReactApplicationContext context) {
        super(context);
    }

    @Override
    public String getName() {
        return "RCTHttpCache";
    }

    @ReactMethod
    public void clearCache(Promise promise){
        try {
            Cache cache = OkHttpClientProvider.getOkHttpClient().cache();
            if (cache != null) {
                cache.delete();
            }
            promise.resolve(null);
        } catch(IOException e){
            promise.reject(e);
        }
    }

    @ReactMethod
    public void getHttpCacheSize(Promise promise){
        try {
            Cache cache = OkHttpClientProvider.getOkHttpClient().cache();
            promise.resolve(cache != null ? ((double)cache.size()) : 0);
        } catch(IOException e){
            promise.reject(e);
        }
    }

    static Method update;
    private void updateCacheSize(DiskStorageCache cache) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (update == null){
            update = DiskStorageCache.class.getDeclaredMethod("maybeUpdateFileCacheSize");
            update.setAccessible(true);
        }
        update.invoke(cache);
    }

    @ReactMethod
    public void getImageCacheSize(Promise promise){
//        FileCache cache1 = ImagePipelineFactory.getInstance().getMainDiskStorageCache();
        FileCache cache1 = ImagePipelineFactory.getInstance().getMainFileCache();
        long size1 = cache1.getSize();
        if (size1 < 0){
            try {
                updateCacheSize((DiskStorageCache)cache1);
            } catch (Exception e){
                promise.reject(e);
                return;
            }
            size1 = cache1.getSize();
        }
//        FileCache cache2 = ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache();
        FileCache cache2 = ImagePipelineFactory.getInstance().getSmallImageFileCache();
        long size2 = cache2.getSize();
        if (size2 < 0){
            try {
                updateCacheSize((DiskStorageCache)cache2);
            } catch (Exception e){
                promise.reject(e);
                return;
            }
            size2 = cache2.getSize();
        }
        promise.resolve(((double)(size1+size2)));
    }

    @ReactMethod
    public void clearImageCache(Promise promise){
        FileCache cache1 = ImagePipelineFactory.getInstance().getMainFileCache();
        cache1.clearAll();
        FileCache cache2 = ImagePipelineFactory.getInstance().getSmallImageFileCache();
        cache2.clearAll();
        promise.resolve(null);
    }
}

  • ios端代码
//
//  RCTHttpCache.m
//  RCTHttpCache
//
//  Created by LvBingru on 12/30/15.
//  Copyright © 2015 erica. All rights reserved.
//

#import "RCTHttpCache.h"
//#import "RCTImageLoader.h"
//#import "RCTImageCache.h"
//#import "RCTBridge.h"

@implementation RCTHttpCache

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(HttpCache);

RCT_EXPORT_METHOD(getHttpCacheSize:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
    NSURLCache *httpCache = [NSURLCache sharedURLCache];
    resolve(@([httpCache currentDiskUsage]));
}

RCT_EXPORT_METHOD(clearCache:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
    NSURLCache *httpCache = [NSURLCache sharedURLCache];
    [httpCache removeAllCachedResponses];
    resolve(nil);
}


RCT_EXPORT_METHOD(getImageCacheSize:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
    resolve(@0);
}

RCT_EXPORT_METHOD(clearImageCache:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
    resolve(nil);
}


@end

相关文章

网友评论

      本文标题:RN获取缓存

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