使用ReactiveCocoa(4.2.1)和Swift进行异步图像加载



我是第一次在Swift中使用ReactiveCocoa的初学者。我正在构建一个应用程序,显示电影列表,我使用MVVM模式。我的ViewModel看起来像这样:

class HomeViewModel {
    let title:MutableProperty<String> = MutableProperty("")
    let description:MutableProperty<String> = MutableProperty("")
    var image:MutableProperty<UIImage?> = MutableProperty(nil)
    private var movie:Movie
    init (withMovie movie:Movie) {
        self.movie = movie
        title.value = movie.headline
        description.value = movie.description
        Alamofire.request(.GET, movie.pictureURL)
            .responseImage { response in
                if let image = response.result.value {
                    print("image downloaded: (image)")
                    self.image.value = image
                }
        }
    }
}

我想在UITableView中这样配置单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell", forIndexPath: indexPath) as! MovieCell
    let movie:Movie = movieList[indexPath.row]
    let vm = HomeViewModel(withMovie: movie)
    // fill cell with data
    vm.title.producer.startWithNext { (newValue) in
        cell.titleLabel.text = newValue
    }
    vm.description.producer.startWithNext { (newValue) in
        cell.descriptioLabel.text = newValue
    }
    vm.image.producer.startWithNext { (newValue) in
        if let newValue = newValue {
            cell.imageView?.image = newValue as UIImage
        }
    }
    return cell
}

对于活性可可来说这是正确的方法吗?我需要声明标题和描述为可变的或只是图像(是唯一一个改变)。我想我可以使用绑定,但我不确定如何进行

要使用Reactive Cocoa + MVVM模式做到这一点,我将首先将所有配置单元格的逻辑从其视图模型移动到单元格类本身。然后从viewModel中删除MutableProperties(它们实际上不是可变的,我们不需要那些信号)。对于图像,暴露一个信号生成器,当start()被调用时,它将执行网络请求来获取图像,而不是在ViewModel上调用init时隐式地获取图像,给我们一些像

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell", forIndexPath: indexPath) as! MovieCell
  cell.viewModel = self.viewModelForIndexPath(indexPath)
  return cell
}
private func viewModelForIndexPath(indexPath: NSIndexPath) -> MovieCellViewModel {
  let movie: Movie = movieList[indexPath.row]
  return HomeViewModel(movie: movie)
}

class MovieCell: UITableViewCell
  @IBOutlet weak var titleLabel: UILabel
  @IBOutlet weak var descriptionLabel: UILabel
  @IBOutlet weak var imageView: UIImageView
  var viewModel: MovieCellViewModel {
    didSet {
      self.configureFromViewModel()
    }
  }
  private func configureFromViewModel() {
    self.titleLabel.text = viewModel.title
    self.descriptionLabel.text = viewModel.description
    viewModel.fetchImageSignal()
      .takeUntil(self.prepareForReuseSignal()) //stop fetching if cell gets reused
      .startWithNext { [weak self] image in
        self?.imageView.image = image
      }
  }
  //this could also go in a UITableViewCell extension if you want to use it other places
  private func prepareForReuseSignal() -> Signal<(), NoError> {
    return Signal { observer in
      self.rac_prepareForReuseSignal // reactivecocoa builtin function
        .toSignalProducer() // obj-c RACSignal -> swift SignalProducer
        .map { _ in () } // AnyObject? -> Void
        .flatMapError { _ in .empty } // NSError -> NoError
        .start(observer)
    }
  }
}

和ViewModel

struct HomeViewModel {
  private var movie: Movie
  var title: String {
    return movie.headline
  }
  var description: String {
    return movie.description
  }
  func fetchImageSignal() -> SignalProducer<UIImage, NSError> {
    return SignalProducer { observer, disposable in
      Alamofire.request(.GET, movie.pictureURL)
        .responseImage { response in
          if let image = response.result.value {
            print("image downloaded: (image)")
            observer.sendNext(image) //send the fetched image on the signal
            observer.sendCompleted()
          } else {
            observer.sendFailed( NSError(domain: "", code: 0, userInfo: .None)) //send your error
          }
        }
  }
}

相关内容

  • 没有找到相关文章

最新更新