清除缓存:react-native-http-cache

github: https://github.com/reactnativecn/react-native-http-cache

android:

npm install react-native-http-cache --save

react-native link react-native-http-cache

将 package.json 中的 react-native-http-cache 改为:

"react-native-http-cache": "https://github.com/puti94/react-native-http-cache"

CacheManager.getCacheSize()    返回网络缓存大小和图片缓存大小

CacheManager.getImageCacheSize()    返回的是一个 promise 对象

CacheManager.getHttpCacheSize()    返回的是一个 promise 对象

CacheManager.clearImageCache()    返回的是一个 promise 对象

CacheManager.clearHttpCache()    返回的是一个 promise 对象

CacheManager.clearCache()     清除缓存

CacheManager.getImageCacheSize()
    .then(data=> {
        data = data / (1024 * 1024);
        this.setState({
            imageCacheSize: data.toFixed(2) + 'M',
        })
        console.log('图片缓存' + data)
    })
    .catch(err => {
        console.log(err)
    })

ios:

在 Build Phases 中添加 依赖 libRCTHttpCache.a

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image} from 'react-native';

import * as CacheManager from 'react-native-http-cache';

export default class Cache extends Component {
    constructor(props){
        super(props);
        this.state = {
            imageCacheSize: 0,
            httpCacheSize: 0,
            size: 0,
        };
    }
    componentDidMount(){
        CacheManager.getImageCacheSize()
            .then(data=> {
                data = data / (1024 * 1024);
                this.setState({
                    imageCacheSize: data.toFixed(2),
                })
                console.log('图片缓存' + data)
            })
            .catch(err => {
                console.log(err)
            })

        CacheManager.getHttpCacheSize()
            .then(data=> {
                data = data / (1024 * 1024);
                this.setState({
                    httpCacheSize: data.toFixed(2),
                })
                console.log('网络缓存' + data)
            })
            .catch(err => {
                console.log(err)
            })
    }
    render() {
        let { imageCacheSize,httpCacheSize,size } = this.state;
        size = (imageCacheSize * 1 + httpCacheSize * 1).toFixed(2);
        // this.setState({size:size})
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>Welcome to React Native!</Text>
                <Text style={styles.welcome}>图片缓存大小:{imageCacheSize}M</Text>
                <Text style={styles.welcome}>网络缓存大小:{httpCacheSize}M</Text>
                <Text style={styles.welcome}>缓存:{size}M</Text>
                <View style={{flexDirection:'row',padding: 10,justifyContent:'space-around'}}>
                    <Image 
                        style={{width: 80,height: 80,marginRight:10}}
                        source={{uri:"http://b.hiphotos.baidu.com/image/h%3D300/sign=5a28a3caf1039245beb5e70fb795a4a8/b8014a90f603738d30915925be1bb051f919ecda.jpg"}}
                    />
                    <Image 
                        style={{width: 80,height: 80,marginRight:10}}
                        source={{uri:"http://b.hiphotos.baidu.com/image/h%3D300/sign=b48b76f776899e51678e3c1472a6d990/e824b899a9014c08ef778daf077b02087bf4f468.jpg"}}
                    />
                    <Image 
                        style={{width: 80,height: 80}}
                        source={{uri:"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2723310483,865690233&fm=26&gp=0.jpg"}}
                    />
                </View>
                <Text style={styles.welcome}
                    onPress={() => {
                        CacheManager.clearImageCache()
                            .then(data => {
                                if(data == null){
                                    console.log(data)
                                    this.setState({imageCacheSize: '0.00M'})
                                }
                            })
                            .catch(err => {
                                console.log(err)
                            })
                    }}
                >
                    清除图片缓存
                </Text>
                 <Text style={styles.welcome}
                    onPress={() => {
                        CacheManager.clearHttpCache()
                            .then(data => {
                                if(data == null){
                                    console.log(data)
                                    this.setState({httpCacheSize: '0.00M'})
                                }
                            })
                            .catch(err => {
                                console.log(err)
                            })
                    }}
                >
                    清除网络缓存
                </Text>
                <Text style={styles.welcome}
                    onPress={() => {
                        CacheManager.clearCache();
                        this.setState({
                            imageCacheSize: '0.00',
                            httpCacheSize: '0.00',
                            size: '0.00',
                        })
                    }}
                >
                    清除缓存
                </Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
        paddingTop: Platform.OS == 'ios' ? 35 : null,
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
});

清除缓存的话,有些会没有清除完,可以直接写死,反正缓存不大

-------------------------------------------------------------------------------

和别的组件一起用的时候Android下的 HttpCacheModule 会报错:

69和80行的方法未找到,下面是单独配置时的.java文件,替换即可

package cn.reactnative.httpcache;

import android.content.Intent;

import com.facebook.cache.disk.DiskStorageCache;
import com.facebook.cache.disk.FileCache;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.react.bridge.Callback;
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 okhttp3.Cache;

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

/**
 * 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().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().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);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39910762/article/details/82970348