Skip to content

Instantly share code, notes, and snippets.

@luyx2412
Forked from bnjm/ModelWithDownload.js
Created November 9, 2018 15:50
Show Gist options
  • Save luyx2412/eaf8ce5f3343d563a3104ea10e864e6b to your computer and use it in GitHub Desktop.
Save luyx2412/eaf8ce5f3343d563a3104ea10e864e6b to your computer and use it in GitHub Desktop.
Example how to download a 3dmodel from the internet using react-native-arkit
// @flow
import { ARKit } from '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),
}}
/>
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment