xamarin.forms - “使用 Xamarin 表单将照片保存在 iPhone 或 iPad 的相册中”但是 PCL 已弃用
问题描述
我正在尝试解决此 Stack Overflow 帖子中的问题“https://stackoverflow.com/questions/49291495/save-photos-in-photo-albums-of-iphone-or-ipad-using-xamarin -形式”。但是,不推荐使用 PCL 后的答案。什么是更新的答案?谢谢你。
解决方案
但是,不推荐使用 PCL 后的答案。
实际上,您只需要在 Share Projects 中做同样的事情。DependencyService在 Xamarin.Forms 中可用,您可以参考https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction。
在表格中
public interface ISavePhotosToAlbum
{
void SavePhotosWithStream(string name, Stream data);
}
在 iOS 中
[assembly: Dependency(typeof(SaveToAlbum))]
namespace xxx.iOS
{
public class SaveToAlbum : ISavePhotosToAlbum
{
public void SavePhotosWithStream(string name,Stream stream)
{
var imageData = NSData.FromStream(stream);
var image = UIImage.LoadFromData(imageData);
image.SaveToPhotosAlbum((img, error) =>
{
});
}
}
}
并在info.plist中添加以下代码
<key>NSCameraUsageDescription</key>
<string>App need to access your camera</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>App need to access your albums</string> // new in iOS 11 and later
<key>NSPhotoLibraryUsageDescription</key>
<string>App need to access your albums</string>
另外,如果你想在Android中实现它
在安卓中
[assembly: Dependency(typeof(SaveToAlbum))]
namespace xxx.Droid
{
public class SaveToAlbum : ISavePhotosToAlbum
{
public void SavePhotosWithStream(string name,Stream stream)
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documentsPath = Path.Combine(documentsPath, "Orders", temp);
Directory.CreateDirectory(documentsPath);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath , FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
}
}
推荐阅读
- azure-cognitive-search - 如何通过 en.microsoft 分析器自定义数字标记化?
- dask - Dask 没有启动工人
- node.js - 如何使用 webpack 和无服务器框架将 bcrypt 捆绑在纱线工作区 monorepo 中?
- bash - 如何从 awk 的输入 FILENAME 变量中删除路径-basename 是否可用?
- android - 播放音乐的 Android 通知
- go - 如何在自定义文件中记录 fmt.Printf
- excel - 无法使用 Spring Boot 和 Apache POI 正确生成 Excel 文件
- mysql - 触发只允许 1 辆车
- ios - numberOfItemsInSection 被调用,但 cellForItemAt 未被调用 UICollectionViewController
- docker - 运行后缀容器时的错误输出