Search code examples
iosswiftuiimagensurl

Best way to save photo from URL, swift


How to save photo? In swift Which way is better?

    @IBAction func savePhoto(_ sender: Any) {
        let imageData = UIImagePNGRepresentation(myImg.image!)
        let compresedImage = UIImage(data: imageData!)
        UIImageWriteToSavedPhotosAlbum(compresedImage!, nil, nil, nil)

        let alert = UIAlertController(title: "Saved", message: "Your image has been saved", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default)
        alert.addAction(okAction)
        self.present(alert, animated: true)
    }   
}

Solution

  • This should work for you. Used this answer from Leo Dabus for the getDataFromUrl method to get the data from the URL:

    Don't forget to add the key Privacy - Photo Library Additions Usage Description to your Info.plist with a description to explain the user why you need access to the photo library.

    enter image description here

    import UIKit
    
    class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
        @IBOutlet var imageView: UIImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
    
        func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
            URLSession.shared.dataTask(with: url) { data, response, error in
                completion(data, response, error)
            }.resume()
        }
    
    
        @IBAction func savePhoto(_ sender: UIButton) {
    
            let yourImageURLString = "https://scontent-frx5-1.cdninstagram.com/t51.2885-15/e35/22794197_139950336649166_440006381429325824_n.jpg"
    
            guard let yourImageURL = URL(string: yourImageURLString) else { return }
    
            getDataFromUrl(url: yourImageURL) { (data, response, error) in
    
                guard let data = data, let imageFromData = UIImage(data: data) else { return }
    
                DispatchQueue.main.async() {
                    UIImageWriteToSavedPhotosAlbum(imageFromData, nil, nil, nil)
                    self.imageView.image = imageFromData
    
                    let alert = UIAlertController(title: "Saved", message: "Your image has been saved", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "Ok", style: .default)
                    alert.addAction(okAction)
                    self.present(alert, animated: true)
                }
            }
    
        }
    }