在使用导航链接进行导航之前使用AVAudioPlayer导航回到第一页

时间:2020-06-25 15:49:13

标签: ios swift swiftui avaudioplayer navigationview

我正在构建一个警报应用程序,其中使用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)
        }
      }
    }
  }
}

0 个答案:

没有答案