ios Capacitor -在我的应用中打开具有共享功能的文件时,由于缺少权限,Filesystem.readFile失败

ej83mcc0  于 2023-06-07  发布在  iOS
关注(0)|答案(1)|浏览(321)

我想使用共享功能在我的应用程序中打开一个文件(我尝试直接从文件系统共享文件)。这是我在app.module.ts(Angular)中的代码:

import {Plugins} from '@capacitor/core';
    const {Filesystem} = Plugins;

    App.addListener("appUrlOpen", async (appUrlOpen) =>
    {
       Filesystem.readFile({path: appUrlOpen.url})
         .then((contents) =>
         {
            const reader = new FileReader();
            reader.onload = () => this.myFileService.importFileFromFileSystem(reader.result as any);
            reader.readAsText(new Blob([atob(contents.data)]));
         }).catch(e => alert(e.errorMessage));
     });

一切正常,除了错误消息:
无法打开文件“blablabla”,因为您没有查看它的权限。
对象'appUrlOpen'看起来像这样:

{
  "iosOpenInPlace":"",
  "iosSourceApplication":"",
  "url":"file:\/\/\/private\/var\/mobile\/Containers\/Shared\/AppGroup\/E7BA70BF-BBAA-4050-9D07-A87E14D4FDEE\/File%20Provider%20Storage\/My%20App%20Name\/MyFolder\/my%20file.territory"
}

Info.plist:

<key>CFBundleDocumentTypes</key>
<array>
    <dict>
  <key>CFBundleTypeRole</key>
  <string>Editor</string>
  <key>CFBundleTypeIconFiles</key>
  <array>
    <string>Icon-22x29.png</string>
    <string>Icon-44x58.png</string>
    <string>Icon-64x64.png</string>
    <string>Icon-320x320.png</string>
  </array>
  <key>CFBundleTypeName</key>
  <string>My App</string>
  <key>CFBundleTypeExtensions</key>
  <array>
      <string>territory</string>
  </array>
  <key>LSIsAppleDefaultForType</key>
  <true/>
  <key>LSHandlerRank</key>
  <string>Alternate</string>
  <key>LSItemContentTypes</key>
  <array>
    <string>public.data</string>
  </array>
    </dict>
</array>
<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>

当我直接从电子邮件附件中打开文件时,此方法有效。但是当我直接点击文件并分享到我的应用程序时,它就不再工作了。这里的文件似乎来自“文件提供程序存储”。我该怎么做才能让它起作用?

1sbrub3j

1sbrub3j1#

我知道这条线已经有点旧了,但我有一个非常类似的问题。
问题似乎是@capacitor/filesystem(5.0.2)插件在加载文件之前和之后都没有调用url.startAccessingSecurityScopedResource()(这对某些目录来说似乎是必要的)。在apple开发者论坛或here中查看this讨论。
这是不可能通过JS/TS做到这一点。
在插件开发人员更改此设置之前,您可以在/filesystem/ios/Plugin/Filesystem.swift上编辑插件:

[...]

public func readFile(at fileUrl: URL, with encoding: String?) throws -> String {
    fileUrl.startAccessingSecurityScopedResource()
    if encoding != nil {
        let data = try String(contentsOf: fileUrl, encoding: .utf8)
        fileUrl.stopAccessingSecurityScopedResource()
        return data
    } else {
        let data = try Data(contentsOf: fileUrl)
        fileUrl.stopAccessingSecurityScopedResource()
        return data.base64EncodedString()
    }
}

[...]

相关问题