Reputation: 666
I am asking the user for permission to access his location and would like to redirect him to ViewA if he accepts or ViewB if he refuses to give location access. What would be the best way to go around this? Thanks in advance.
VIEW
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()
}
}
Upvotes: 0
Views: 47
Reputation: 54426
You can try using a @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)
...
}
}
}
Upvotes: 1