简体   繁体   中英

SwiftUI authentication view

In swift UI I want the content view to be my root view for my app with a conditional setup to check if the users is logged in or not. If the user is logged in a list view shows other wise show the login view so the user can log in. Based on my research i could not find a best way to do this.

In my case I can not get the solution I found to work and do not know if it is the best solution.

import SwiftUI

struct ContentView: View {
    @ObservedObject var userAuth: UserAuth = UserAuth()
    // MARK: - View

    @ViewBuilder
    var body: some View {
        if !userAuth.isLoggedin {
            return LoginView().environmentObject(userAuth)
        } 
        return  BookList()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

import Combine

class UserAuth: ObservableObject {

    let didChange = PassthroughSubject<UserAuth,Never>()

    // required to conform to protocol 'ObservableObject'
    let willChange = PassthroughSubject<UserAuth,Never>()

    func login() {
        // login request... on success:
        self.isLoggedin = true
    }

    func logout() {
        // login request... on success:
        self.isLoggedin = false
    }

    var isLoggedin = false {
        didSet {
            didChange.send(self)
        }

//        willSet {
//            willChange.send(self)
//        }
    }
}

When running this all i get is a white screen. It seems that the view builder might be the problem but removing that i get a opaque error on content view

There two problems with provided code snapshot: 1) incorrect view builder content, and 2) incorrect model.

See below both fixed. Tested with Xcode 11.4 / iOS 13.4

struct ContentView: View {
    @ObservedObject var userAuth: UserAuth = UserAuth()
    // MARK: - View

    @ViewBuilder              // no need return inside
    var body: some View {
        if !userAuth.isLoggedin {
            LoginView().environmentObject(userAuth)
        }
        else {
            BookList()
        }
    }
}

import Combine

class UserAuth: ObservableObject {
    @Published var isLoggedin = false     // published property to update view

    func login() {
        // login request... on success:
        self.isLoggedin = true
    }

    func logout() {
        // login request... on success:
        self.isLoggedin = false
    }
}

how about just this:

var body: some View {
    if !userAuth.isLoggedin {
      LoginView().environmentObject(userAuth)
    } else {
      BookList()
      }
}

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