在 iOS 中,要将图像显示到图库中,您必须编写额外的代码,因为仅使用 File.WriteAllBytes 不会调用本机 UIImageWriteToSavedPhotosAlbum API 来将其显示在相册中。
为此,您必须按如下方式调用此 API:
做一个依赖服务:
public interface ISavePhotosToAlbum
{
void SavePhotosWithFilePath(String Path);
}
现在添加一个原生类并执行以下操作:
[assembly: Dependency(typeof(SaveToAlbum))]
namespace SavePhotosDemo.iOS
{
public class SaveToAlbum : ISavePhotosToAlbum
{
public void SavePhotosWithFilePath(String Path)
{
using (var url = new NSUrl (Path))
using (var data = NSData.FromUrl (url))
var image = UIImage.LoadFromData (data);
image.SaveToPhotosAlbum((img, error) =>
{
if (error == null)
{//Success }
else
{//Failure}
});
}
}
}
然后按如下方式使用这个依赖服务:
DependencyService.Get<ISavePhotosToAlbum>().SavePhotosWithStream(imageUrl);
另外,请通过在 OnPlatform if 语句中添加此依赖项服务调用,仅针对 ios 添加此依赖项服务调用。
更新
使用以下代码在照片库中添加自定义相册:
void AddAssetToAlbum(UIImage image, PHAssetCollection album, string imageName)
{
try
{
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
{
// Create asset request
var creationRequest = PHAssetCreationRequest.CreationRequestForAsset();
var options = new PHAssetResourceCreationOptions
{
OriginalFilename = imageName
};
creationRequest.AddResource(PHAssetResourceType.Photo, image.AsJPEG(), options);
// Change asset request (change album by adding photo to it)
var addAssetRequest = PHAssetCollectionChangeRequest.ChangeRequest(album);
addAssetRequest.AddAssets(new PHObject[] { creationRequest.PlaceholderForCreatedAsset });
}, (success, error) =>
{
if (!success)
Console.WriteLine("Error adding asset to album");
});
}
catch (Exception ex)
{
string h = ex.Message;
}
}
请注意您使用PHPhotoLibrary.RequestAuthorization 方法请求授权,因为我们需要请求访问权限才能使用照片库。另外,自 iOS 10 起及以上版本我们还需要在目标 .plist 文件中为“Privacy - Photo Library Usage Description”添加访问条目:
<key>NSPhotoLibraryUsageDescription</key>
<string>Access to photos is needed to provide app features</string>
更新
最后,添加以下内容开始在文件应用程序中显示文档:
<key>UIFileSharingEnabled</key> <true/> <key>LSSupportsOpeningDocumentsInPlace</key> <true/>