Skip to content

Instantly share code, notes, and snippets.

@macrozone
Last active March 29, 2018 15:42

Revisions

  1. macrozone revised this gist Sep 12, 2017. No changes.
  2. macrozone created this gist Sep 12, 2017.
    74 changes: 74 additions & 0 deletions ModelWithDownload.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@
    // @flow
    import { ARKit } from '@panter/react-native-arkit'
    import { branch, compose, lifecycle, renderComponent } from 'recompose'
    import { unzip } from 'react-native-zip-archive'
    import RNFetchBlob from 'react-native-fetch-blob'
    import React from 'react'


    const getModelPath = modelId => (
    `${RNFetchBlob.fs.dirs.CacheDir}/models/${modelId}/`
    )

    const getModelFile = modelId => (
    `${getModelPath(modelId)}product-optimized.scnassets/model.dae`
    )

    const getModelUrl = modelId => (
    `https://example.com/path/to/download/model?modelId=${modelId}`
    )

    async function loadModel(passedProps = null) {
    const props = passedProps || this.props


    const { modelId } = props

    const path = getModelPath(modelId)
    const modelFile = getModelFile(modelId)
    const exists = await RNFetchBlob.fs.exists(modelFile)
    if (exists) {
    this.setState({ isLoading: false })
    } else {
    this.setState({ isLoading: true })
    const result = await RNFetchBlob.config({
    fileCache: true,
    })
    .fetch('GET', getModelUrl(modelId))
    .progress((received, total) => {
    console.log('progress', received, total, received / total)
    })

    console.log('The file saved to ', result.path())
    const unzipPath = await unzip(result.path(), path)
    console.log(`unzip completed at ${unzipPath}`)
    this.setState({ isLoading: false })
    }
    }

    const withModelDownload = compose(
    lifecycle({
    componentDidMount: loadModel,
    componentWillReceiveProps: loadModel,
    }),
    branch(
    ({ isLoading }) => isLoading,
    renderComponent(({ pos }) => (
    // you can render a placeholder here.
    <ARKit.Box
    pos={pos}
    shape={{ width: 1, height: 1, length: 1, chamfer: 0.01 }}
    />
    )),
    ),
    )

    export default withModelDownload(({ pos, modelId }) => (
    <ARKit.Model
    pos={pos}
    model={{
    scale: 1,
    file: getModelFile(modelId),
    }}
    />
    ))