如何使用flutter在ios的外部存储中保存文本文件?

Kes*_*hav 16 storage file ios dart flutter

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

我想保存文件,以便用户以后可以从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);
}
Run Code Online (Sandbox Code Playgroud)

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

ni.*_*ni. 23

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

来自:https : //developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

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

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

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

  • 感谢您的回答,但此解决方案的问题是用户还可以访问所有其他文件,例如 db 和 json 文件。有没有办法只拒绝这些访问? (9认同)
  • @nani 这些应该放在库目录中,而不是文档目录中 (3认同)

jam*_*mes 18

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

Directory directory = Platform.isAndroid
    ? await getExternalStorageDirectory() //FOR ANDROID
    : await getApplicationSupportDirectory(); //FOR iOS
Run Code Online (Sandbox Code Playgroud)

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

  • 这就引出了一个问题:Android 不支持 getApplicationSupportDirectory() 吗?... https://pub.dev/documentation/path_provider/latest/path_provider/getApplicationSupportDirectory.html 意味着它在两个平台上都可用。为什么不在两个平台上使用应用程序支持目录?换句话说:为什么要为andriod使用ext存储目录? (3认同)

小智 15

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

Xcode (info.plist):

Xcode 上的 Info.plist

编辑器(info.plist):

<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
Run Code Online (Sandbox Code Playgroud)

资料来源:

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

来源:Apple 开发人员 - iOS 密钥