简体   繁体   中英

issue with image cache in getting image back firebase swift iOS

在此输入图像描述 [ 在此输入图像描述 ][!I want load image from download url from firebase using image cache how can I can create an inheritance where my image gets loaded I guess I am missing OOP concept somewhere. my image view is swipe label, how too create an instance where I can display the image on my view.

import UIKit

import Firebase

class swipeLabelViewController: UIViewController {

@IBOutlet weak var UserAgeText: UILabel!


var user:User? {

    didSet {


        let userNameSwipe = user?.userName

        userNameLabel.text = userNameSwipe

        let userAgeSwipe = user?.userAge

        UserAgeText.text = userAgeSwipe

        guard let profileImageUrl = user?.profileImageUrl else { 

return } profileImageView.loadImage(with: profileImageUrl)

        print(profileImageUrl)

  //  let userFetchedImage = user?.profileImageUrl

     //   swipeLabel.image = userFetchedImage

       // self.swipeLabel.image = UIImage(contentsOfFile: profileImageUrl)

     }
}
var profileImageView: CustomImageView = {


    let iv = CustomImageView()


    return iv

}()


var imageI : UIImage!

// var swipepic = CustomImageView()

@IBOutlet weak var swipeLabel: UIImageView!


@IBOutlet weak var userNameLabel: UILabel!




override func viewDidLoad() {


    super.viewDidLoad()


   swipeLabel.image = imageI


    let gesture = UIPanGestureRecognizer(target: self, action: 

selector(wasDragged(gestureRecognizer:)))

 swipeLabel.addGestureRecognizer(gesture)



 fetchCurrentUserData() 


    }

// user model class``

class User {

// attributes getting users info  so i can set up  from  firebase





var userName:String!


var userAge:String!


var uid:String!


var profileImageUrl: String!

init (uid:String,dictionary:Dictionary) {

self.uid = uid

if let userName = dictionary [ "userName" ] as? String{


    self.userName = userName

}

if let userAge = dictionary [ "userAge" ] as? String{


    self.userAge = userAge
}

if let profileImageUrl = dictionary["profileImageURL"] as? String {

  self.profileImageUrl = profileImageUrl

}

}
}

// and lastly image cache class customImageView

import Foundation

import UIKit

var imageCache = String: UIImage

class CustomImageView: UIImageView {

var lastImgUrlUsedToLoadImage: String?


func loadImage(with urlString: String) {


    // set image to nil


    self.image = nil

    // set lastImgUrlUsedToLoadImage


    lastImgUrlUsedToLoadImage = urlString


    // check if image exists in cache


    if let cachedImage = imageCache[urlString] {


        self.image = cachedImage

        return
    }

    // url for image location




    guard let url = URL(string: urlString) else { return }





    // fetch contents of URL


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

        // handle error


        if let error = error {


            print("Failed to load image with error", 

error.localizedDescription) }

        if self.lastImgUrlUsedToLoadImage != url.absoluteString {

            return
        }

        // image data
        guard let imageData = data else { return }



        // create image using image data


        let photoImage = UIImage(data: imageData)



        // set key and value for image cache


        imageCache[url.absoluteString] = photoImage


        // set image

        DispatchQueue.main.async {

            self.image = photoImage
        }

        }.resume()
}

}

no errors I just can't see image on my swipelabel UIImage

You need to make a separate request to download the image from the url that firebase returns. Here is a playground example:

//: A SpriteKit based Playground

import PlaygroundSupport
import UIKit

enum ImageDownloadError: Error {
  case failedToConvertDataToImage
}

func dowloadImage(from url: URL, completion: @escaping (Result<UIImage, Error>) -> Void) {
  let task = URLSession.shared.dataTask(with: url) { data, response, error in
    guard let image = data.flatMap(UIImage.init(data:)) else {
      return completion (.failure(error ?? ImageDownloadError.failedToConvertDataToImage))
    }
    completion(.success(image))
  }.resume()
}

let imageView = UIImageView()
dowloadImage(from: URL(string: "https://res.cloudinary.com/demo/image/upload/sample.jpg")!) { [weak imageView] result in
  switch result {
  case .failure(let error):
    print(error.localizedDescription)
  case .success(let image):
    imageView?.image = image
  }
}
imageView.frame = .init(origin: .zero, size: .init(width: 300, height: 300))
PlaygroundPage.current.liveView = imageView
PlaygroundPage.current.needsIndefiniteExecution = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM