When the user doesn’t authorize our app to always use the location data, the app doesn’t work. In this case we should present an alert to the user that the app can’t deliver the promised functionality. As we did for the day entries data, we use Combine to bind the user interface to the information if the correct authorization is given. Open LocationProvider and add the following property:
| @Published var wrongAuthorization = false |
This property keeps track of the authorization status. We need to set it to true when the authorization status is not authorizedAlways. Add the highlighted line in the following code to locationManager(_:didChangeAuthorization:):
| func locationManager(_ manager: CLLocationManager, |
| didChangeAuthorization status: |
| CLAuthorizationStatus) { |
| |
| switch status { |
| case .authorizedAlways: |
| printLog("success") |
| case .notDetermined: |
| printLog("notDetermined") |
| default: |
» | wrongAuthorization = true |
| } |
| } |
Next we need the code that presents the alert to the user when Not Always authorization is granted. Open ContentView and add the highlighted modifier to the outer VStack:
| .background(Color(UIColor.systemBackground)) |
» | .alert(isPresented: $locationProvider.wrongAuthorization) { |
» | Alert(title: Text("Not authorized"), |
» | message: Text("Open settings and authorize."), |
» | primaryButton: .default(Text("Settings"), action: { |
» | UIApplication.shared.open( |
» | URL(string: UIApplication.openSettingsURLString)!) |
» | }), |
» | secondaryButton: .default(Text("OK"))) |
» | } |
The modifier .alert(...) presents an alert to the user when the bound value of the first parameter becomes true. The alert itself is defined in the closure of the alert modifier. In this case we define an alert with a title, a message, and two buttons. For the first button we add an action that opens the app settings in the iOS Settings app. The user can then change the authorization to make the app work again.
Our app is finished. Build and run it on your iPhone and see how much time you spend outside. After you’ve used the app for a few days, you should see something like the following image:
As you can see from my data, I work from home.