从Firebase下载图像到tableview

时间:2017-05-31 21:51:35

标签: ios swift firebase firebase-realtime-database

class ArtistModel {

    var id: String?
    var name: String?
    var genre: String?
    var img: String?

    init(id: String?, name: String?, genre: String?, img: String?){
        self.id = id
        self.name = name
        self.genre = genre
        self.img = img
    }
}

这是我的tableviewCell

class addArtistTableViewCell: UITableViewCell {

    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var lblGenre: UILabel!
    @IBOutlet weak var img: UIImageView!

和我的viewController

import UIKit
import Firebase
import FirebaseDatabase


class addArtistViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

     var refArtists: FIRDatabaseReference!

    @IBOutlet weak var textFieldName: UITextField!
    @IBOutlet weak var textFieldGenre: UITextField!
    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var labelMessage: UILabel!


    @IBOutlet weak var tableViewArtists: UITableView!

    //list to store all the artist
    var artistList = [ArtistModel]()

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        //getting the selected artist
        let artist  = artistList[indexPath.row]

        //building an alert
        let alertController = UIAlertController(title: artist.name, message: "Give new values to update ", preferredStyle: .alert)

        //the confirm action taking the inputs
        let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in

            //getting artist id
            let id = artist.id

            //getting new values
            let name = alertController.textFields?[0].text
            let genre = alertController.textFields?[1].text

            //calling the update method to update artist
            self.updateArtist(id: id!, name: name!, genre: genre!)
        }

        //the cancel action doing nothing
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

        //adding two textfields to alert
        alertController.addTextField { (textField) in
            textField.text = artist.name
        }
        alertController.addTextField { (textField) in
            textField.text = artist.genre
        }

        //adding action
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)

        //presenting dialog
        present(alertController, animated: true, completion: nil)
    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return artistList.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        //creating a cell using the custom class
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! addArtistTableViewCell

        //the artist object
        let artist: ArtistModel

        //getting the artist of selected position
        artist = artistList[indexPath.row]

        //adding values to labels
        cell.lblName.text = artist.name
        cell.lblGenre.text = artist.genre

        //returning cell
        return cell
    }

    @IBAction func buttonAddArtist(_ sender: UIButton) {

        addArtist()
    }

    override func viewDidLoad() {
        super.viewDidLoad()





        //getting a reference to the node artists
        refArtists = FIRDatabase.database().reference().child("artists")

        //observing the data changes
        refArtists.observe(FIRDataEventType.value, with: { (snapshot) in

            //if the reference have some values
            if snapshot.childrenCount > 0 {

                //clearing the list
                self.artistList.removeAll()

                //iterating through all the values
                for artists in snapshot.children.allObjects as! [FIRDataSnapshot] {
                    //getting values
                    let artistObject = artists.value as? [String: AnyObject]
                    let artistName  = artistObject?["artistName"]
                    let artistId  = artistObject?["id"]
                    let artistGenre = artistObject?["artistGenre"]
                    let artistImg = artistObject?["artistImg"]

                    //creating artist object with model and fetched values
                    let artist = ArtistModel(id: artistId as! String?, name: artistName as! String?, genre: artistGenre as! String?, img: artistImg as! String?)

                    //appending it to list
                    self.artistList.append(artist)
                }

                //reloading the tableview
                self.tableViewArtists.reloadData()
            }
        })
    }


    func addArtist(){
        //generating a new key inside artists node
        //and also getting the generated key
        let key = refArtists.childByAutoId().key

        //creating artist with the given values
        let artist = ["id":key,
                      "artistName": textFieldName.text! as String,
                      "artistGenre": textFieldGenre.text! as String,
                      ] //as [String : Any]

        //adding the artist inside the generated unique key
        refArtists.child(key).setValue(artist)

        //displaying message
        labelMessage.text = "Artist Added"
    }

    func updateArtist(id:String, name:String, genre:String){
        //creating artist with the new given values
        let artist = ["id":id,
                      "artistName": name,
                      "artistGenre": genre
        ]

        //updating the artist using the key of the artist
        refArtists.child(id).setValue(artist)

        //displaying message
        labelMessage.text = "Artist Updated"
    }

1 个答案:

答案 0 :(得分:0)

首先我要缓存图像。

    let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {

    func loadImageFromCacheWithUrlSting(urlString: String) {

        self.image = nil

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

        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print(error!)
            }

            DispatchQueue.main.async {

                if let downloadedImage = UIImage(data: data!) {
                    imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
                    self.image = downloadedImage
                }
            }
        }.resume()
    }

这样可以避免每次加载视图时下载图像。然后将这样的内容添加到cellForRow

if let artistImage = dictionary["img"] as? String {
cell?.artistImageView.loadImageFromCacheWithUrlSting(urlString: artistImage)
}