簡體   English   中英

(iOS + Firebase)無法將圖像從UITableViewCell傳遞到下一個ViewController

[英](iOS + Firebase) Unable to pass the Image to the next ViewController from a UITableViewCell

我有一個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),請告訴我是否可以解決此問題。

如果您有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。

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

}

首先,您可以使用以下代碼下載圖像:

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上移動的行。

因此,這里傳遞模型對象並調用圖像下載方法的簡單操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM