简体   繁体   中英

API Request in ReactiveSwift

I am beginner in ReactiveSwift. I create weather app and my request does not work.

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 

}

Map block is not called. What should i change in this request or in parsing method ?

You have to start your SignalProducer .

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

})

you also have

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

in all cases, you have to "start" cold signals in order to make them work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM