我正在嘗試構建一個簡單的應用程式,該應用程式具有允許用戶發送自動包含其位置的短信的功能。我找到了一些代碼,但是它們要么是舊的,要么是使用 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)")
}
}
uj5u.com熱心網友回復:
您正在混合 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483979.html
