如何解决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图库,那个时候你是拿不到路径的。只有选了才能拿到路径,看这个。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。