I could do it with completionHandler, but I'm trying to get server data with Combine. The following is what I have.
// UIViewController //
import UIKit
import Combine
class ViewController: UIViewController {
// MARK: - Variables
private var cancellableSet: Set<AnyCancellable> = []
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
let urlStr = "https://api.github.com/repos/ReactiveX/RxSwift/events"
let viewModel = ViewModel(urlStr: urlStr, waitTime: 2.0)
viewModel.fetchData(urlText: viewModel.urlStr, timeInterval: viewModel.waitTime)
.sink { completion in
print("complete")
} receiveValue: { dataSet in
print("count: \(dataSet)")
}
.store(in: &cancellableSet)
print("Yeah...")
}
}
struct DataModel: Hashable, Decodable {
let id: String
let type: String
}
// ViewModel //
import UIKit
import Combine
class ViewModel: NSObject {
var cancellables = [AnyCancellable]()
var urlStr: String
var waitTime: Double
init(urlStr: String, waitTime: Double) {
self.urlStr = urlStr
self.waitTime = waitTime
}
func fetchData(urlText: String, timeInterval: Double) -> Future<[DataModel], Error> {
return Future<[DataModel], Error> { [weak self] promise in
guard let strongSelf = self else { return }
if let url = URL(string: urlText) {
var request = URLRequest(url: url)
request.timeoutInterval = timeInterval
let sessionConfiguration = URLSessionConfiguration.default
let publisher = URLSession(configuration: sessionConfiguration).dataTaskPublisher(for: request)
publisher.sink { completion in
print("complete")
} receiveValue: { (data: Data, response: URLResponse) in
do {
let dataModels = try JSONDecoder().decode([DataModel].self, from: data)
promise(.success(dataModels))
} catch {
print("Error while parsing: \(error)")
promise(.failure("Failure" as! Error))
}
}
.store(in: &strongSelf.cancellables)
} else {
promise(.failure("Failure" as! Error))
}
}
}
}
If I run it, I don't get an error. The app doesn't crash, either. The view controller doesn't deliver anything. What am I doing wrong? Muchos thankos.