Я работаю над приложением для 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
CLLocationManager в AppIntent ⇐ IOS
Программируем под IOS
1719971603
Anonymous
Я работаю над приложением для 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!")
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78699785/cllocationmanager-in-appintent[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия