模型类Swift中的完成处理程序

时间:2019-04-11 14:01:08

标签: ios swift firebase

我正在将MVC用于Firebase。现在,在Model类中,我想显示一个TableView,其中包含从Firebase检索的数据。每个单元都有一个图像。现在的问题是,我找不到找到使图像显示在表格视图中的方法。下载图片在后端,我找不到显示它的方法。

class List {
    let ref:DatabaseReference?
    var name : String
    var title : String
    var subtitle : String
    var time : String
    var puretime : Any
    var indexOfSelf : String
    lazy var photo : UIImage = UIImage()

    init(name: String, title: String, subtitle: String, time: String, puretime: Any, indexOfSelf: String, photo: UIImage) {
        self.ref = nil
        self.name = name
        self.title = title
        self.subtitle = subtitle
        self.time = time
        self.puretime = puretime
        self.indexOfSelf = indexOfSelf
        self.photo = photo
    }
    typealias CompletionHandler = (_ success:Bool) -> Void
    init?(snapshot: DataSnapshot)
    {
        guard
        let value = snapshot.value as? [String: AnyObject],
        let url = value["0"] as? String,
        let name = value["name"] as? String,
        let title = value["title"] as? String,
        let subtitle = value["subtitle"] as? String,
        let time = value["time"] as? String,
        let puretime = value["puretime"] as? Any,
        let indexOfSelf = value["indexOfSelf"] as? String
        else{
            return nil
        }

        self.ref = snapshot.ref
        self.name = name
        self.title = title
        self.subtitle = subtitle
        self.time = time
        self.puretime = puretime
        self.indexOfSelf = indexOfSelf
        var image = UIImage()

    }
    var image = UIImage()
    func getImage(url:String, completionHandler: @escaping CompletionHandler) {
        print("Doing something!")

        let storageRef = Storage.storage().reference(forURL: url)
        storageRef.getData(maxSize: 1 * 2084 * 2084)
        { data, error in
            if let error = error {
                print("error from downloading image is \(error)")

            } else {
                self.image = UIImage(data: data!)!
                let flag = true
                completionHandler(flag)
            }

        }

    }

    func toAnyObject() -> Any{
        return [
            "name": name,
            "title": title,
            "subtitle": subtitle,
            "time": time,
            "puretime": puretime,
            "indexOfSelf": indexOfSelf,
            "photo": photo
        ]
    }
}

除图像外,其他所有实体都在工作。我不确定在我的情况下如何使用补全。所以有人可以给我一些建议吗? 非常感谢

1 个答案:

答案 0 :(得分:0)

创建一个服务类并添加如下方法(我也建议将List创建为结构而不是类。)

class YourServiceClass {
    func getItemList(completion: @escaping (Array< List >?,Error?)-> Void)
    {
      //call your get service and inside you service response
      //check for all your validation here  is a success then

        let listElms = arrayOfItems.compactMap(List.init)
        completion(listElms,nil)

    }
}

现在从您的viewController或viewModel调用 getItemList