Search code examples
javascriptreact-nativebase64icloudreact-native-ios

Invalid encoded content of file from iCloud


I'm trying to read the content of a file that exists in iCloud, I tried using react-native-fs or react-native-fetch-blob and both libraries give the same result, so issue should be objetive c side, here is the code:

If I download the file manually and see the encoded content, I see correct data, an encoded string like this (thi's what I need):

U2FsdGVkX19qe+9FMvVqZBb7U6E3g1ynMqBwYUosBiOv7b5rF4/dVenIfPvWuiiCxEHhN5ILrYdBDnPLqcytWO8KjBV4XuN2MvduBDNiB090vhVJnq+7jtOQZ7+uXbEZil9j2zyVRxTul2RTs/Uh3HglbK3iiExypcDRPGtfGB/OPncuaYq5ggxzHu26Ii6VJcBvmQVyTth9JG9wNYa6l+2FlTTqcdp/0Xr8/KamERw8xje9qVnLExLL8xjG8JhBTlLwVaMGnIiLee20wGXNhzzHdUwEDnHDZAo8wzcFAnG7605h/6S6vG6p25+gsOnC2Tc2xwOigrAJC7TuPN81ZZC8pdkzwtgktG9I7tOxyfbdw87t8/jw/CbIJr4m8ckxQy/kvEy6aApeYmhlX9L0rQ==

BUT, when I read the content of the same file via filesystem using the above libs from react native I get this:

YnBsaXN0MDDTAQIDBAUGXE5TVVJMTmFtZUtleV8QEE5TVVJMRmlsZVNpemVLZXlfEBhOU1VSTEZpbGVSZXNvdXJjZVR5cGVLZXlcbG9ja3kuYmFja3VwEQGYXxAcTlNVUkxGaWxlUmVzb3VyY2VUeXBlUmVndWxhcggPHC9KV1oAAAAAAAABAQAAAAAAAAAHAAAAAAAAAAAAAAAAAAAAeQ== 

This string decoded is:

bplist00Ó\NSURLNameKey_NSURLFileSizeKey_NSURLFileResourceTypeKey\locky.backup_NSURLFileResourceTypeRegular/JWZy

WTF?

javascript code in both libs, same result

// react-native-fs
RNFS.readFile(backup.path, 'base64')
  .then((content) => {
    console.log(content, atob(content))
  })
  .catch((err) => {
    console.log('error', err)
  })

// react-native-fetch-blob
RNFetchBlob.fs.readFile(backup.path, 'utf8')
.then((data) => {
  console.log(data)
  // handle the data ..
})

Any advice? Thanks


Solution

  • Here's the issue, the first time your app adds a document’s on-disk representation to an iCloud (ubiquity) container, the system transfers the entire file or file package to the iCloud server, this task create the document’s metadata first, which includes information such as the document name, modification date, file size, and file type ("wrong" decoded string above) and then transfer the data (file).

    In Apple Docs

    In iOS, apps must ask the system (either explicitly or implicitly) to download the file. You implicitly download a file by trying to access that file by using methods in the NSFileCoordinator class, or you explicitly download the file by invoking the startDownloadingUbiquitousItemAtURL:error: method in the NSFileManager class

    and that's it, after call this methods, file can be read and contents is correct instead of metadata.