我是新手,我很努力地了解如何返回获取引脚的结果。
我可以将结果设置为@Published
,但是我只想能够调用fetch方法并等待结果或错误。
class PinService: NSObject, ObservableObject {
private var session: Session
private var subscriptions = Set<AnyCancellable>()
init(session: Session) {
self.session = session
super.init()
}
func fetchPins (categories: Set<CategoryModel>, coordinates: CLLocationCoordinate2D) {
_fetchPins(categories: categories, coordinates: coordinates)
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("fetchPins() error")
case .finished:
print("fetchPins() complete")
}
}, receiveValue: { pins in
/*
What to do here?
I can add a @Published var pins: [Pin], and do
self.pins = pins
But if I want to be able to return the value or the error, how can I do that?
*/
})
.store(in: &self.subscriptions)
}
private func _fetchPins(categories: Set<CategoryModel>, coordinates: CLLocationCoordinate2D) -> Future<[Pin], Error> {
return Future<[Pin], Error> { promise in
let categoryIds = categories.map { return $0.id }.joined(separator: ",")
let radius = 15 //miles
self.session.request(baseUrl + "/api/v1/pinsRadius?latitude=\(coordinates.latitude)&longitude=\(coordinates.longitude)&radius=\(radius)&categories=\(categoryIds)")
.responseDecodable(of: [Pin].self) { (response: DataResponse) in
switch response.result {
case .success(let pins):
promise(.success((pins)))
case .failure(let error):
promise(.failure(error))
}
}
}
}
}
对不起,如果是一个愚蠢的问题,谢谢。
答案 0 :(得分:2)
一种解决方案是在函数中使用完成处理程序,然后从receiveValue
调用它
func fetchPins (categories: Set<CategoryModel>,
coordinates: CLLocationCoordinate2D,
completion: @escaping (Result<[Pin], Error>) -> Void)) {
_fetchPins(categories: categories, coordinates: coordinates)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
completion(.failure(error))
print("fetchPins() error")
case .finished:
print("fetchPins() complete")
}
}, receiveValue: { pins in
completion(.success(pins))
})
.store(in: &self.subscriptions)
}
您对fetchPins
的呼叫将类似于
fetchPins(categories: someValue, coordinates: someOtherValue) { pins in
//do stuff with pins here
}