display image from url swift
let imageCache = NSCache<AnyObject, AnyObject>() extension UIImageView { func setImage(from url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) { contentMode = mode if let imageFromCache = imageCache.object(forKey: url as AnyObject) { self.image = imageFromCache as? UIImage return } URLSession.shared.dataTask(with: url) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let imageToCache = UIImage(data: data) else { return } DispatchQueue.main.async() { imageCache.setObject(imageToCache, forKey: url as AnyObject) self.image = imageToCache } }.resume() } func setImage(from link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { guard let url = URL(string: link) else { return } setImage(from: url, contentMode: mode) } }
swift image
//Make sure the image you want to show is imported into your "Assets.xcassets" file. Image("dog")
image view in swift
// First step: let imageView = let imageView = UIImageView(image: UIImage(named: "your image name")!) imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200) view.addSubview(imageView) // Second step: var imageView : UIImageView imageView = UIImageView(frame:CGRectMake(10, 50, 100, 300)); imageView.image = UIImage(named:"image.jpg") self.view.addSubview(imageView)
how to add an image in swift
//The first step is to rename the image you want to add into your xcode project //Then, drag the picture to the Assets.xcassests folder. //Next, use the Image struct and init(name) to display the picture //For example, if your picture in the Assets.xcassests folder is named daddy, then to get the picture, use Image("daddy") //There are more modifiers to the Image but that will not be discussed here
Source: www.simpleswiftguide.com