SwiftUI authentication view

旧街凉风 提交于 2020-12-15 07:20:48

问题


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


回答1:


how about just this:

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



回答2:


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
    }
}


来源:https://stackoverflow.com/questions/61150073/swiftui-authentication-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!