Skip to main content
 首页 » 编程设计

c#之如何在 ios 11 中保存到照片相册崩溃

2024年02月25日76JeffreyZhao

当我们运行下面提到的代码来下载图像并将其保存在照片库中时,它会在 iOS 11 中自动崩溃。请指导解决此问题。

try  
{ 
    string uri = "https://www.xamarin.com/content/images/pages/branding/assets/xamagon.png"; 
    using (var url = new NSUrl(uri)) 
    using (var data = NSData.FromUrl(url)) 
    UIImage.LoadFromData(data).SaveToPhotosAlbum((image, error) =>  
    { 
        var o = image as UIImage; 
        Console.WriteLine("error:" + error); 
    }); 
}  
catch(Exception exx)  
{ 
    throw exx; 
} 

请您参考如下方法:

Swift - 4, Xcode 9, IOS 11

信息.plist

  <key>NSPhotoLibraryUsageDescription</key> 
  <string> photos description.</string> 
 
  <key>NSPhotoLibraryAddUsageDescription</key> 
  <string> photos add description.</string> 

在按钮点击中添加代码

let url = "https://www.xamarin.com/content/images/pages/branding/assets/xamagon.png" 
        let data = try! Data(contentsOf: URL(string: url)!) 
 
        let image:UIImage = UIImage(data: data)! 
 
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil) 

@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) { 
        if let error = error { 
            // we got back an error! 
            let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert) 
            ac.addAction(UIAlertAction(title: "OK", style: .default)) 
            present(ac, animated: true) 
        } else { 
 
            let ac = UIAlertController(title: "Saved!", message: "The image has been saved to your photos.", preferredStyle: .alert) 
            ac.addAction(UIAlertAction(title: "OK", style: .default)) 
            present(ac, animated: true) 
        } 
    }