中从服务器下载数据的最佳实践

中从服务器下载数据的最佳实践

本文介绍了在 SwiftUI 中从服务器下载数据的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是一个概念性问题.

My question is a conceptual question.

我有以下代码:

struct CategoriesList : View {

    @State private var categories: [CategoryMetadata] = []

    var body: some View {
        NavigationView {
            List(self.categories) { category in
                NavigationButton(destination: PostsList(category: category)) {
                    CategoryRow(category: category)
                }
            }
        }.navigationBarTitle(Text("Categorie"))
    }
}

这只是使用元素(类别)列表来组成我的 UI,我有一个与我的视图相关联的状态,它会在视图更改时自动更新视图.

That simply compose my UI using a list of elements (categories) and I have a state associated with my view that auto-update the view when it changes.

这一切都很好,但对我来说不清楚谁应该触发网络请求来填充模型.

It's all fancy and nice but for me it's not clear WHO should fire the network request to fill the model.

我理解绑定和 @state 的想法,但是,一般来说,我应该如何构建代码以在开始时拥有我需要的模型?

I understood the bindings and the @state idea, but, in general, how should I architecture the code to have the models I need at the beginning?

在旧方法中,我会在 viewDidLoad 中实现此行为,但使用 SwiftUI 的新范式,获取数据的最佳方法是什么?

In the old approach I would have implemented this behavior in the viewDidLoad, but with the new paradigm of SwiftUI, what is the best approach to get my data?

推荐答案

SwiftUI 社区还没有真正建立任何最佳实践,因为这项技术太新了.我的回答是基于我在不同的 WWDC19 会议上看到的.

The SwiftUI community hasn't really established any best-practices yet because the technology is so new. My answer is based off of what I've seen from different WWDC19 sessions.

首先,创建一个带有 categories 属性的 BindableObject.然后编写您的网络请求代码并将 self.categories 设置为您新下载的类别.

First, create a BindableObject with a categories property. Then write your network request code and set self.categories to your newly downloaded categories.

import SwiftUI
import Combine

final class CategoryStore: BindableObject {
    var didChange = PassthroughSubject<Void, Never>()

    var categories = [String]()

    init() {
        // TODO: Fetch categories from API
        self.categories = ["A", "B", "C"]
    }
}

然后,将 CategoryStore 添加到 View 并与 List 一起使用以遍历类别.

Then, add CategoryStore to View and use it with List to iterate over the categories.

import SwiftUI

struct ContentView : View {
    @ObjectBinding private var store = CategoryStore()

    var body: some View {
        List(store.categories.identified(by: \.self)) { category in
            Text(category)
        }
    }
}

每当 categories 属性更新时,您的 UI 都会更新为新的类别(tysm 合并)

Whenever the categories property updates, your UI will update with the new categories (tysm Combine)

这篇关于在 SwiftUI 中从服务器下载数据的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:39