1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ExpoでDropboxからインポート/エクスポートを実現する

Last updated at Posted at 2017-08-06

やりたいこと

reduxのstateをjsonとしてdropboxに吐き出してエクスポートし、それのインポートも可能にしたい

問題

Expoを用いたReact Naitveの開発をしているのでdropboxのsdk等をつかえない
-> OSのシェア機能で他アプリを呼び出して、ごにょごにょして解決するのがよさそう

解決

エクスポート

こちらはさほど難しくなかった。
react-nativeShareを呼び出してjsonを渡してあげることで実現できる。(dropboxが端末にインストールされている前提)

Export = () => {
  Share.share({
    message: JSON.stringify(this.props.data)
  })
}

インポート

こちらが大変だった。
DocumentPickerを使えばアプリを呼び出せるが、どうやって中身を読むのかで困った。

自分の技術力では実装できずにexpo.ioのforumに質問を投げたところ、実現できた。

Import = async () => {
  try {
    const pickerResponse = await DocumentPicker.getDocumentAsync()
    if (pickerResponse.type === 'cancel') {
      return false
    } else if (pickerResponse.type === 'success') {
      try {
        const downloaded = await FileSystem.downloadAsync(pickerResponse.uri, FileSystem.documentDirectory + 'import.json')
        const fileResponse = await FileSystem.readAsStringAsync(downloaded.uri)
        console.log(JSON.parse(fileResponse))
      } catch (exception) {
        console.log(`[FileSystem]: ${exception}`)
      }
    } else {
      return false
    }
  } catch (exception) {
    console.log(`[DocumentPicker]: ${exception}`)
  }
}

forumの質問はこちら(https://forums.expo.io/t/read-a-contents-from-dropbox-with-documentpicker-filesystem/1976)

はまったところ

割りと初歩的な(かつ当然と言われれば当然な気もする...)ところなのかもしれないが、インポートの際にDocumentPickerを用いてDropboxからファイルを選択した際に例外を投げるところでつまづいた。
原因はdocumentPickerが返してくれるuriはfile:///だがローカルにはないらしく参照できなかったからだと思われる。
これに気が付かずハマったが、forumでダウンロードされてないからじゃないかという指摘を頂き、FileSystem.downloadAsync()を使ってダウンロードすることを試すとうまくいった。

最後に

Expoはとても便利だが提供してくれるAPIをしっかり理解して使いこなす必要がある。
nativeでのファイルの扱いや連携のいい勉強になった。
forumはとても頼りになります、ありがとうございました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?