Save Drawing to Gallery in Swift 5

I am trying to save a drawing to my photo gallery but it’s not saving. Here is the code I am using to draw over UIImageView . Save right func saves the photo.

                  var nextPage = UIButton()
      var clear = UIButton()
         var submitToDB = UIButton()
        var drawPlace = UIImageView()
         var myLayer = CALayer()
           var path = UIBezierPath()
         var startPoint = CGPoint()
        var touchPoint = CGPoint()

      func addArrowImageToButton(button: UIButton, arrowImage:UIImage = #imageLiteral(resourceName: "bb") ) {
let btnSize:CGFloat = 32
let imageView = UIImageView(image: arrowImage)
let btnFrame = button.frame    
button.bringSubviewToFront(imageView)
        }

     override func viewDidAppear(_ animated: Bool) {    
self.addArrowImageToButton(button: submitToDB)
     }

           func setup(){
submitToDB.layer.cornerRadius = 0
drawPlace.clipsToBounds = true
drawPlace.isMultipleTouchEnabled = false
        }

        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
             {
let touch = touches.first
if let point = touch?.location(in: drawPlace){
    startPoint = point

}
      }

     override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let point = touch?.location(in: drawPlace){
    touchPoint = point
}

path.move(to: startPoint)
path.addLine(to: touchPoint)
startPoint = touchPoint
draw()
            }

func draw() {
let strokeLayer = CAShapeLayer()
strokeLayer.fillColor = nil
strokeLayer.lineWidth = 5
strokeLayer.strokeColor = UIColor.blue.cgColor
strokeLayer.path = path.cgPath
drawPlace.layer.insertSublayer(strokeLayer, below: myLayer)
drawPlace.setNeedsDisplay()
}

override func viewDidLoad() {
super.viewDidLoad()
setup()
draw()
}

func save() {
guard let selectedImage = drawPlace.image else {
print(“Image not found!”)
return
}
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}

//MARK: - Add image to Library
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
showAlertWith(title: “Save error”, message: error.localizedDescription)
} else {
showAlertWith(title: “Saved!”, message: “Your image has been saved to your photos.”)
}
}

func showAlertWith(title: String, message: String){
let ac = UIAlertController(title: title, message: message, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: “OK”, style: .default))
present(ac, animated: true)
}

@objc func moveRight() {
save()
}

@timswift Do you still have issues with this?

This topic was automatically closed after 166 days. New replies are no longer allowed.