如何使用Flutter在iOS上将文本文件保存到外部存储?

36

我创建了一个应用程序,用户可以在Android的本地存储中创建和保存文本文件。 我使用了 path_provider 软件包,该软件包提供了 getExternalStorageDirectory() 函数以将数据保存到外部存储器中。 但是,我无法找到相同的功能在 ios 上。在iOS上不支持 getExternalStorageDirectory() 函数。

我想要保存该文件,以便用户稍后可以从 Files app 中访问该文件在iOS上。enter image description here

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中实现相同的功能吗。


尝试使用此链接 https://dev59.com/EVIH5IYBdhLWcg3weOYr#74457977。 - Wai Yan
3个回答

53

你可以将文件保存在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

如果现在打开Files应用程序并单击“On My iPhone”,您应该会看到一个名为您的应用程序名称的文件夹。


9
谢谢您的回答,但这种解决方案的问题是用户也可以访问所有其他文件,例如db和json文件。有没有办法只拒绝对这些文件的访问? - nani
谢谢!它帮助了我。 - Andres Naranjo
3
@nani 这些应该放在库目录中,而不是文档目录中。 - BlueRaja - Danny Pflughoeft
但是当应用程序被卸载时,该文件夹也会被删除。 - appdev

33

作为对@ni的回答的补充,您必须启用两个键。应该看起来像这样:

Xcode(info.plist):

Xcode上的Info.plist

编辑器(info.plist):

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

源代码中的信息:

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

来源:苹果开发人员 - iOS键值


16

我已使用下面的代码来修复这个问题。

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

同时按照 @Gabrielhn 提到的,添加那些文件。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接