Swift AppIntentsを使用して、アプリにショートカットを作成、その3

その3:アプリに処理指示、アプリ起動、パラメータあり

AlbumShuffleIntents.swift

import Foundation
import AppIntents
import SwiftUI

struct AlbumShuffleIntentAppRun: AppIntent {
    static var title: LocalizedStringResource = "Album Shuffle App Run"
    static var description = IntentDescription("Execute 'Shuffle' or 'Shuffle & Play'.")
    
    static var openAppWhenRun: Bool = true

    @Parameter(title: "Shuffle Type")
    var shuffleType: AlbumShuffleType
    
    @MainActor
    func perform() async throws -> some IntentResult {
        if shuffleType == .shuffle {
            Music.shared.autoRun = true
        }
        Music.shared.selection = 1
        Music.shared.albumShuffle()
        if shuffleType == .shuffleandplay {
            Music.shared.play()
        }
        return .result()
    }
    
    static var parameterSummary: some ParameterSummary {
        Summary("Shuffle type \(\.$shuffleType)")
    }
}

enum AlbumShuffleType: String, AppEnum {
    case shuffle
    case shuffleandplay

    static var typeDisplayRepresentation: TypeDisplayRepresentation = "Shuffle Type"
        static var caseDisplayRepresentations: [AlbumShuffleType: DisplayRepresentation] = [
        .shuffle: "Shuffle",
        .shuffleandplay: "Shuffle & Play",
    ]
}

struct AlbumShuffleAppRunShortcuts: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        AppShortcut(
            intent: AlbumShuffleIntentAppRun(),
            phrases: [
                "\(.applicationName)",
            ]
        )
    }
    static var shortcutTileColor: ShortcutTileColor = .blue
}

SwiftSwift,SwiftUI

Posted by shi-n