5

I am facing a problem, cannot figure out how to implement such action. I want to Download Photo from external source, and then I want to open it in gallery.

Checked this source: How to open iOS gallery app from React Native app

Here one developer suggest to use this code:

openPhotos = () =>{
switch(Platform.OS){
  case "ios":
    Linking.openURL("photos-redirect://");
  break;
  case "android":
    Linking.openURL("content://media/internal/images/media");
  break;
  default:
    console.log("Could not open gallery app");
 }
}

This code does open gallery, but when I select default gallery app, it shows black screen, if I choose google photos app it opens the gallery without black screen.

My question would be how could I refactor my code, to be able to Download Photo, and open downloaded photo in gallery?

Component code:

import React from "react";
import {View,Text, StyleSheet,Platform,Image,Alert} from "react-native";
import PhotoComments from "./PhotoComments";
import moment from "moment";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import { Button } from "react-native-elements";
import { Linking } from "expo";

function downloadFile(uri) {
  let filename = uri.split("/");
  filename = filename[filename.length - 1];
  let fileUri = FileSystem.documentDirectory + filename;
  FileSystem.downloadAsync(uri, fileUri)
    .then(({ uri }) => {
      saveFile(uri);
    })
    .catch(error => {
      Alert.alert("Error", "Couldn't download photo");
      console.error(error);
    });
}
async function openPhotos(uri) {
  switch (Platform.OS) {
    case "ios":
      Linking.openURL("photos-redirect://");
      break;
    case "android":
      //Linking.openURL("content://media/internal/images/media/");
      Linking.openURL("content://media/internal/images/media");
      break;
    default:
      console.log("Could not open gallery app");
  }
}

async function saveFile(fileUri) {
  const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
  if (status === "granted") {
    const asset = await MediaLibrary.createAssetAsync(fileUri);
    const data = await MediaLibrary.createAlbumAsync("Download", asset, false);
    console.log("deubeuger");
    console.log(data);
    console.log("buger");

    Alert.alert("Success!", JSON.stringify(fileUri));
    openPhotos(fileUri);
  }
}

const PhotoRecord = ({ data }) => {
  return (
    <View style={styles.container}>
      <View style={styles.infoContainer}>
        <Text style={styles.usernameLabel}>@{data.username}</Text>
        <Text style={styles.addedAtLabel}>
          {moment(new Date(data.addedAt)).format("YYYY/MM/DD HH:mm")}
        </Text>
      </View>
      <View style={styles.imageContainer}>
        <Image source={{ uri: data.links.thumb }} style={styles.image} />
      </View>
      <PhotoComments comments={data.photoComments} />
      <View style={styles.btnContainer}>
        <Button
          buttonStyle={{
            backgroundColor: "white",
            borderWidth: 1
          }}
          titleStyle={{ color: "dodgerblue" }}
          containerStyle={{ backgroundColor: "yellow" }}
          title="Add Comment"
        />
        <Button
          onPress={() => downloadFile(data.links.image)}
          style={styles.btn}
          title="Download"
        />
      </View>
    </View>
  );
};

I managed to implement downloading from external source, but cannot find the working solutions on how to open downloaded photo through gallery app.

Maybe I am looking for solution which is not efficient, maybe there is a better way?

LuckyLuke
  • 1,028
  • 2
  • 14
  • 28

1 Answers1

3

Couldn't find desirable solution for this problem. Decided to develop an app a little bit differently, if someone with similar problem will search for this thread. I made Download Button which will Download photo to the device

import React, { useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  Alert,
  TouchableOpacity
} from "react-native";
import PhotoComments from "./PhotoComments";
import moment from "moment";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import { Button } from "react-native-elements";
import ZoomableImage from "./ZoomableImage";

function downloadFile(uri) {
  let filename = uri.split("/");
  filename = filename[filename.length - 1];
  let fileUri = FileSystem.documentDirectory + filename;
  FileSystem.downloadAsync(uri, fileUri)
    .then(({ uri }) => {
      saveFile(uri);
    })
    .catch(error => {
      Alert.alert("Error", "Couldn't download photo");
      console.error(error);
    });
}
async function saveFile(fileUri) {
  const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
  if (status === "granted") {
    const asset = await MediaLibrary.createAssetAsync(fileUri);
    await MediaLibrary.createAlbumAsync("Download", asset, false);
    Alert.alert("Success", "Image was successfully downloaded!");
  }
}

const PhotoRecord = ({ data }) => {
  const [show, setShow] = useState(false);

  return (
    <View style={styles.container}>
      <ZoomableImage
        show={show}
        setShow={setShow}
        imageSource={data.links.image}
      />
      <View style={styles.infoContainer}>
        <Text style={styles.usernameLabel}>@{data.username}</Text>
        <Text style={styles.addedAtLabel}>
          {moment(new Date(data.addedAt)).format("YYYY/MM/DD HH:mm")}
        </Text>
      </View>
      <TouchableOpacity
        activeOpacity={1}
        style={styles.imageContainer}
        onLongPress={() => setShow(true)}
      >
        <Image source={{ uri: data.links.thumb }} style={styles.image} />
      </TouchableOpacity>
      <PhotoComments comments={data.photoComments} />
      <View style={styles.btnContainer}>
        <Button
          buttonStyle={{
            backgroundColor: "white",
            borderWidth: 1
          }}
          titleStyle={{ color: "dodgerblue" }}
          containerStyle={{ backgroundColor: "yellow" }}
          title="Add Comment"
        />
        <Button
          onPress={() => downloadFile(data.links.image)}
          style={styles.btn}
          title="Download"
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    display: "flex",
    flexDirection: "column"
  },
  infoContainer: {
    borderBottomWidth: 1,
    borderColor: "gainsboro",
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between",
    padding: 15
  },
  usernameLabel: {
    fontSize: 18,
    fontWeight: "bold"
  },
  addedAtLabel: {
    paddingTop: 10,
    color: "#404040"
  },
  imageContainer: {
    width: "100%",
    height: 380
  },
  image: {
    width: "100%",
    height: "100%",
    resizeMode: "cover"
  },
  btnContainer: {
    flex: 1,
    flexDirection: "row",
    marginBottom: 100,
    justifyContent: "space-between"
  }
});

export default PhotoRecord;

  • On my device it looks like this

  • If Download button clicked it will download the photo to the device

  • If user want to inspect the image, he can do long press on the photo and then the photo will be open in a web view modal

This is far from perfect, but I could figure out by myself. The code for modal is here:

import React from "react";
import { Modal, Dimensions, StyleSheet, View } from "react-native";
import { WebView } from "react-native-webview";


const ZoomableImage = ({ show, setShow, imageSource }) => {
  return (
    <Modal
      animationType={"fade"}
      transparent={false}
      visible={show}
      onRequestClose={() => {
        setShow(!show);
      }}
    >
      <View style={styles.container}>
        <WebView source={{ uri: imageSource }} style={styles.image} />
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "space-between"
  },
  image: {
    height: Math.round(Dimensions.get("window").height),
    width: Math.round(Dimensions.get("window").width),
    flex: 1
  }
});
export default ZoomableImage;

Couldn't achieve what I wanted but came up with a slightly different solution, hopes this will help someone.

LuckyLuke
  • 1,028
  • 2
  • 14
  • 28
  • looking for something same. Need to open the native gallery though WebView wont do it for me – Blue Bot Dec 15 '20 at 11:56
  • Tried your functions but had this error on IOS: [Unhandled promise rejection: Error: Asset couldn't be saved to photo library] have you face it? – GeekDev Dec 19 '20 at 11:50
  • 2
    Well it's not working properly, I will post an answer as soon as I find a solution – GeekDev Dec 19 '20 at 12:42