Home > Software engineering >  How to create UIImage object by url(swfit?)
How to create UIImage object by url(swfit?)

Time:08-08

I need to get avatar's pngData, and now I can get string value of avatar's url value. I know I can get pngData by this expression:

data = image.pngData()

but how to create a UIImage object by url? I didn't find any init method by using url. (I know there is a way to create ImageView object and using sd_webImage, but I know need UIImage object.)

CodePudding user response:

A method that get image from url

func getImageWithURL(urlString:String,completion: @escaping (_ image:UIImage?) -> Void) {
        guard let url = URL(string: urlString) else {
            print("invalid url")
            completion(nil)
            return
        }
        DispatchQueue.global().async {
            if let data = try? Data(contentsOf: url) {
                DispatchQueue.main.async {
                    let image = UIImage(data: data)
                    completion(image)
                }
            } else {
                print("Error: Url not conataining Image")
                completion(nil)
            }
        }
    }

and how you can call it

 getImageWithURL(urlString: "https://picsum.photos/200") { image in
        if let image = image {
            print("there is an image")
            let pngData = image.pngData()
            let jpegData = image.jpegData(compressionQuality: 1.0)
        }
    }
  • Related