Xamarin.Essentials 提供了一種共享本地檔案的機制。典型用例:
await Share.RequestAsync(new ShareFileRequest
{
Title = "Sharing a file...",
File = new ShareFile(pathToLocalFile),
});
pathToLocalFile- 包含必須共享的本地檔案的絕對路徑。
雖然此代碼在 Android 上完美運行,但在 iOS 上卻無法按預期運行。
在 iOS 上,“共享檔案”表只出現幾秒鐘,然后就消失了。
我該如何解決這個問題?
uj5u.com熱心網友回復:
我檢查了與此功能相關的Xamarin.Essentials 示例,并得出以下結論。
ShareFileRequest類具有PresentationSourceBounds應該設定為parent視圖元素的邊界。
應該從可見的視圖元素呼叫“共享檔案”功能,例如通過單擊頁面上的按鈕。從選單項呼叫此功能不起作用。
因此,我創建了一個頁面,并在頁面 xaml 中宣告了這樣的按鈕:
<Button Text="Click here to share the file..."
Command="{Binding ShareLocalFileCommand}"
CommandParameter="{Binding Source={RelativeSource Self}}" />
在頁面視圖模型中,我ShareLocalFileCommand這樣宣告:
public Command<View> ShareLocalFileCommand { get; }
在視圖模型建構式中,我已經ShareLocalFileCommand像這樣初始化了屬性:
ShareLocalFileCommand = new Command<View>(ExecuteShareLocalFileCommandAsync);
并且相關的方法已經這樣實作了:
private async void ExecuteShareLocalFileCommandAsync(View viewElement)
{
await Share.RequestAsync(new ShareFileRequest
{
Title = "Sharing local file...",
File = new ShareFile(LocalFilePath), // LocalFilePath contains path to local file to be shared
PresentationSourceBounds = GetAbsoluteBounds(viewElement)
});
}
private static System.Drawing.Rectangle GetAbsoluteBounds(View element)
{
Element looper = element;
var absoluteX = element.X element.Margin.Top;
var absoluteY = element.Y element.Margin.Left;
while (looper.Parent != null)
{
looper = looper.Parent;
if (looper is View view)
{
absoluteX = view.X view.Margin.Top;
absoluteY = view.Y view.Margin.Left;
}
}
return new System.Drawing.Rectangle((int)absoluteX, (int)absoluteY, (int)element.Width, (int)element.Height);
}
請注意,在單擊按鈕和呼叫await Share.RequestAsync()之間不應出現任何視圖元素出現和消失,例如確認對話框等。否則viewElement引數將作為null.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480356.html
標籤:C# xamarin xamarin.ios
