首页 > 解决方案 > “使用 Xamarin 表单将照片保存在 iPhone 或 iPad 的相册中”但是 PCL 已弃用

问题描述

我正在尝试解决此 Stack Overflow 帖子中的问题“https://stackoverflow.com/questions/49291495/save-photos-in-photo-albums-of-iphone-or-ipad-using-xamarin -形式”。但是,不推荐使用 PCL 后的答案。什么是更新的答案?谢谢你。

标签: xamarin.formsxamarin.ios

解决方案


但是,不推荐使用 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);
            }
        }
    }
}

推荐阅读