简体   繁体   中英

How to pass user input data between a multi-page SwiftUI user registration?

Considering an iOS SwiftUi app that has 3 pages in total for the user registration process.

  • 1st page containing an email input and a continue button
  • 2nd page containing a username input and a continue button
  • 3rd page containing a password input and a Register button

What would the best practice be for capturing the user input data and then sending it out to a backend?

My initial assumption is to store the data that the user inputs in pages 1 and 2 locally. Then on tap of the Register button on page 3, get the previously locally stored data along with the page 3 data and send it out as one to the backend. Then clear the local storage.

Other thoughts have been to use @EnvironmentObject to store user inputs, but is this secure/recommended?

There's isn't really a right answer here, but we can look to the react world for inspiration since SwiftUI is heavily based on react. The approach that's become popular is to create a single source of truth, ie a single "store" that houses your shared state.

How do you communicate with the store? The simplest approach would be to create a class, instantiate that class in AppDelegate and pass the instance down your view hierarchy. You can either pass it explicitly as a property on each view, or pass it implicitly using SwiftUI's EnvironmentObject.

Here's what a simple store might look like:

class AppState: ObservableObject {
  @Published var firstName: String?
  @Published var lastName: String?

  func submit() {
    // submit first and last name to the API
  }
}

A similar, but more robust implementation is to use a very popular pattern known as Redux. In this approach, mutating the store is decoupled from the state of the store by firing actions and modifying the state in a reducer function. You can see a cool example of implementing Redux in a SwiftUI way with Combine here:

https://swiftwithmajid.com/2019/09/18/redux-like-state-container-in-swiftui/

Also take a look at this approach for how it optimizes store-connected components by utilizing a KeyPath-specific publisher to define which store sub-state changes should affect a component:

https://nalexn.github.io/swiftui-observableobject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM