-1

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)
    }   
}
Woop
  • 99
  • 2
  • 11

1 Answers1

2

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)
            }
        }

    }
}
ronatory
  • 7,156
  • 4
  • 29
  • 49
  • Note that saving a JPEG file data as PNG would discard its image orientation info. Btw the method looks familiar getDataFromUrl https://stackoverflow.com/revisions/aa305b0c-0b36-4c5d-a7f8-e0648d48b3c3/view-source – Leo Dabus Oct 29 '17 at 09:06
  • Just use the original jpeg data `unwrappedData`. btw you can keep the name `guard let data = data else { return }`. and use `data` `guard let image = UIImage(data: data) else { return }`. You shouldn't recompress it. `UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)` – Leo Dabus Oct 29 '17 at 09:15
  • Thanks for the hint. Indeed I used the answer to help the OP. Linked the answer – ronatory Oct 29 '17 at 09:15
  • Thanks again @LeoDabus – ronatory Oct 29 '17 at 09:24
  • Just use a single guard `guard let data = data, let imageFromData = UIImage(data: data) else { return }` – Leo Dabus Oct 29 '17 at 09:25
  • Hi. Thank U for reply. But in your example a static URL. But how made this code otherwise. Users paste their url and push button save. – Woop Oct 29 '17 at 09:27
  • @Woop not related to your question but `, handler: nil` and `, completion: nil` it is not required – Leo Dabus Oct 29 '17 at 09:29
  • Thanks again @LeoDabus – ronatory Oct 29 '17 at 09:33
  • @Woop Just add a text field and let the user paste there the image url, after that the user hits the save button and use this url instead of the static one – ronatory Oct 29 '17 at 09:34
  • @ronatory How it better to make? I didnt have such a big experience like U ((( – Woop Nov 02 '17 at 15:08
  • @Woop so in your screenshot you have already a text field. Just connect it to your code like you did with your image view. Than you can access the text of the text field to use it as the url. Just try it step by step. There are enough resources available for achieving your goal if you get stuck. Just search – ronatory Nov 02 '17 at 16:44
  • @ronatory Thank U you are best! – Woop Nov 02 '17 at 19:27
  • ur above code worked for me thanks and upvoted you – Dilip Tiwari Nov 13 '19 at 08:51