【问题标题】:fetching images from firebase in swift 3在swift 3中从firebase获取图像
【发布时间】:2017-12-02 16:01:46
【问题描述】:

我使用 Firebase 作为我的项目的后端。我需要在表格视图中显示来自 Firebase 数据库的文本和图像。它仅在我的表格视图中显示文本,并在检索图像时显示错误“无法转换类型为 'UIImage?' 的值?”到预期的参数类型“字符串””。请任何可以纠正我的人。我的代码如下:

//应用委托

import UIKit
import CoreData
import Firebase
import FirebaseDatabase
import FirebaseStorage

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    FIRApp.configure()

    return true
}

//视图控制器

import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var ref: FIRDatabaseReference? = nil
var refHandle: UInt? = nil
var userList = [User]()



@IBOutlet var tblHome: UITableView!

let textCellIdentifier = "TextCell"



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    tblHome.delegate = self
    tblHome.dataSource = self


   self.ref = FIRDatabase.database().reference()

    print("ref = ",ref)
    fetchUsers()

}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    print("userList is", userList.count)
    return userList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) as! HomeCell


    cell.profname.text = userList[indexPath.row].imageName

  if let url = URL.init(string: userList[indexPath.row].imageUrl) {             // Error: cannot convert value of type 'UIImage?' to expected argument type 'String'
        cell.profImage.image.downloadedFrom(url: url)
    }


    return cell

}



func fetchUsers() {

    refHandle = ref?.child("Users").observe(.childAdded, with: { (snapshot) in

        print("refHandle =", self.refHandle)

        if let dictionary = snapshot.value as? [String: AnyObject] {

            print("dictionary =", dictionary)
            let user = User()
            user.setValuesForKeys(dictionary)
            self.userList.append(user)

            print("userlist is", user)

            DispatchQueue.main.async(execute: {
                self.tblHome.reloadData()

            })

        }

    })

}



}

extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
    contentMode = mode
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data)
            else { return }
        DispatchQueue.main.async() { () -> Void in
            self.image = image
        }
        }.resume()
}
  //  func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
     //   guard let url = URL(string: link) else { return }
   //     downloadedFrom(url: url, contentMode: mode)
   // }
}

//主单元格

import UIKit

class HomeCell: UITableViewCell {

@IBOutlet var profImage: UIImageView!

@IBOutlet var profname: UILabel!


override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}
}

//用户

import UIKit


class User: NSObject {
var imageName: String?
var imageUrl: UIImage?
}

【问题讨论】:

  • 哪一行报错?
  • if let url = URL.init(string: userList[indexPath.row].imageUrl) { // 错误:无法转换 'UIImage?' 类型的值到预期的参数类型 'String' cell.profImage.image.downloadedFrom(url: url) } 视图控制器中的这一行给出了错误。我也标记了错误的原因。 @eshirima

标签: uitableview firebase swift3 firebase-realtime-database firebase-storage


【解决方案1】:

根据文档,URL() 接受一个字符串,而您将一个 UIImage 传递给它。

在您的 User 类中,imageUrl 的类型为 UIImage?,您将其传递给 URL 构造函数,即使它需要一个字符串。

您可以通过将您的 User 类更改为此来解决此问题:

class User: NSObject 
{
    var imageName: String?
    var imageUrl: String? // pass this to the URL constructor
    var image: UIImage? // this stores the actual image
}

【讨论】:

  • 现在,出现错误: if let url = URL.init(string: userList[indexPath.row].imageUrl!) { // 无法转换 'UIImage?' 类型的值到预期的参数类型 'String' cell.profImage.image.downloadedFrom(url: url) }//Error: value of type 'UIImage?'没有成员“downloadedFrom”
  • 你完全理解你的代码吗?还是您从在线资源中获得的?我问这个是因为您的实际使用与您在两种情况下的设置不同,即String 问题和downloadedFrom
  • 对不起,我做不到;远离我的笔记本电脑。改为cell.profImage.downloadedFrom(url: url)。我真的建议不要从 SO 获取代码,特别是如果您不确定发生了什么或如何将其集成到您的项目中。阅读thiswatch this 分别了解UIImageViews 以及如何使用扩展。
  • 我只从堆栈溢出中得到了这个解决方案。所以我使用了它。我只有那个问题。它在控制台上打印数据。只是我需要从扩展中获取数据。
猜你喜欢
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 2021-07-17
相关资源
最近更新 更多