如何在生成时填充Documents文件夹 [英] How to populate Documents folder at build time

查看:42
本文介绍了如何在生成时填充Documents文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NativeScript 6.8 Javascript应用程序,可以下载更新的数据文件。我发现在iOS上我无法在app文件夹中创建文件。(至少,在发布版本中是可以的;在调试版本中是可以的。)我可以更改代码以从Documents文件夹读取数据文件,但是如何在构建时使用原始数据文件预先填充Documents文件夹?我不希望在运行时复制所有数据文件。

或者,我是否误解了iOS发布版本中不能在app文件夹(或子文件夹)中创建文件的限制?

推荐答案

在iOS上实时更新文件比人们预期的要复杂得多。因此,是的,您需要从Documents文件夹访问实时更新的文件,而不是将文件备份到iCloud,并处理大量的计时条件,例如,就在将文件的初始副本复制到Documents文件夹之前运行的实时更新(看起来不太可能,但我在测试时看到过这种情况)。

我已经在下面包含了我开发的函数。对于上下文,当我发现在线文件需要实时更新时,我会使用appSetting将文件的日期保存为字符串(保存为值会降低精度)。

该函数并不完美,但目前,它可以完成工作。我从NativeScript 6.8 JavaScript项目中的app.js调用它。

/**
* Copy files in app/files folder to Documents folder so they can be updated 
*/
async function copyFilesToDocuments() {

  let filesCopied = appSettings.getBoolean("copyFilesToDocuments", false);

  if (!filesCopied) { // only copy files on first invocation

    let filesFolder = fs.knownFolders.currentApp().getFolder("files"); // Folder object 
    let documentsFolder = fs.knownFolders.documents(); // Folder object 
  
    let fileEntities = await filesFolder.getEntities();
  
    for (entity of fileEntities) {
      let sourceFile = fs.File.fromPath(entity.path);
      let targetFilePath = fs.path.join(documentsFolder.path, entity.name);
      let targetDate = parseInt(appSettings.getString(entity.name, "0"), 10); // live-update date or 0 

      if (fs.Folder.exists(targetFilePath) && targetDate > global.dataDate ) { // if file has been live-updated 
        console.log("app.js copyFilesToDocuments: file '" + entity.name + "' skipped to avoid overwrite. ");
        continue; // don't overwrite newer file 
      }

      appSettings.remove(entity.name); // remove any live-update timestamp
      let targetFile = fs.File.fromPath(targetFilePath);
      let content = await sourceFile.read();
      try {
        await targetFile.write(content);
        if (platform.isIOS) {
          // Prevent file from being backed up to iCloud
          // See https://stackoverflow.com/questions/58363089/using-nsurlisexcludedfrombackupkey-in-nativescript
          // See https://stackoverflow.com/questions/26080120/cfurlcopyresourcepropertyforkey-failed-because-passed-url-no-scheme
          NSURL.fileURLWithPath(targetFilePath).setResourceValueForKeyError(true, NSURLIsExcludedFromBackupKey);
        }
        // console.log("app.js copyFilesToDocuments file copied: " + entity.name);
      } catch(e) {
        console.warn("app.js copyFilesToDocuments error: " + e);
        //TODO:  app will fail at this point with some files not found :-(
      } // end catch
    } // end for
    appSettings.setBoolean("copyFilesToDocuments", true);
  } // end files not yet copied
} // end copyFilesToDocuments

这篇关于如何在生成时填充Documents文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆