在短信中自动包含用户的当前位置 (Swift)

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

我正在尝试构建一个简单的应用程序,该应用程序具有允许用户发送自动包含其位置的短信的功能。我找到了一些代码,但它们要么旧了,要么正在使用 objective-c。我已经了解了消息的发送,但是我不知道如何自动将用户的当前位置放入消息正文中。

到目前为止,这是我的代码:

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)")

    }
}

您正在混合 UIKit 和 SwiftUI 的代码。首先,您必须创建位置管理器 class,然后将 class 分配给 StateObject 并在 SWiftUI 视图中使用它。

使用以下位置管理器:-

       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
           }
       }

现在初始化 locationManager View 执行以下操作:-

       @StateObject var locationManager = LocationManager()

然后在您想要访问用户位置时使用以下代码请求位置:-

       locationManager.requestLocation()

现在您可以使用以下方式访问位置:-

       locationManager.location.latitude 

       locationManager.location.longitude