我有以下代码进行API调用,接收数据并将其分配给Core 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`
}
但是,我需要返回作为此调用的结果返回和解码的对象的数量。如果失败,我返回0。实际上,我想要的是:
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'
}
我如何返回作为网络调用的结果收到的对象的计数?
我的建议是解码数据并在管道中创建Core data记录并返回一个发布者。在另一个函数中订阅发布者和sink
的项目数量和/或处理错误。
我没有你的定制物品,你必须妥善管理self
func importUsers(url: URL) -> AnyPublisher<Int,Error> {
URLSession.shared.dataTaskPublisher(for: url)
.map(.data)
.tryMap{data -> Int in
var users: [GitUser] = []
var cdError : Error?
self.importContext.performAndWait {
do {
let users = try self.decoder.decode([GitUser].self, from: data)
try self.importContext.save()
} catch {
cdError = error
}
}
if let error = cdError { throw error }
return users.count
}
.eraseToAnyPublisher()
}
但是你也可以使用async/await
func importUsers(url: URL) async throws -> Int {
let (data, _) = try await URLSession.shared.data(from: url)
let users = try await self.importContext.perform {
try self.decoder.decode([GitUser].self, from: data)
try self.importContext.save()
}
return users.count
}
或iOS 13兼容的async
版本,这里perform
可以是异步的
func importUsers(url: URL) async throws -> Int {
try await withCheckedThrowingContinuation { continuation in
let task = URLSession.shared.dataTask(with: url) { [unowned self] (data, _ , error) in
if let error = error { continuation.resume(with: .failure(error)); return }
self.importContext.perform {
do {
let users = try self.decoder.decode([GitUser].self, from: data!)
try self.importContext.save()
continuation.resume(with: .success(users.count))
} catch {
continuation.resume(with: .failure(error))
}
}
}
task.resume()
}
}