【问题标题】:How to save a text file in external storage in ios using flutter?如何使用flutter将文本文件保存在ios的外部存储中?
【发布时间】:2019-08-08 18:38:49
【问题描述】:

我创建了一个应用程序,用户可以在其中创建文本文件并将其保存在 Android 的本地存储中。我使用了 path_provider 包,它提供了 getExternalStorageDirectory() 将数据保存在外部存储中。但是对于 ios,我找不到相同的。 getExternalStorageDirectory() 不支持 ios。

我想保存文件,以便用户以后可以从 Files 应用程序 中的 ios.

访问该文件
Future<String> get _localPath async{
var dir = await getExternalStorageDirectory();

  return dir.path;
}

Future<File> get _localFile async{
  final path = await _localPath;

  return File('$path/test.txt');
}

Future<File> writeData(String msg) async{
  final file = await _localFile;

  return file.writeAsString(msg);
}

以上代码适用于 Android(如果提供存储权限)。任何人都可以帮助我在 ios 中实现同样的目标。

【问题讨论】:

    标签: ios file dart flutter storage


    【解决方案1】:

    我已经使用下面的代码来解决这个问题。

    Directory directory = Platform.isAndroid
        ? await getExternalStorageDirectory() //FOR ANDROID
        : await getApplicationSupportDirectory(); //FOR iOS
    

    还添加@Gabrielhn 提到的那些文件

    【讨论】:

      【解决方案2】:

      作为恭维做@ni。回答,您必须启用这两个键。这是它应该看的:

      Xcode (info.plist):

      Info.plist on Xcode

      编辑器(info.plist):

      <key>LSSupportsOpeningDocumentsInPlace</key>
      <true/>
      <key>UIFileSharingEnabled</key>
      <true/>
      

      来源信息:

      在 iOS 11 及更高版本中,如果此键 LSSupportsOpeningDocumentsInPlaceUIFileSharingEnabled 键均为 YES,则本地文件提供程序将授予对应用程序 Documents 目录中所有文档的访问权限.这些文档出现在“文件”应用程序和文档浏览器中。用户可以就地打开和编辑这些文档。

      来源:Apple developer - iOS keys

      【讨论】:

        【解决方案3】:

        您可以将文件保存在 NSDocumentsDirectory (getApplicationDocumentsDirectory()) 中,然后将其提供给用户。

        发件人:https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

        使用此目录来存储用户生成的内容。该目录的内容可以通过文件共享提供给用户;因此,他的目录应该只包含您可能希望向用户公开的文件。

        要让用户可以使用该目录,您需要打开“your_app/ios/Runner.xcworkspace”下的 Xcode 项目。然后打开Runner目录下的Info.plist文件,添加两行key为UIFileSharingEnabledLSSupportsOpeningDocumentsInPlace。将两个键的值设置为YES

        如果您现在打开“文件”应用并点击“在我的 iPhone 上”,您应该会看到一个包含您的应用名称的文件夹。

        【讨论】:

        • 感谢答案,但这个解决方案的问题是用户还可以访问所有其他文件,如 db 和 json 文件。有没有办法只拒绝访问这些?
        • 谢谢!它帮助了我
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-02
        • 1970-01-01
        • 2020-03-24
        • 2011-12-14
        • 1970-01-01
        • 2021-12-10
        相关资源
        最近更新 更多