Search code examples
swiftswiftuicllocationmanager

Automatically include user’s current location in a SMS (Swift)


I'm trying to build a simple app for with a feature that will allow a user to send an sms that automatically includes their location. I have found some code for it however they’re either old or is using objective-c. I have got the sending of the message covered however I'm lost at how I can automatically put the user's current location in the message’s body.

Here is my code so far:

import SwiftUI

import CoreLocation

import UIKit

struct MessageView: View {

    @State private var isShowingMessages = false

      var body: some View {

        Button("Show Messages") {
            self.isShowingMessages = true
        }
        .sheet(isPresented: self.$isShowingMessages) {
           MessageComposeView(recipients: ["09389216875"], 
                              body: "Emergency, I am here with latitude: \(locationManager.location.coordinate.latitude); longitude: \(locationManager.location.coordinate.longitude") { messageSent in 
                                            print("MessageComposeView with message sent? \(messageSent)") } \\ I currently get an error in this chunk 
        }
 }

class ViewController: UIViewController, CLLocationManagerDelegate {

   var locationManager: CLLocationManager!

  override func viewDidLoad() {

        super.viewDidLoad()

        locationManager = CLLocationManager()

        locationManager.delegate = self

        locationManager.requestWhenInUseAuthorization()

    }

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        if status != .authorizedWhenInUse {return}

        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        locationManager.startUpdatingLocation()

        let locValue: CLLocationCoordinate2D = manager.location!.coordinate

        print("locations = \(locValue.latitude) \(locValue.longitude)")

    }
}


Solution

  • You are mixing the code of UIKit and SwiftUI. First You have to create location Manager class and then assign that class to StateObject and use it in SWiftUI View.

    Use following as Location manager : -

           class LocationManager: NSObject, ObservableObject,CLLocationManagerDelegate {
               let manager = CLLocationManager()
    
               @Published var location: CLLocationCoordinate2D?
    
               override init() {
                   super.init()
                   manager.delegate = self
               }
    
               func requestLocation() {
                   manager.requestLocation()
               }
    
               func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
                   location = locations.first?.coordinate
               }
           }
    

    Now Initialize locationManager View Do as Following : -

           @StateObject var locationManager = LocationManager()
    

    Then request location using following code whenever you want to access user location : -

           locationManager.requestLocation()
    

    And now you can access location Using following : -

           locationManager.location.latitude 
    

    or

           locationManager.location.longitude