Advertisement
Guest User

load image

a guest
Nov 13th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.16 KB | None | 0 0
  1. //
  2. //  ViewController.swift
  3. //  MyToast
  4. //
  5. //  Created by hackeru on 13/11/2019.
  6. //  Copyright © 2019 hackeru. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. class ViewController: UIViewController {
  12.     let charuf="https://images.unsplash.com/photo-1484557985045-edf25e08da73?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=967&q=80"
  13.    
  14.    let neoShark="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/what-is-baby-shark-1548869443.jpg?crop=0.526xw:1.00xh;0.342xw,0&resize=768:*"
  15.     @IBOutlet weak var neoButton: UIImageView!
  16.     override func viewDidLoad() {
  17.         super.viewDidLoad()
  18.         // Do any additional setup after loading the view, typically from a nib.
  19.        
  20.     }
  21.  
  22.     @IBAction func btnHelp(_ sender: Any) {
  23.         //Toast.show(message: "Please help me", controller: self)
  24.         neoButton.loadImageUsingCache(withUrl: neoShark)
  25.     }
  26.    
  27. }
  28.  
  29. let imageCache = NSCache<NSString,UIImage>()
  30.  
  31. extension UIImageView{
  32.    
  33.     func loadImageUsingCache(withUrl urlString:String){
  34.         let url = URL(string: urlString)
  35.         if url == nil {return}
  36.         self.image = nil
  37.        
  38.         //check for cached images
  39.         if let cachedImage = imageCache.object(forKey: urlString as NSString){
  40.             self.image = cachedImage
  41.             return
  42.         }
  43.        
  44.         let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView.init(style: .gray)
  45.         self.addSubview(activityIndicator)
  46.         activityIndicator.startAnimating()
  47.         activityIndicator.center = self.center
  48.        
  49.         //if not , download image from url
  50.         URLSession.shared.dataTask(with: url!, completionHandler: {
  51.             (data, response, error) in
  52.             if error != nil {
  53.                 print (error!)
  54.                 return
  55.             }
  56.             DispatchQueue.main.async {
  57.                 if let image = UIImage(data: data!){
  58.                     imageCache.setObject(image, forKey: urlString as NSString)
  59.                     self.image=image
  60.                     activityIndicator.removeFromSuperview()
  61.                 }
  62.             }
  63.         }).resume()
  64.        
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement