【发布时间】:2020-12-03 00:28:44
【问题描述】:
晚上好,
问题
我使用 GET 请求从 API 接收一组 Notes。每个笔记都有一个类型(ATC、成像和实验室)
问题是端点为我提供了所有笔记的列表,但我想按笔记类型将它们分成UISegmentedControl。即第 1 段有 ATC,第 2 段有成像,最后一段是实验室。
守则
笔记模型
var id: Int
var name: String?
var date: Date
var createdByFirstName: String?
var createdByLastName: String?
var type: String?
var isClosed: Bool
API 请求
func getAssociatedInjuryNotes(with injuryId: Int, completion: @escaping ((Result<[AssociatedInjuryNote], InjuryError>) -> Void)) {
let baseURL = self.configuration.baseURL
let endPoint = baseURL.appendingPathComponent("injury/\(injuryId)/notes")
API.shared.httpClient.get(endPoint) { (result) in
switch result {
case .success(let response):
do {
let injuryAssociatedNote = try API.jsonDecoder.decode([AssociatedInjuryNote].self, from: response.data)
completion(.success(injuryAssociatedNote))
} catch (let error) {
completion(.failure(.unknown(message: error.localizedDescription)))
}
case .failure(let error):
completion(.failure(.unknown(message: error.localizedDescription)))
}
}
}
如何在视图控制器中获取数据
fileprivate class InjuryAssociatedNotesViewModel {
private(set) var injuryId: Int
@Published private(set) var injuryNotes: [AssociatedInjuryNote] = []
@Published private(set) var error: String?
init(injuryId: Int) {
self.injuryId = injuryId
}
func refresh() {
InjuryAPI.shared.getAssociatedInjuryNotes(with: injuryId) { (result) in
switch result {
case .success(let associatedNotes):
self.injuryNotes = associatedNotes.sorted(by: {
$0.date.compare($1.date) == .orderedDescending
})
case .failure(let error):
self.error = error.localizedDescription
}
}
}
}
CollectionView 设置
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let viewModel = self.viewModel else { return UICollectionViewCell() }
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NoteCell.reuseIdentifier, for: indexPath) as? NoteCell else { fatalError("Could not dequeue cell of type: '\(NoteCell.self)'") }
let injuryAssociatedNote = viewModel.injuryNotes[indexPath.item]
cell.configure(with: injuryAssociatedNote)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let viewModel = self.viewModel else { return 0 }
return viewModel.injuryNotes.count
}
如果有人能指出我正确的方向,将不胜感激,我正在为此苦苦挣扎。
【问题讨论】: