Swift AppIntentsを使用して、アプリにショートカットを作成、その1
その1:アプリに処理指示、アプリ起動、パラメータなし
AlbumShuffleIntentsAppRun.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 @MainActor func perform() async throws -> some IntentResult { Music.shared.autoRun = true Music.shared.selection = 1 Music.shared.albumShuffle() return .result() } }
- titleはLocalizedStringResource型のため、ローカライズファイル設定している場合、ローカライズファイルで変換される
- 「static var openAppWhenRun: Bool = true」でアプリが起動される
- IntentResultは一番シンプルな型、valueが返せ次に繋げられる、上記は特に何も返さないパターン
参考までにMusic.swift抜粋
import Foundation import MediaPlayer import Algorithms import SwiftUI final class Music: ObservableObject { @Published var selection = 1 @Published var iCloud = false @Published var shufflePlay = false @Published var autoPlay = false @Published var minTracks: Int = 1 @Published var selectLibrary: UInt64 = 0 @Published var selectLibraryName: String = "Music Library" @Published var playlistList: [(UInt64, String)] = [] @Published var albumCount: Int = 0 @Published var backgroundColor: Int = 0 @Published var selectMPMediaItemCollection: MPMediaItemCollection? = nil @Published var autoRun = false : : : func albumShuffle() { let iCloudFilter = MPMediaPropertyPredicate(value: self.iCloud, forProperty: MPMediaItemPropertyIsCloudItem, comparisonType: .equalTo) let mPMediaQuery = MPMediaQuery.albums() mPMediaQuery.addFilterPredicate(iCloudFilter) var collections: [MPMediaItemCollection]? = [] if self.selectLibrary == 0 { collections = mPMediaQuery.collections } else { collections = self.playList(playlistid: self.selectLibrary) } if let collections = collections { let randomcollections = collections.randomSample(count: collections.count).filter({collection in collection.items.count >= self.minTracks}) if randomcollections.count > 0 { let randomAlbumIndex = Int.random(in: 0..<randomcollections.count) self.albumCount = randomcollections.count self.selectMPMediaItemCollection = randomcollections[randomAlbumIndex] } } } : : : }