(iOS + Firebase)无法将图像从UITableViewCell传递到下一个ViewController

时间:2018-12-05 08:30:28

标签: ios swift firebase uitableview

我有一个UITableView,其中的数据来自Firebase RealtimeDatabase。用户选择该行后,该行中的数据,即标题,说明和图像将被带到下一个ViewController。

我可以通过标题和说明,但不能通过图像。

这是我的UITableView代码:

import UIKit
import Firebase

class PostTable: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

    var posts = [Post]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView = UITableView(frame: view.bounds, style: .plain)
        view.addSubview(tableView)

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")
        var layoutGuide:UILayoutGuide!

        layoutGuide = view.safeAreaLayoutGuide

        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.reloadData()


        observePosts()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func observePosts() {
        let postsRef = Database.database().reference().child("Data")
        print(postsRef)
        postsRef.observe(.value, with: { snapshot in
            var tempPosts = [Post]()

            for child in snapshot.children{

                if let childSnapshot = child as? DataSnapshot,
                    let dict = childSnapshot.value as? [String:Any],
                    let title = dict["title"] as? String,
                    let logoImage = dict["image"] as? String,
                    let url = URL(string:logoImage),
                    let description = dict["description"] as? String{


                    let userProfile = UserProfile(title: title, photoURL: url)
                    let post = Post(id: childSnapshot.key, title: userProfile, description: description, image: userProfile)
                    print(post)
                    tempPosts.append(post)
                }
            }

            self.posts = tempPosts
            self.tableView.reloadData()
        })
    }

    func getImage(url: String, completion: @escaping (UIImage?) -> ()) {
        URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
            if error == nil {
                completion(UIImage(data: data!))
            } else {
                completion(nil)
            }
            }.resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let postsInfo = posts[indexPath.row]
        print(postsInfo)

        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
        let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
        DvC.getName = postsInfo.title.title
        DvC.getDesc = postsInfo.description
//        DvC.getImg = postsInfo.title.photoURL
        self.navigationController?.pushViewController(DvC, animated: true)
    }
}

这是第二个ViewControler,其中包含帖子详细信息:

import UIKit

class PostTableDetailed: UIViewController {

    var getName = String()
    var getDesc = String()

    @IBOutlet weak var Name: UILabel!
    @IBOutlet weak var Description: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        Name.text! = getName
        Description.text! = getDesc     
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

我也有一些模型(Post,UserProfile)和服务(UserService和ImageService),请告诉我是否可以解决此问题。

3 个答案:

答案 0 :(得分:1)

如果有imageUrl,则只需将其从PostTable传递到PostTableDetailed并下载图像。

   // PostTable
       func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let postsInfo = posts[indexPath.row]
            print(postsInfo)

            let Storyboard = UIStoryboard(name: "Main", bundle: nil)
            let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
            DvC.getName = postsInfo.title.title
            DvC.getDesc = postsInfo.description
            DvC.getImg = postsInfo.photoURL
            self.navigationController?.pushViewController(DvC, animated: true)
        }

// PostTableDetailed
class PostTableDetailed: UIViewController {

    var getName = String()
    var getDesc = String()
    var imageUrl = ""

    @IBOutlet weak var Name: UILabel!
    @IBOutlet weak var Description: UILabel!
    @IBOutlet weak var imageView: UIImageView!


    override func viewDidLoad() {
        super.viewDidLoad()

        Name.text! = getName
        Description.text! = getDesc 
        updayeImage()    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

 private func updateImage() {
        URLSession.shared.dataTask(with: URL(string: self.imageUrl)!) { data, response, error in
            if error == nil, let data = data {
                imageView.image = UIImage(data: data)
            } 
            }.resume()
    }

}

任务完成时将显示图像。 因此,建议您在imageView中添加微调器。

答案 1 :(得分:1)

在PostDetail ViewController中这样做

import UIKit

class PostTableDetailed: UIViewController {

    var getName = String()
    var getDesc = String()
    var getImg = String()

    @IBOutlet weak var Name: UILabel!
    @IBOutlet weak var Description: UILabel!
    @IBOutlet weak var ImageContainer: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        Name.text! = getName
        Description.text! = getDesc    
        if let image = getImage(url: getImg) { (image)
            ImageContainer.image = image 
        }

    }

    override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
         // Dispose of any resources that can be recreated.
    }

    func getImage(url: String, completion: @escaping (UIImage?) -> ()) {
        URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
            if error == nil {
                completion(UIImage(data: data!))
            } else {
                completion(nil)
            }
        }.resume()
    }

}

答案 2 :(得分:0)

首先,您可以使用以下代码下载图像:

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {

func downloadImageWithUrlString(urlString: String) -> Void {

    if urlString.count == 0 {
        print("Image Url is not found")
        return
    }

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

    let request = URLRequest(url: URL(string: urlString)!)
    let dataTask = URLSession.shared.dataTask(with: request) {data, response, error in
        if error != nil { return }
        DispatchQueue.main.async {
            let downloadedImage = UIImage(data: data!)
            if let image = downloadedImage {
                imageCache.setObject(image, forKey: urlString as AnyObject)
                self.image = UIImage(data: data!)
            }
        }
    }
    dataTask.resume()
}
}

现在,如果您正在使用包含Title,Description和ImageUrlString的模型,则只需将选定的模型对象传递给下一个viewController。

在下一个ViewController中,只需调用相同的方法来下载您在第一个ViewController上使用的图像。您无需将映像从VC1传递到VC2,因为它可能尚未下载映像,您可以选择一行以在下一个VC上移动。

因此,这里传递模型对象并调用图像下载方法的简单操作。