UIImageWriteToSavedPhotosAlbum与iOS 9中的UIImageView

时间:2015-09-29 15:33:25

标签: ios swift uiimageview uiimage swift2

我正在努力开发一个"保存图像"我的应用程序中的功能,用户可以从他们的照片库中的TableView保存图像。我在社区中搜索了很多,而且我找不到与我的案子有关的任何内容,所以我要解释一下:

正如在官方指南中所说,UIImageWriteToSavedPhotosAlbum必须接收UIImage,所以我试图将我的UIImageView转换为UIImage以实现这一点,但是当一切都很好没有警告或错误时,APP正在显示错误,说明"数据不可用"。

我需要做些什么才能让它发挥作用?我发错了数据吗?

<UIImage: 0x16db7780>, {400, 345}

这是我的代码:

func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {

    if error == nil
    {
        let ac = UIAlertController(title: "Imagen guardada", message: "", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(ac, animated: true, completion: nil)
    }
    else
    {
        let ac = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(ac, animated: true, completion: nil)
    }
}


@IBAction func handleGesture(sender: AnyObject) {

    self.votarFrame?.hidden = true

    let guardarMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)

    var img:UIImage!

    img = self.productoImageView.image

    let saveImage = UIAlertAction(title: "Guardar imagen", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        UIImageWriteToSavedPhotosAlbum(img, self, "image:didFinishSavingWithError:contextInfo:", nil)
    })

    let cancelAction = UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.Cancel, handler: nil)

    guardarMenu.addAction(saveImage)
    guardarMenu.addAction(cancelAction)

    self.presentViewController(guardarMenu, animated: true, completion: nil)
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

在致电UIImageView之前,您需要拍摄UIImageWriteToSavedPhotosAlbum的快照。将以下扩展名添加到UIView并调用此函数:

func takeSnapshot() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.myImageView.bounds.size, false, UIScreen.mainScreen().scale);

    self.drawViewHierarchyInRect(self.myImageView.bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}