ReactiveSwift中的API请求

时间:2018-09-10 13:34:31

标签: ios reactive-programming reactive-cocoa reactive-swift

我是ReactiveSwift的初学者。我创建了天气应用,但我的请求无法正常工作。

func fetchCurrentWeather() -> SignalProducer<TodayWeatherData?, DownloadError> {
    guard let unwrappedURL = url else { return SignalProducer.empty }

    return URLSession.shared.reactive
        .data(with: URLRequest(url: unwrappedURL))
        .retry(upTo: 2)
        .flatMapError { error in
            print("Error = \(error.localizedDescription)")
            return SignalProducer.empty
        }
        .map { (data, response) -> TodayWeatherData? in
            do {
                let weatherArray = try JSONDecoder().decode(TodayWeatherData.self, from: data)
                return weatherArray
            } catch (let error) {
                print("\(error)")
                return nil
            }
        }
        .observe(on: UIScheduler())
}

self.weatherFetcher.fetchCurrentWeather().map { weather in 

}

未调用地图块。我应该在此请求或解析方法中更改什么?

1 个答案:

答案 0 :(得分:1)

您必须启动SignalProducer

self.weatherFetcher.fetchCurrentWeather().startWithResult({ result in 
    switch result {
       case .success(let weather): //use the result value
       case .failed(let error): //handle the error
    }

})

您也有

  • startWithFailed()
  • startWithValues()
  • startWithCompleted()
  • start()

在所有情况下,您都必须“启动”冷信号以使其正常工作。