Я пытаюсь создать намерение приложения, которое позволяет пользователю выбирать день в маршруте поездки. Поездка должна быть выбрана до того, как можно отобразить доступные дни. Иллюстрация: < /p>
// Entity Definition:
import AppIntents
struct ShortcutsItineraryDayEntityDemo: Identifiable, Hashable, AppEntity {
typealias DefaultQuery = TripItineraryDayQueryDemo
static var typeDisplayRepresentation: TypeDisplayRepresentation = "Trip Itinerary Day"
var displayRepresentation: DisplayRepresentation {
"Trip Day"
}
var id: String
static var defaultQuery: DefaultQuery {
TripItineraryDayQueryDemo()
}
init() {
self.id = UUID().uuidString //itineraryDay.id?.uuidString ?? itineraryDay.date.formatted()
}
}
struct TripItineraryDayQueryDemo: EntityQuery {
// This is only works in shortcut editor but not at runtime. Why? How can I fix this issue?
@IntentParameterDependency(\.$tripEntity)
var tripEntity
@IntentParameterDependency(\.$title)
var intentTitle
func entities(for identifiers: [ShortcutsItineraryDayEntityDemo.ID]) async throws -> [ShortcutsItineraryDayEntityDemo] {
print("entities being called with identifiers: \(identifiers)")
// This method is called when the app needs to fetch entities based on identifiers.
let tripsStore = TripsStore()
guard let trip = tripEntity?.tripEntity.trip,
let itineraryId = trip.firstItineraryId else {
print("No trip or itinerary ID can be found for the selected trip.")
return []
}
return [] // return empty for this demo
}
func suggestedEntities() async throws -> [ShortcutsItineraryDayEntityDemo] {
print("suggested itinerary days being called")
let tripsStore = TripsStore()
guard let trip = tripEntity?.tripEntity.trip,
let itineraryId = trip.firstItineraryId else {
print("No trip or itinerary ID found for the selected trip.")
return []
}
return []
}
}
< /code>
// Entity that fetches trips for user to pick from when PlanActivityIntentDemo intent is ran from shortcuts app
struct ShortcutsTripEntity: Codable, AppEntity {
init(id: String, title: String) {
self.id = id
self.title = title
}
init(id: String, title: String, trip: Trip) {
self.id = id
self.title = title
self.trip = trip
}
var id: String
@Property(title: "Title")
var title: String
var photoURL: String?
var trip: Trip = Trip()
static var typeDisplayRepresentation: TypeDisplayRepresentation {
"Trip"
}
var displayRepresentation: DisplayRepresentation {
// return .init(title: "\(title)")
guard let photoURL = URL(string: photoURL ?? ""),
let imageData = try? Data(contentsOf: photoURL) else {
return .init(title: "\(title)", image: .init(systemName: "photo.fill"))
}
return .init(title: "\(title)", image: .init(data: imageData))
}
static var defaultQuery = TripQuery()
static func getRemoteEntities() async throws -> [ShortcutsTripEntity] {
let result = await DBAPIService.shared.getTrips()
switch result {
case .success(let trips):
return trips.compactMap { trip in
guard let id = trip.id else { return nil }
return ShortcutsTripEntity(id: id.uuidString, title: trip.title, trip: trip)
}
case .failure(let error):
throw error
}
}
struct TripQuery: EntityPropertyQuery {
static var properties = EntityQueryProperties {
Property(\ShortcutsTripEntity.$title) {
EqualToComparator { NSPredicate(format: "title = %@", $0) }
ContainsComparator { NSPredicate(format: "title CONTAINS %@", $0) }
}
}
static var sortingOptions = SortingOptions {
SortableBy(\ShortcutsTripEntity.$title)
}
func entities(for identifiers: [String]) async throws -> [ShortcutsTripEntity] {
// Lookup trips by ID (e.g., from cache or database)
print("fetcing all trips for identifires: \(identifiers)")
let entities = try await getRecentlyCreatedEntities().filter({ identifiers.contains($0.id) })
print(entities)
return entities
}
func suggestedEntities() async throws -> [ShortcutsTripEntity] {
print("fetching suggested trips")
return try await getRecentlyCreatedEntities()
}
func entities(matching string: String) async throws -> [ShortcutsTripEntity] {
try await ShortcutsTripEntity.getRemoteEntities().filter({$0.title.localizedCaseInsensitiveContains(string)})
}
private func getRecentlyCreatedEntities() async throws -> [ShortcutsTripEntity] {
// returns 10 recently created trips by default
try await ShortcutsTripEntity.getRemoteEntities()
}
func entities(matching comparators: [NSPredicate], mode: ComparatorMode, sortedBy: [Sort], limit: Int?) async throws -> [ShortcutsTripEntity] {
try await ShortcutsTripEntity.getRemoteEntities()
}
}
< /code>
struct PlanActivityIntentDemo: AppIntent {
static var title: LocalizedStringResource { "Plan New Activity" }
// The selected trip fails to get injected when intent is run from shortcut app
@Parameter(title: "Trip", description: "The trip to plan an activity for", requestValueDialog: "Which trip would you like to plan an activity for?")
var tripEntity: ShortcutsTripEntity
@Parameter(title: "Activity Title", description: "The title of the activity", requestValueDialog: "What do you want to do or see?")
var title: String
@Parameter(title: "Activity Day", description: "Activity Day")
var activityDay: ShortcutsItineraryDayEntity
func perform() async throws -> some ProvidesDialog {
// This is a demo intent, so we won't actually perform any actions.
.result(dialog: "Activity '\(title)' planned")
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... app-intent
Как вводить зависимость параметров во время выполнения в приложении для iOS ⇐ IOS
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как вводить зависимость параметров во время выполнения в приложении для iOS
Anonymous » » в форуме IOS - 0 Ответы
- 7 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как вводить зависимость параметров во время выполнения в приложении для iOS
Anonymous » » в форуме IOS - 0 Ответы
- 15 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как вводить зависимость параметров во время выполнения в приложении для iOS
Anonymous » » в форуме IOS - 0 Ответы
- 8 Просмотры
-
Последнее сообщение Anonymous
-