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

史黛西库克

我是 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 的代码。首先,您必须创建位置管理器类,然后将该类分配给 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 视图执行以下操作: -

       @StateObject var locationManager = LocationManager()

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

       locationManager.requestLocation()

现在您可以使用以下命令访问位置:-

       locationManager.location.latitude 

或者

       locationManager.location.longitude

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章