Search code examples
swiftswiftuicore-location

Using CLLocationManager with SwiftUI (XCode 14.3.1, iOS 16.6)


I'm building an iPhone app to display the current solar time -- the time of day based on the location of the sun in the sky at your actual location, rather than the time zone in which you find yourself. To do that, I need to know longitude.

I obviously need to create and use a CLLocationManager instance. All of the examples I've found on-line for doing that assume the use of UIKit, and include some initialization and event handling code in a view controller that's a CLLocationManagerDelegate. That depends expressly on UIViewController.

It may be possible to mix UIKit and SwiftUI, and if so, that may solve my problem. But I don't know, and my Google fu has turned up no relevant examples.

Does anyone know how to create a new class that uses a CLLocationManager instance, with appropriate delegates, in SwiftUI? Best of all: Any sample code for a toy "where am I" app using SwiftUI that I could swipe?

I tried setting up a class in my application to manage location information:

class SMCLocation {
    var longitude: Double
    var latitude: Double
    var valid: Bool = false
    
    private var lm = CLLocationManager()

    init() {
        lm.delegate = self
    }
    
    private func start() -> Void {
        
    }
}

The Swift compiler dislikes this, and complains in the init function, at the lm.delegate = self statement,

Cannot assign value of type 'SMCLocation' to type '(any CLLocationManagerDelegate)?'
Add missing conformance to 'CLLocationManagerDelegate' to class 'SMCLocation'

I don't know what such a conformance is, or how to add it to my class.


Solution

  • You are missing the conformance like the error says

    class SMCLocation: NSObject, CLLocationManagerDelegate {