Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 19 days ago.
Improve this question
I have the following code:
/* #MainActor */ class Locator : NSObject, ObservableObject
{
private let locationManager: CLLocationManager
private var authorizationContinuation: CheckedContinuation<CLAuthorizationStatus, Never>?
#Published var authorizationStatus: CLAuthorizationStatus
#Published var location: CLLocation?
#Published var error: Error?
override init()
{
locationManager = CLLocationManager()
authorizationStatus = locationManager.authorizationStatus
super.init()
locationManager.delegate = self
}
/* #MainActor */ func checkAuthorizationStatus() async -> CLAuthorizationStatus
{
let status = locationManager.authorizationStatus
if status == .notDetermined
{
return await withCheckedContinuation
{ continuation in
authorizationContinuation = continuation
locationManager.requestWhenInUseAuthorization()
}
}
else
{
authorizationStatus = status <=== WARNING
return status
}
}
}
extension Locator : CLLocationManagerDelegate
{
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager)
{
authorizationStatus = manager.authorizationStatus
authorizationContinuation?.resume(returning: authorizationStatus)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print(error)
self.error = error
location = nil
}
}
Without either making the whole class or checkAuthorizationStatus() #MainActor, I get the following run-time warning:
Publishing changes from background threads is not allowed; make sure
to publish values from the main thread (via operators like
receive(on:))
What would be your considerations for choosing to make the whole class #MainActor or just the function/'part' that needs it, in this case and in general?
EDIT: To satisfy people that vote to close this questions because it's seems based on opinion: Is there in the above code any run-time difference between the two options?
UI needs to be updated on the MainActor or you get the “publishing changes in the background warning”. If the purpose of the class is to update UI it should be wrapped with MainActor.
Related
I'm trying to use #EnvironmentObject to control some aspects of my app. The issue I'm having is that one of my controllers can't access the environment object. I get the fatal error "No #ObservableObject of type Environment found".
I've searched other questions, and every solution I could find consisted of sending .environmentObject(myEnvironment) to the view in question. The problem is this is not a view, and I don't seem to have that option.
Also, in my SceneDelegate I send the environmentObject to the first view, so that is not the problem.
Here is my code.
First, I created a model to declare all my environment variables
Environment
struct Environment {
var showMenu: Bool
var searchText: String
var location : Location
init() {
self.showMenu = false
self.searchText = ""
self.location = Location()
}
}
Next I have a controller which purpose is to handle any actions related to the environment, right now it has none
EnvironmentController
import Foundation
class EnvironmentController : ObservableObject {
#Published var environment = Environment()
}
Now, in the SceneDelegate I call the NextDeparturesView, which in turn calls, the MapView.
MapView
import SwiftUI
import MapKit
//MARK: Map View
struct MapView : UIViewRepresentable {
#EnvironmentObject var environmentController: EnvironmentController
var locationController = LocationController()
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ uiView: MKMapView, context: Context) {
let coordinate = CLLocationCoordinate2D(
latitude: environmentController.environment.location.latitude,
longitude: environmentController.environment.location.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: coordinate, span: span)
uiView.showsUserLocation = true
uiView.setRegion(region, animated: true)
}
}
You'll notice that in the MapView I call the LocationController, which is where the fatal error occurs
LocationController
import SwiftUI
import MapKit
import CoreLocation
final class LocationController: NSObject, CLLocationManagerDelegate, ObservableObject {
//MARK: Vars
#EnvironmentObject var environmentController: EnvironmentController
#ObservedObject var userSettingsController = UserSettingsController()
//var declaration - Irrelevant code to the question
//MARK: Location Manager
var locationManager = CLLocationManager()
//MARK: Init
override init() {
//more irrelevant code
super.init()
//Ask for location access
self.updateLocation()
}
//MARK: Functions
func updateLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization)){
locationManager.requestAlwaysAuthorization()
}
else {
locationManager.startUpdatingLocation()
}
}
//MARK: CLLocationManagerDelegate methods
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error updating location :%#", error)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
self.setDefaultLocation()
break
case .restricted:
self.setDefaultLocation()
break
case .denied:
self.setDefaultLocation()
break
default:
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation = manager.location?.coordinate
self.environmentController.environment.location.latitude = Double(currentLocation!.latitude)
self.environmentController.environment.location.longitude = Double(currentLocation!.longitude)
manager.stopUpdatingLocation()
}
//MARK: Other Functions
func recenter() {
locationManager.startUpdatingLocation()
}
func setDefaultLocation() {
if self.$userSettingsController.userCity.wrappedValue == "" {
self.environmentController.environment.location.latitude = 0.0
self.environmentController.environment.location.longitude = 0.0
} else {
self.environmentController.environment.location.latitude = self.citiesDictionary[self.userSettingsController.userCity]!.latitude
self.environmentController.environment.location.longitude = self.citiesDictionary[self.userSettingsController.userCity]!.longitude
}
}
}
So, this is where the fatal error occurs. For instance, my app usually calls setDefaultLocation() first, and the app is crashing there. Any idea what I am doing wrong, or how to solve it?
Thank you in advance.
EDIT
After much help from #pawello2222 I've solved my problem, however with some changes to the overall structure of my application.
I will accept his answer as the correct one, but I'll provide a list of things that I did, so anyone seeing this in the future might get nudged in the right direction.
I was wrongly assuming that View and UIViewRepresentable could both access the #EnvironmentObject. Only View can.
In my Environment struct, instead of a Location var, I now have a LocationController, so the same instance is used throughout the application. In my LocationController I now have a #Published var location: Location, so every View has access to the same location.
In structs of the type View I create the #EnvironmentObject var environmentController: EnvironmentController and use the LocationController associated with it. In other class types, I simply have an init method which receives a LocationController, which is sent through the environmentController, for instance, when I call MapView I do: MapView(locController: environmentController.environment.locationController) thus insuring that it is the same controller used throughout the application and the same Location that is being changed. It is important that to use #ObservedObject var locationController: LocationController in classes such as MapView, otherwise changes won't be detected.
Hope this helps.
Don't use #EnvironmentObject in your Controller/ViewModel (in fact anywhere outside a View). If you want to observe changes to Environment in your Controller you can do this:
class Environment: ObservableObject {
#Published var showMenu: Bool = false
#Published var searchText: String = ""
#Published var location : Location = Location()
}
class Controller: ObservableObject {
#Published var showMenu: Bool
private var environment: Environment
private var cancellables = Set<AnyCancellable>()
init(environment: Environment) {
_showMenu = .init(initialValue: environment.showMenu)
environment.$showMenu
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] value in
self?.showMenu = value
})
.store(in: &cancellables)
}
}
You can also use other forms of Dependency Injection to inject the Environment (or even use a singleton).
Generally there are different ways to show your Environment variables (eg. showMenu) in the View (and refresh it):
1) The Environment is injected into your View (NOT to ViewModel) as an #EnvironmentObject - for cases when you need to access the Environment from the View only.
2) The ViewModel subscribes to the Environment (as presented above) and publishes its own variables to the View. No need to use an #EnvironmentObject in your View then.
3) The Environment is injected into your View as an #EnvironmentObject and then is passed to the ViewModel.
How do you get user location permissions in SwiftUI?
I tried asking for user location permissions after a button tap, but the dialogue box disappears after about a second. Even if you do end up clicking it in time, permission is still denied.
import CoreLocation
.
.
.
Button(action: {
let locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}) {
Image("button_image")
}
Things like location manager should be in your model, not your view.
You can then invoke a function on your model to request location permission.
The problem with what you are doing now is that your CLLocationManager gets released as soon as the closure is done. The permission request methods execute asynchronously so the closure ends very quickly.
When the location manager instance is released the permission dialog disappears.
A location model could look something like this:
class LocationModel: NSObject, ObservableObject {
private 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()
}
}
}
extension LocationModel: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.authorisationStatus = status
}
}
You would probably also want functions to start & stop location updates and an #Published CLLocation property
I'm trying to execute a Location Service once. This LocationService is called from another object class, that will add the location info into the parameters. All of this will be one object.
The problem is that when I init the object, everything is populated less the location data, which will be populated a few ms later.
I need to wait until the callback is executed, to successfully generate the full object before using it
So considering that I have the next "LocationService" class
public class LocationService: NSObject, CLLocationManagerDelegate{
let manager = CLLocationManager()
var locationCallback: ((CLLocation?) -> Void)!
var locationServicesEnabled = false
var didFailWithError: Error?
public func run(callback: #escaping (CLLocation?) -> Void) {
locationCallback = callback
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.requestWhenInUseAuthorization()
locationServicesEnabled = CLLocationManager.locationServicesEnabled()
if locationServicesEnabled {
manager.startUpdatingLocation()
}else {
locationCallback(nil)
}
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationCallback(locations.last!)
manager.stopUpdatingLocation()
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
didFailWithError = error
locationCallback(nil)
manager.stopUpdatingLocation()
}
deinit {
manager.stopUpdatingLocation()
}
}
And it is called from the object class like this:
class ObjectX: NSObject{
//Class variables
#objc override init() {
let getLocation = LocationService()
getLocation.run {
if let location = $0 {
//get location parameters
}}
Finally the ObjectX class is initiated and used from other place
let getLocation = ObjectX()
//After initiate it I use the object for other purposes, but here the object is not complete, the location parameters have not been populated yet
How can I wait in the class that is calling it until the callback is executed? Should I use getLocation.performSelector()? How?
Maybe this is not the best way to resolve this but it worked for me.
Basically, instead of creating the ObjectX and setting the in the process, the location service is gonna be called the before, then in the callback, the ObjectX is gonna be initialised, then we can set the location parameters for the ObjectX with the location object the we received in the object.
We remove the location set from the initialiser
class ObjectX: NSObject{
//Class variables
#objc override init() {
//Setting the rest of the parameters that are not location
}}
Then class that was initialising the object, we init and run the LocationService, then in callback we create the ObjectX and we set the location parameters
let ls = LocationService()
ls.run { location in
let objectX = ObjectX()
objectX.location = location
//We can use the object here
}
Now I'm working on iOS using RxSwift framework. In my app I have to user user location, but I don't need it to be updated in real time. It's enough if location updated every time user opens app or does some defined action. Therefore, how about implementing singleton class where the last result is cached. Each update by action changes cached result and accepts it to the stream. Stream's default value is cached value. Then, views where user location is needed would subscribe on this stream.
Example implementation using Cache and RxSwift
import Foundation
import Cache
import CoreLocation
import RxSwift
import RxCocoa
class UserLocationManager: NSObject {
private enum Keys: String {
case diskConfig = "Disk Config"
case lastLocation = "User Last Location"
}
// MARK: - Variables
private func cache<T: Codable>(model: T.Type) -> Cache.Storage<T> {
let storage = try! Cache.Storage(diskConfig: DiskConfig(name: Keys.diskConfig.rawValue), memoryConfig: MemoryConfig(expiry: .never), transformer: TransformerFactory.forCodable(ofType: model))
return storage
}
private let locationManager = CLLocationManager()
private var lastPosition: MapLocation? {
get {
do {
return try cache(model: MapLocation.self).object(forKey: Keys.lastLocation.rawValue)
}
catch { return nil }
}
set {
do {
guard let location = newValue else { return }
try cache(model: MapLocation.self).setObject(location, forKey: Keys.lastLocation.rawValue)
}
catch { }
}
}
private let disposeBag = DisposeBag()
static let shared = UserLocationManager()
var locationStream = BehaviorRelay<CLLocationCoordinate2D?>(value: nil)
// MARK: - Methods
func updateLocation() {
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation()
}
}
func subscribe() {
locationStream.accept(lastPosition?.clCoordinate2D)
locationStream.subscribe(onNext: { [weak self] location in
guard let `self` = self else { return }
guard let location = location else { return }
self.lastPosition = MapLocation(latitude: location.latitude, longitude: location.longitude)
}).disposed(by: disposeBag)
locationManager.delegate = self
}
// MARK: - Lifecycle
override init() {
super.init()
defer {
self.subscribe()
}
}
}
// MARK: - CLLocationManagerDelegate
extension UserLocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else { return }
UserLocationManager.shared.locationStream.accept(location.coordinate)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}
}
There's no problem conceptually of having a global stream that can be subscribed to. However, your specific implementation is worrisome to me.
One of the cool things about Observable streams is that they are lazy, no work is done unless needed, but you are writing extra code to bypass that feature and I don't think it's necessary. Also, storing there current location when the app goes into the background and just assuming that is a valid location when the app comes back to the foreground (possibly weeks later) sounds inappropriate to me.
The RxCocoa package already has an Rx wrapper for CLLocationManager. It seems to me it would be far simpler to just use it. If you only need one location update then use .take(1). I'd be inclined to add a filter on the accuracy of the location before the take(1).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to learn how to program location into apps, and this whole chunk of code just really confused me with the locationManager and delegates. I don't get at all what's going on when you declare a function called locationManager. You are defining this function, locationManager, right? With 2 parameters. So what exactly is calling this locationManager? When going through the Complete iOS Developer Course, he takes this locationManager snippet and copy pastes it without explaining the principles behind what you're doing when copying and pasting it. Is there some line of code that calls "locationManager(...)"? If so, where does this happen? My brain keeps thinking that if it's a function that's inherited from a superclass, CLLocationManagerDelegate, wouldn't you have to override it in order to get it to work? And could you give some intuition on how delegates work exactly?
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var myMap : MKMapView!
var manager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Core Location
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
var userLocation:CLLocation = locations[0] as CLLocation
var latitude:CLLocationDegrees = userLocation.coordinate.latitude
var longitude:CLLocationDegrees = userLocation.coordinate.longitude
var latDelta:CLLocationDegrees = 0.01
var lonDelta:CLLocationDegrees = 0.01
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
myMap.setRegion(region, animated: true)
}
func locationManager(manager:CLLocationManager, didFailWithError error:NSError)
{
println(error)
}
Thank you very much for your help!
These delegate methods, defined in the CLLocationManagerDelegate protocol, are called by the CLLocationManager object that you instantiated and are referencing in the manager variable. So, you've instantiated the CLLocationManager object, you've asked it to inform you when there are location updates, and it does that by calling these delegate methods you've implemented.
You say:
My brain keeps thinking that if it's a function that's inherited from a superclass, CLLocationManagerDelegate, wouldn't you have to override it in order to get it to work?
The CLLocationManagerDelegate is not a class. It is a "protocol". It defines what functions the delegate object (in this case, your view controller) may/should implement. So, there's nothing to override.