GetFileFromApplicationUriAsync、CopyAsync、AsStreamForRead 未在 Uno 平台中实现。解决方法?

GetFileFromApplicationUriAsync, CopyAsync, AsStreamForRead not implemented in Uno Platform. Workarounds?

我尝试使用以下方法,但它们在 Uno (Android) 中都显示为 未实现。我能做什么?

有Xamarin.Essentials替代吗?

或其他 NuGet 包

或者我应该在每个平台上使用本地实现

是否可以直接在 Uno 中实施

var pdfFile = StorageFile.GetFileFromApplicationUriAsync(..);
pdfFile.CopyAsync(..);
(await pdfFile.OpenReadAsync()).AsStreamForRead(); // AsStreamForRead() not implemented

我正在使用 Uno.UI 的 v1.45.0。

Uno 尚未实现大多数 Windows.StorageFile API,因为大多数 System.IO 中有可用的替代方案,它们将跨平台工作。

但是,如果您尝试显示 pdf,目前没有跨平台选项。在 Android 上,显示 pdf 的最佳方式是启动 intent,在 iOS 上,可以在 WebView.

中显示 pdf

Android 的部分示例代码:

        public async Task Read(CancellationToken ct, string filePath)
        {
            var intent = new Intent(Intent.ActionView);

            var file = new Java.IO.File(filePath);
            var contentUri = Android.Support.V4.Content.FileProvider.GetUriForFile(ContextHelper.Current, _fileProviderAuthority, file);

            intent.SetFlags(ActivityFlags.GrantReadUriPermission);
            intent.SetDataAndType(contentUri, "application/pdf");

            StartActivity(intent);
        }

iOS 的部分示例代码:

                    <ios:WebView 
                                 Source="{Binding FilePath}"
                                 HorizontalAlignment="Stretch"
                                 VerticalAlignment="Stretch" />

作为大卫·奥利弗

Uno hasn't implemented most of the Windows.StorageFile APIs, as for the most part there are alternatives available in System.IO, which will work cross-platform.

所以...

  1. 从应用程序包打开文件,我们可以将其构建操作设置为Embedded Resource而不是Content。我们可以使用以下代码代替 StorageFile.GetFileFromApplicationUriAsync() 方法:

    public Stream GetStreamFromResourceFile(string filename, Type callingType = null)
    {
        var assembly = (callingType ?? GetType()).Assembly;
        string foundResourceName = assembly.GetManifestResourceNames().FirstOrDefault(r => r.EndsWith(filename, StringComparison.InvariantCultureIgnoreCase));
        if (foundResourceName == null)
            throw new FileNotFoundException("File was not found in application resources. Ensure that the filename is correct and its build action is set to 'Embedded Resource'.", filename);
        return assembly.GetManifestResourceStream(foundResourceName);
    }
    
  2. 复制一个文件

    await pdfFile.CopyAsync(..);
    

    我们改为:

    await pdfFile.CopyToAsync(newFile);
    
  3. 并获取以供读取

    (await pdfFile.OpenReadAsync()).AsStreamForRead();
    

    我们使用:

    File.OpenRead(pdfFile);
    

所以最后我们有:

        string filename = "File.pdf";
        var pdfFile = GetStreamFromResourceFile(filename, GetType());
        string newFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
        using (var newFile = File.Create(newFilePath))
        {
            await pdfFile.CopyToAsync(newFile);
        }

        var fileStream = File.OpenRead(newFilePath);