根据用户输入导航到其他视图

时间:2020-06-29 21:54:12

标签: ios swift swiftui

我要向用户请求访问其位置的权限,如果他接受,则希望将其重定向到ViewA,如果他拒绝授予位置访问,则要将其重定向到ViewB。 解决此问题的最佳方法是什么?预先感谢。

查看

struct UserPermissionView: View {
@ObservedObject var viewModel: UserPermissionViewModel

init(viewModel: UserPermissionViewModel) {
    self.viewModel = viewModel
}

var body: some View {
    NavigationView {
        ZStack {
            WeatherViewProperties.bgColors["clear sky"]
            .edgesIgnoringSafeArea(.all)
            
            GeometryReader { geometry in
                VStack(alignment: .center) {
                    Image("weatherpermission")
                    Text("Hey! We need permission to access your location!").fixedSize(horizontal: false, vertical: true).font(.title)
                    .frame(maxWidth: geometry.size.width * 0.80)
                    
                    Button(action: {
                        self.viewModel.requestAuthorisation()
                    }) {
                        Text("Grant Location")
                    }
                }
            }
        }
    }
}

VIEWMODEL

class UserPermissionViewModel: NSObject, ObservableObject {
let locationManager = CLLocationManager()
@Published var authorisationStatus: CLAuthorizationStatus = .notDetermined

override init() {
    super.init()
    self.locationManager.delegate = self
}

public func requestAuthorisation(always: Bool = false) {
    if always {
        self.locationManager.requestAlwaysAuthorization()
    } else {
        self.locationManager.requestWhenInUseAuthorization()
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用@ViewBuilder

struct ContentView: View {
    @ObservedObject var viewModel: UserPermissionViewModel

    init(viewModel: UserPermissionViewModel) {
        self.viewModel = viewModel
    }

    var body: some View {
        NavigationView {
            content
        }
    }

    @ViewBuilder
    var content: some View {
        switch viewModel.authorisationStatus {
        case .notDetermined:
            requestPermissionView
        case .denied:
            Text("denied")
        default:
            Text("...")
        }
    }

    var requestPermissionView: some View {
        ZStack {
            WeatherViewProperties.bgColors["clear sky"]
            .edgesIgnoringSafeArea(.all)
            
            ...
        }
    }
}