I have the following code that makes an API call, receives data and assigns it to Core Data managed objects. This works well, and updates my data.
func importUsers(url: URL) {
URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.sink(receiveCompletion: { completion in
if case .failure(let error) = completion {
print("DataImporter.runImport failed with error: \(error)")
}
}, receiveValue: { [weak self] data in
guard let self = self
else { return }
self.importContext.perform {
do {
// 2. Decode the response. This decodes directly to the Core Data Store
let users = try self.decoder.decode([GitUser].self, from: data)
try? self.importContext.save()
} catch {
print("DataImporter.runImport failed to decode json with error: \(error)")
}
}
})
.store(in: &self.cancellables) // store the returned cancellable in a property on `DataImporter`
}
However, I need to return the number of objects returned and decoded as a result of this call. If it fails, I return 0. Essentially, I want this:
func importUsers(url: URL) -> Int {
URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.sink(receiveCompletion: { completion in
if case .failure(let error) = completion {
print("DataImporter.runImport failed with error: \(error)")
}
}, receiveValue: { [weak self] data in
guard let self = self
else { return 0 }
var users: [GitUser] = []
self.importContext.perform {
do {
// 2. Decode the response. This decodes directly to the Core Data Store
users = try self.decoder.decode([GitUser].self, from: data)
try? self.importContext.save()
} catch {
print("DataImporter.runImport failed to decode json with error: \(error)")
}
}
return users.count
}).store(in: &self.cancellables) // error: Cannot convert return expression of type '()' to return type 'Int'
}
How do I return the count of objects received as a result of the network call?