Я работаю над приложением для iOS, которое поможет автостопщикам документировать свои поездки. Было бы очень удобно иметь ярлык iOS для создания записи как для мест получения, так и для мест высадки. Для этого проекта я использую SwiftUI и SwiftData. Записи должны включать текущее местоположение. Ниже приведен мой объект AppIntent AddTripRecord.
Я могу без проблем получить доступ к текущему местоположению в приложении, используя аналогичный IntentLocationManager. Однако, когда я пытаюсь использовать его внутри моего AddTripRecord, кажется, что метод DidUpdateLocations никогда не вызывается.
Что-то мне не хватает? Я просто любитель Swift.
import Foundation
import AppIntents
import CoreLocation
class IntentLocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
var locationContinuation: CheckedContinuation?
let manager = CLLocationManager()
@Published var lastLocation: CLLocation?
@Published var locationError: CLError?
@Published var authorizationStatus: CLAuthorizationStatus
override init() {
self.authorizationStatus = manager.authorizationStatus
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
checkAuthorizationStatus()
}
func requestLocation() async throws -> CLLocationCoordinate2D? {
try await withCheckedThrowingContinuation { continuation in
locationContinuation = continuation
manager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
NSLog(String(describing: locations.first?.coordinate))
locationContinuation?.resume(returning: locations.first?.coordinate)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
NSLog(error.localizedDescription)
locationContinuation?.resume(throwing: error)
}
func checkAuthorizationStatus() {
switch manager.authorizationStatus {
case .notDetermined, .authorizedWhenInUse:
manager.requestAlwaysAuthorization()
case .restricted, .denied:
self.locationError = CLError(.denied)
case .authorizedAlways:
NSLog("startUpdatingLocation")
manager.startUpdatingLocation()
@unknown default:
self.locationError = CLError(.locationUnknown)
}
self.authorizationStatus = manager.authorizationStatus
NSLog(String(describing: manager.isAuthorizedForWidgetUpdates))
}
}
struct AddTripRecord: AppIntent {
static var title = LocalizedStringResource("Add a new trip record")
@Parameter(title: "Trip")
var trip: TripIntentItem
@Parameter(title: "Record Type")
var recordType: TripRecordType
func perform() async throws -> some IntentResult {
let locationManager = IntentLocationManager()
let location = try await locationManager.requestLocation()
guard let currentLocation = location else {
return .result(value: "Failed to get current location")
}
let recordLocation = CLLocationCoordinate2D(latitude: currentLocation.latitude, longitude: currentLocation.longitude)
let record = TripRecord(type: recordType, content: "", location: recordLocation)
// trip.records.append(record)
// try! await SharedDatabase.shared.database.save()
return .result(value: "Trip record successfuly saved!")
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... -appintent