Ashley
Ashley

Reputation: 519

swift show alert with custom cell

I have a custom cell. It has an UIImageView and a button. When I click the button, my app will save my image to Photo Album and show an result alert.

Here my code:

@IBAction func saveImage(sender: UIButton) {
        UIImageWriteToSavedPhotosAlbum(self.photo.image!, self, "saveImageToLibrary:didFinishSavingWithError:contextInfo:", nil)
    }

func saveImageToLibrary(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
    let vc = ViewController()
    if error == nil {
        let ac = UIAlertController(title: "Saved!", message: "Image has been saved to your photos.", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        vc.presentViewController(ac, animated: true, completion: nil)
    } else {
        let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        vc.presentViewController(ac, animated: true, completion: nil)
    }
}

But when I click my Save button in tableview, it saves image successfully with an warming:

Warning: Attempt to present <UIAlertController: 0x7fa452f74ee0> on <Test.ViewController: 0x7fa452f56f40> whose view is not in the window hierarchy!

How can I call an alert from custom cell?

Upvotes: 2

Views: 3139

Answers (1)

TPlet
TPlet

Reputation: 948

I would solve this using a delegate: In your custom Cell add this code

var delegate: UIViewController?

and in your tableView(tableView: cellForRowAtIndexPath) add this line:

cell.delegate = self

and finally in your saveImageToLibrary implementation replace the vc by delegate?. The ? is because you created the delegate as an optional.

Upvotes: 1

Related Questions