下载未保存在Xamarin Forms iOS本地文件夹中的照片
galary iOS上未显示保存的图像(在Android上运行良好,但在iOS上运行不正常) 这是我将图像保存到设备的代码下载未保存在Xamarin Forms iOS本地文件夹中的照片,xamarin,xamarin.forms,xamarin.ios,Xamarin,Xamarin.forms,Xamarin.ios,galary iOS上未显示保存的图像(在Android上运行良好,但在iOS上运行不正常) 这是我将图像保存到设备的代码 public void SavePicture(string name, byte[] data, string location = "Downloads") { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
public void SavePicture(string name, byte[] data, string location = "Downloads")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documentsPath = Path.Combine(documentsPath, location);
Directory.CreateDirectory(documentsPath);
string filePath = Path.Combine(documentsPath, name);
File.WriteAllBytes(filePath, data); // writes to local storage
}
还允许在info.plist上使用照片权限
隐私-照片库使用说明
执行此代码后,我无法在iOS设备上找到保存的照片
如何解决此问题?在iOS中,要将图像显示到图库中,您必须像使用
文件一样编写其他代码。WriteAllBytes
不会调用本机UIImageWriteToSavedPhotosAlbum
API将其显示在相册中
为此,您必须按如下方式调用此API:
DependencyService.Get<ISavePhotosToAlbum>().SavePhotosWithStream(imageUrl);
创建依赖项服务:
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);
请务必使用PHPhotoLibrary.RequestAuthorization
方法请求授权,因为我们需要请求访问才能使用照片库。另外,从iOS 10及以上版本开始,我们还需要在target.plist文件中添加一个访问条目,用于“隐私-照片库使用说明”:
NSPhotoLibraryUsageDescription
需要访问照片才能提供应用程序功能
使现代化
最后,添加以下内容开始在文件应用程序中显示文档:
<key>UIFileSharingEnabled</key> <true/> <key>LSSupportsOpeningDocumentsInPlace</key> <true/>
UIFileSharingEnabled LSSupportsOpeningDocumentsInPlace
将图像保存到LocalStorage与将其保存到照片库不同。你想做哪一个?实际上我想将所有文档下载到我指定的本地文件夹。你的代码应该可以做到这一点。有什么问题吗?您是否收到错误或异常?我没有收到任何异常,此代码已执行,但当我搜索下载文件时,我找不到该文件。我已使用此NSData,工作正常,但您能告诉我如何在Xamarin iOS中的文件夹中保存文档吗?您要将其保存到哪个特定文件夹?我想创建一个类似“MyDownloads”的文件夹,并将此文件保存在此处。那么如何执行此操作呢?在我的应用程序中,我显示了文档列表,当用户单击任何项目时,将该项目转换为字节数组并保存到本地文件夹。我的代码已执行,但在本地文件夹中找不到我保存的文档。这是因为您仅将其保存在文档目录中!
<key>UIFileSharingEnabled</key> <true/> <key>LSSupportsOpeningDocumentsInPlace</key> <true/>