在将图像取回Firebase Swift iOS中图像缓存的问题

时间:2019-06-06 21:41:03

标签: ios swift firebase firebase-authentication

enter image description here [enter image description here] [!我想使用图像缓存从Firebase的下载URL加载图像,我如何才能在加载图像的地方创建继承,我想我在某个地方缺少OOP概念。我的图像视图是滑动标签,还如何创建一个实例,以便在视图上显示图像。

导入UIKit

导入Firebase

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 { 

返回}             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: 

选择器(wasDragged(gestureRecognizer:)))

 swipeLabel.addGestureRecognizer(gesture)



 fetchCurrentUserData() 


    }

//用户模型类``

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
}

如果让profileImageUrl = dictionary [“ profileImageURL”]表示为?字符串{

  self.profileImageUrl = profileImageUrl

}

}
}

//,最后是图像缓存类customImageView

导入基金会

导入UIKit

var imageCache =字符串:UIImage

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()
}

}

没有错误,我只是在swipelabel UIImage上看不到图像

1 个答案:

答案 0 :(得分:0)

您需要另外请求以从firebase返回的url下载图像。这是一个游乐场示例:

//: 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