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

その2:アプリに処理指示、View表示、パラメータなし

AlbumShuffleIntents.swift

import Foundation
import AppIntents
import SwiftUI

struct AlbumShuffleIntent: AppIntent {
    static var title: LocalizedStringResource = "Album Shuffle"
    static var description = IntentDescription("Execute Shuffle & Play.")
    
    @MainActor
    func perform() async throws -> some ShowsSnippetView {
        Music.shared.albumShuffle()
        Music.shared.play()
        return .result {
            AlbumShuffleSnippetView()
        }
    }
}

AlbumShuffleSnippetView.swift

import SwiftUI

struct AlbumShuffleSnippetView: View {
    var body: some View {
        VStack(spacing: 8.0) {
            Label(Music.shared.albumTitle(collection: Music.shared.selectMPMediaItemCollection), systemImage: "opticaldisc")
                .font(.body)
            Label(Music.shared.artistName(collection: Music.shared.selectMPMediaItemCollection), systemImage: "person")
                .font(.body)
                .lineLimit(1)
            Label(Music.shared.albumTracks(collection: Music.shared.selectMPMediaItemCollection), systemImage: "music.note.list")
                .font(.body)
                .lineLimit(1)
        }
        .foregroundColor(.white)
    }
}
  • import SwiftUI大事!!これがないとShowsSnippetViewの応答コードがコンパイルエラーになる
  • AlbumShuffleSnippetView()はSwiftUI

SwiftSwift,SwiftUI

Posted by shi-n