c# - Xamarin.iOS 获取附加在电子邮件中的图像文件路径
问题描述
我有一种方法可以获取之前下载到手机图库中的图像并将其附加到电子邮件中。这在 Android 中完美运行。但是在 iOS 中,我无法弄清楚如何获取我刚刚保存到图库中的图像的文件路径。
这是到目前为止的 Xamarin.IOS 代码:
public string SaveToGallery(byte[] imgBytes, string fileName)
{
var imageData = new UIImage(NSData.FromArray(imgBytes));
string filePath = string.Empty;
NSError errorMsg = null;
imageData.SaveToPhotosAlbum((image, error) =>
{
if (error != null)
errorMsg = error;
});
if (errorMsg is null)
{
return string.Empty;
}
return filePath;
}
我正在使用 Xamarin.Essentials.Email 创建电子邮件,EmailAttachment 类将字符串 fullPath 作为参数。SaveImg() 方法使用 DependencyService 调用上面保存图像的 Xamarin.iOS 代码,并应返回保存图像的文件路径:
private static async Task EmailImg(List<string> recipients, string subject, string body, byte[] imgBytes)
{
try
{
var message = new EmailMessage
{
To = recipients,
Subject = subject,
Body = body,
//Cc = ccRecipients,
//Bcc = bccRecipients
};
string filePath = string.Empty;
if (imgBytes != null)
{
filePath = await SaveImg(imgBytes);
if (!string.IsNullOrEmpty(filePath))
message.Attachments.Add(new EmailAttachment(filePath));
}
await Email.ComposeAsync(message);
}
catch (FeatureNotSupportedException fbsEx)
{
await Application.Current.MainPage.DisplayAlert("Oops", "Email function not supported on this device", "Okay");
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Oops", "Failed to pass details to email client", "Okay");
}
}
解决方案
您无需将图像保存到图库。您可以将它们保存到本地文件夹并使用该本地文件夹filePath
添加附件。(您可以在 iOS 和 Android 上使用此方法)
这是示例:
private async void EmailImg(List<string> recipients, string subject, string body, byte[] imgBytes)
{
try
{
var message = new EmailMessage
{
To = recipients,
Subject = subject,
Body = body,
//Cc = ccRecipients,
//Bcc = bccRecipients
};
var fileName = "myImage.jpg";
var filePath = Path.Combine(FileSystem.AppDataDirectory, fileName);
File.WriteAllBytes(filePath, imgBytes);
if (imgBytes != null)
{
if (!string.IsNullOrEmpty(filePath))
message.Attachments.Add(new EmailAttachment(filePath));
}
await Email.ComposeAsync(message);
}
catch (FeatureNotSupportedException fbsEx)
{
await Application.Current.MainPage.DisplayAlert("Oops", "Email function not supported on this device", "Okay");
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Oops", "Failed to pass details to email client", "Okay");
}
}
如果将图像保存到 iOS 画廊,则无法获取当时的路径。你只有在选择它时才能得到路径,看这个。
推荐阅读
- git - 无法推送到 Github 或 Bitbucket
- javascript - MVC - 添加在客户端创建的新记录
- mule - Mulesoft 自定义策略转换扩展
- google-tag-manager - 通过 Google Tag Manager 中的计算组合两个数据层变量
- android - 具有固定纵横比的 ConstraintLayout 链
- perl - 在linux上自动替换主机密钥
- api - linkedin "此应用程序不允许创建应用程序令牌"
- javascript - CSS 将相似项目设置为与屏幕上最高项目相同的高度
- python-3.x - 切换音乐开/关 Kivy
- c++ - 检查 nullptr 导致 CTD