我正在构建一个警报应用程序,其中使用AVAudioPlayer设置了警报声音。但是由于某些原因,当我设置AVAudioPlayer并导航到下一个视图时,它会立即导航回到NavigationView的第一页。我目前有以下代码:
import SwiftUI
import AVFoundation
import UserNotifications
struct SetAlarmView: View {
@State
var date = Date()
@EnvironmentObject
var alarm: Alarm
@State
var tagSelection: Int ? = nil
func setAlarm(secondsToAlarm: Double) - > Void {
let sound = Bundle.main.path(forResource: "simple", ofType: "mp3")
let player =
try !AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
player.play(atTime: player.deviceCurrentTime + secondsToAlarm)
}
func setupAlarmSession() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playback, options: [.defaultToSpeaker, .duckOthers])
try audioSession.setActive(true)
} catch {}
}
@ViewBuilder
var body: some View {
VStack {
DatePicker("", selection: $date).labelsHidden().onAppear {
self.setupAlarmSession()
}
Spacer()
NavigationLink(destination: ActiveAlarmView(), tag: 2, selection: $tagSelection) {
Button(action: {
let secondsToAlarm = self.date.timeIntervalSinceNow
self.setAlarmNotification(secondsToAlarm: secondsToAlarm)
self.setAlarm(secondsToAlarm: secondsToAlarm)
self.tagSelection = 2
}) {
HStack {
Image(systemName: "clock.fill").font(.title)
Text("Set Alarm").fontWeight(.semibold).font(.title)
}.frame(minWidth: 0, maxWidth: .infinity)
.padding().foregroundColor(.white)
.background(Color.purple)
.cornerRadius(40)
.padding(20)
}
}
}
}
}