Не удается сохранить захваченное изображение и видео в firebase в react native (expo) - PullRequest
0 голосов
/ 21 июня 2020

Я новичок в React Native, и я застрял в проекте, над которым ставлю перед собой задачу. Вот мой код на странице камеры ... Я не хочу сохранять в firebase со страницы камеры ...

// src/camera.page.js file
import React from 'react';
import { View, Text, Alert } from 'react-native';
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';

import styles from './styles';
import Toolbar from './toolbar.component';
import Gallery from './gallery.component';

export default class CameraPage extends React.Component {
    camera = null;

    state = {
        captures: [],
        // setting flash to be turned off by default
        flashMode: Camera.Constants.FlashMode.off,
        capturing: null,
        // start the back camera by default
        cameraType: Camera.Constants.Type.back,
        hasCameraPermission: null,
    };

    setFlashMode = (flashMode) => this.setState({ flashMode });
    setCameraType = (cameraType) => this.setState({ cameraType });
    handleCaptureIn = () => this.setState({ capturing: true });

    handleCaptureOut = () => {
        if (this.state.capturing)
            this.camera.stopRecording();
    };

    handleShortCapture = async () => {
        const photoData = await this.camera.takePictureAsync();
        this.setState({ capturing: false, captures: [photoData, ...this.state.captures] })
    };


    handleLongCapture = async () => {
        // Before starting to recording, setup a timer that calls stopRecording() after 20s IF the camera is still recording, otherwise, no need to call stop
        setTimeout(() => this.state.capturing && this.camera.stopRecording(), 20*1000);
        const videoData = await this.camera.recordAsync();
        this.setState({ capturing: false, captures: [videoData, ...this.state.captures] });
    };

    async componentDidMount() {
        const camera = await Permissions.askAsync(Permissions.CAMERA);
        const audio = await Permissions.askAsync(Permissions.AUDIO_RECORDING);
        const hasCameraPermission = (camera.status === 'granted' && audio.status === 'granted');

        this.setState({ hasCameraPermission });

        
    };

    render() {
        const { hasCameraPermission, flashMode, cameraType, capturing, captures } = this.state;

        if (hasCameraPermission === null) {
            return <View />;
        } else if (hasCameraPermission === false) {
            return <Text>Access to camera has been denied.</Text>;
        }

        return (
            <React.Fragment>
                
                    <View>
                        <Camera
                            type={ cameraType }
                            flashMode={ flashMode }
                            style={styles.preview}
                            ref={camera => this.camera = camera}
                        />
                    </View>
                    {captures.length > 0 && <Gallery captures={captures}/>}
                <Toolbar 
                    capturing={capturing}
                    flashMode={flashMode}
                    cameraType={cameraType}
                    setFlashMode={this.setFlashMode}
                    setCameraType={this.setCameraType}
                    onCaptureIn={this.handleCaptureIn}
                    onCaptureOut={this.handleCaptureOut}
                    onLongCapture={this.handleLongCapture}
                    onShortCapture={this.handleShortCapture}
                />
            </React.Fragment>
        );
    };
};

У меня есть другой компонент галереи экрана. js ... это то место, где я хочу сохранить в firebase при нажатии кнопки ... Я пробовал использовать модальный режим для предварительного просмотра захваченное изображение или видео, но модальный режим не работает, я не знаю почему. Также я хочу иметь возможность воспроизводить записанное видео в модальном окне перед сохранением в firebase или отбрасывать изображение / видео. Ниже мой код на gallery.component. js

import React, { useState } from 'react';
import { View, Text, Image, Button, Modal, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as firebase from 'firebase';
import { Camera } from 'expo-camera';

import styles from './styles';

export default ({ captures = [] }) => {
    const [isVisible, setIsVisible] = useState(false);

    const takePicture = async () => {
        const photoData = await Camera.takePictureAsync();
        if (!photoData.cancelled) {
            uploadImage(photoData.uri, imageName)
                .then(() => {
                    Alert.alert("Success");
                })
                .catch((error) => {
                    Alert.alert('Error:', error.message);
                });
        }
    }

    const uploadImage = async (uri, imageName) => {
        const response = await fetch(uri);
        const blob = await response.blob();
        var ref = storage().ref().child("images/" + imageName);
        return ref.put(blob)
    }

    return (
        <Modal
            transparent={true}
            visible={isVisible}
        // style={[styles.bottomToolbar, styles.galleryContainer]} 
        >
            <View style={{ backgroundColor: "#000000aa", flex: 1 }}>
                {captures.map(({ uri }) => (
                    <View style={styles.galleryImageContainer} key={uri}>
                        <Image source={{ uri }} style={styles.galleryImage} />
                    </View>
                ))}
            </View>
            <TouchableOpacity
                style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginTop: 20,
                    top: -20
                }}
                onPress={() => setIsVisible(false)}
            >
                <Ionicons
                    name="md-close-outline"
                    color="white"
                    size={40}
                />
                <Text style={{ color: 'white' }}>Discard</Text>
            </TouchableOpacity>
            <Button
                title='Save'
                onPress={takePicture}
            />
        </Modal>
    );
};

Пожалуйста, мне нужна помощь для достижения упомянутого выше. Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...