for rent for rent - 1 month ago 6
PHP Question

What is the best way to get an image from a server by Swift?

I have an image in my website's server and i want to get it by Swift.Usually i just send data through PHP to Swift using HTTP Requests,but i don't know how to send an image.How can i do it?

Answer Source

This is my download image function, you just need the download URL:

let imageCache = NSCache<AnyObject, AnyObject>()

func downloadImageFromURL(string: String) -> UIImage {

    if let cachedImage = imageCache.object(forKey: string as AnyObject) as? UIImage {

        return cachedImage

    } else {

        let data = NSData(contentsOf: URL(string: string)!)
        return UIImage(data: data! as Data)!

    }

}

You simply call: let image = downloadImageFromURL("yourURL")

EDIT

This is a version for downloading images directly into the imageView that I have used before; it's a different approach, maybe it loads faster:

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {


func downloadImage(from imgURL: String!) {

    self.image = nil

    // Check if there's an image in the cache 

    if let cachedImage = imageCache.object(forKey: imgURL as AnyObject) as? UIImage {
        self.image = cachedImage
        return
    }

    // Otherwise, download image from Firebase via URL-string

    let url = URLRequest(url: URL(string: imgURL)!)

    let task = URLSession.shared.dataTask(with: url) {
        (data, response, error) in

        if error != nil {
            print(error!)
            return
        }

        DispatchQueue.main.async {
            if let image = UIImage(data: data!) {
                imageCache.setObject(image, forKey: imgURL as AnyObject)
            }
            self.image = UIImage(data: data!)
        }

    }

    task.resume()
}
}