简体   繁体   English

无法从 Cloud Firestore 数据库下载图像

[英]Cannot download image from Cloud Firestore database

This is the tableviewController which supposed to show image in each row but it does not.这是 tableviewController 应该在每一行中显示图像但它没有。 在此处输入图像描述 When I run the application on simulator it starts and displays the table view with titles and subtitles but images.当我在模拟器上运行应用程序时,它会启动并显示带有标题和副标题但图像的表格视图。 I also attach the screenshots of simulator with some prints and of the structure of the database.我还附上了模拟器的截图以及一些打印和数据库的结构。 在此处输入图像描述

import UIKit
import AVKit
import AVFoundation
import FirebaseFirestore
import Combine

class ListOfVideoLessonsTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    
    let pinchGesture = UIPinchGestureRecognizer()
    
    private var viewModel = VideosViewModel()
    private var cancellable: AnyCancellable?
    var player = AVPlayer()
    var playerViewController = AVPlayerViewController()
    
    @IBOutlet var table: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
 
        self.viewModel.fetchData()
        
        self.title = "Video Lessons"
        
        table.delegate = self
        table.dataSource = self
        
        cancellable = viewModel.$videos.sink { _ in
            DispatchQueue.main.async{
                
                self.table.reloadData()
        }
    }
}

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("videos count = ", viewModel.videos.count)
        return viewModel.videos.count
}
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let video = viewModel.videos[indexPath.row]
        tableView.tableFooterView = UIView()
        
        cell.textLabel?.text = video.name
        cell.detailTextLabel?.text = video.lessonName
        cell.accessoryType = .disclosureIndicator
        let image = UIImage(named: video.imageName)
        cell.imageView?.image = image
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor(named: "VideoLessonsCellHighlighted")
        cell.selectedBackgroundView = backgroundView
        cell.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
        cell.detailTextLabel?.font = UIFont(name: "Helvetica", size: 12)
        
        return cell
}
    

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
}
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        playVideo(at: indexPath)
}
    
     func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.contentView.backgroundColor = UIColor(named: "VideoLessonsCellHighlighted")
            cell.textLabel?.highlightedTextColor = UIColor(named: "textHighlighted")
            cell.detailTextLabel?.highlightedTextColor = UIColor(named: "textHighlighted")
    }
}

     func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.contentView.backgroundColor = nil
            
    }
}
    
        func playVideo(at indexPath: IndexPath){
            let selectedVideo = viewModel.videos[indexPath.row]
            let videoURL = URL(string: selectedVideo.fileURL)
            player = AVPlayer(url: videoURL!)
            playerViewController.player = player
            
            
          self.present(playerViewController, animated: true, completion: {
                self.playerViewController.player?.play()
        })
           
    }
}

This is the viewModel which I believe should download images and pass to the tableview cells.这是我认为应该下载图像并传递给 tableview 单元的 viewModel。

import Foundation
import FirebaseFirestore


class VideosViewModel: ObservableObject {

@Published var videos = [Video]()
private var db = Firestore.firestore()

func fetchData() {
    db.collection("videos").addSnapshotListener { [self] (querySnapshot, error) in
    guard let documents = querySnapshot?.documents else {
    print("No Documents")
    return
}

self.videos = documents.map { (queryDocumentSnapshot) -> Video in
    let data = queryDocumentSnapshot.data()
                
    let name = data["name"] as? String ?? ""
    let imageName = data["imageName"] as? String ?? ""
    let lessonName  = data["lessonName"] as? String ?? ""
    let fileURL  = data["fileURL"] as? String ?? ""
              
    print(data)


    return Video(name: name , imageName: imageName , lessonName: lessonName, fileURL: fileURL )
                
              
            }
        }
    }
}

And this the struct of the video这是视频的结构

import Foundation

struct Video {
    var name: String
    var imageName: String
    var lessonName: String
    var fileURL: String
}

Does an image with that ' video.imageName ' exist within the app?应用程序中是否存在带有“ video.imageName ”的图像?

let image = UIImage(named: video.imageName)
cell.imageView?.image = image

you should be download from firebase storage.您应该从 firebase 存储下载。

use to用来

guard let url = URL(string: video.imageName) else {return}
URLSession.shared.dataTask(with: URL, completionHandler: (Data?, URLResponse?, Error?) -> Void)

the first answer is one option however you will encounter the frozen screen while scrolling the UITableView.第一个答案是一个选项,但是您在滚动 UITableView 时会遇到冻结的屏幕。 if you want to void that.如果你想取消它。 Then you can use SDWebImage SDK然后你可以使用 SDWebImage SDK

import UIKit
import SDWebImage

class ListOfVideoLessonsTableViewController {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let video = viewModel.videos[indexPath.row]
        tableView.tableFooterView = UIView()
        
        cell.textLabel?.text = video.name
        cell.detailTextLabel?.text = video.lessonName
        cell.accessoryType = .disclosureIndicator
        let image = UIImage(named: video.imageName)
        cell.imageView?.sd_imageIndicator = SDWebImageActivityIndicator.gray
        cell.imageView ?.sd_setImage(with: URL(string: stringWithoutWhitespace), placeholderImage: UIImage())      
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor(named: "VideoLessonsCellHighlighted")
        cell.selectedBackgroundView = backgroundView
        cell.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
        cell.detailTextLabel?.font = UIFont(name: "Helvetica", size: 12)
        
        return cell
    }
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 flutter firestore 未在云 firestore 数据库中创建文档 - flutter firestore not creating a document in the cloud firestore database 使用 FastAPI 在全球范围内访问 Cloud Firestore 数据库 - Access cloud Firestore database globally with FastAPI Firebase 云功能不更新 Firestore 数据库中的数据 - Firebase Cloud function not updating data in Firestore database 使用 Cloud Firestore 数据库 API 创建云 Firestore 数据库,其中“database_id”为“(默认)”不起作用 - using Cloud Firestore Database API to create cloud firestore database with`database_id` of '(default)' not working 我想从 Cloud Firestore 数据库中获取纬度和经度以在 map Android Studio 上添加标记 - I want to get latitude and longitude from Cloud Firestore database to add markers on map Android Studio 如何从 firebase 存储中获取图像 URL 列表并将其上传到云 firestore? - How to get a list of image URL from firebase storage and upload it to cloud firestore? 从 Cloud Firestore 获取特定数据值 - get specific value of Data from cloud firestore 从 Cloud Firestore 使用 Flutter 获取整数 - Get an Integer with Flutter from the Cloud Firestore 与 firebase 云函数中的 firebase firestore 交互 - Interacting with firebase firestore from firebase cloud functions 使用 Flutter 从 Cloud Firestore 读取数据 - Reading data from Cloud Firestore with Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM