从URL保存照片的最佳方式,swift [关闭]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从URL保存照片的最佳方式,swift [关闭]相关的知识,希望对你有一定的参考价值。

如何保存照片?在swift中哪种方式更好?

    @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)
    }   
}
答案

这应该适合你。使用this answerLeo Dabus作为getDataFromUrl方法从URL获取数据:

不要忘记将密钥Privacy - Photo Library Additions Usage Description添加到您的Info.plist,并附上说明,向用户解释您需要访问照片库的原因。

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

    }
}

以上是关于从URL保存照片的最佳方式,swift [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

如何在 swift 4 中从图像选择器获取照片本地 url

如何在 Swift 中从相机或照片库加载图像 [关闭]

哪种是临时保存原始数据的最佳方式? [关闭]

使用swift在iOS上本地保存和检索包含所有元数据的照片

Swift - 保存并稍后获取大量数据的最佳方式

在 iOS (Swift) 中使用后台位置更新的最佳方式 [关闭]