1. 程式人生 > >清除快取:react-native-http-cache

清除快取: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);
    }
}