Приложение Swift timer перестает работать в фоновом режиме - PullRequest
0 голосов
/ 15 апреля 2020

Я работаю над личным IOS приложением таймера, но по какой-то причине таймер просто останавливается всякий раз, когда я выхожу из приложения, я не слишком уверен, что это такое, так как я сделал более простые приложения таймера, которые работают на заднем плане прекрасно, но этот работает в течение 1 секунды, а затем просто останавливается. Любая подсказка, если есть что-то не так с кодом? Спасибо за любую помощь.

import UIKit
import UserNotifications
import AVFoundation

class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

 let notificationCenter = UNUserNotificationCenter.current()
        let options: UNAuthorizationOptions = [.alert, .sound, .badge]
        notificationCenter.requestAuthorization(options: options) {
            (didAllow, error) in
            if !didAllow {
                print("User has declined notifications")
            }
        }

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

        view.addGestureRecognizer(tap)



    }

    var counter = 0
    var timer:Timer?
    var timeLeft:Int = 60
    var periodTwoTime: Int = 0
    var periodOneTime: Int = 0
    var firstTimerRunning: Bool = true
    var audioPlayer: AVAudioPlayer?
    var soundEnabled = true


    @IBOutlet weak var timeRemaining: UILabel!
    @IBOutlet weak var periodOne: UITextField!
    @IBOutlet weak var periodTwo: UITextField!

    @objc func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }

    //Function to switch to second timer (periodTwo)
    func secondTimer(){
        timeLeft = periodTwoTime
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
            }
    //plays first timer
    func firstTimer(){
        timeLeft = periodOneTime
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
    }



    // START FUNCTION HERE
    @IBAction func startTimer(_ sender: UIButton) {
        timer?.invalidate()
        periodOneTime = Int(periodOne.text!)!
        periodTwoTime = Int(periodTwo.text!)!
        timeLeft = periodOneTime
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)


    }

    @IBAction func stopTimer(_ sender: UIButton) {
        timer?.invalidate()
        timeRemaining.text = "0"
        timer = nil
    }


    @objc func onTimerFires()
    {
        timeLeft -= 1
        timeRemaining.text = String(timeLeft)

        if timeLeft <= 0 {
            timer?.invalidate()

        }
        //checks if time left is 0, then checks if the first tiemr is running and sets a timer accordingly
        if timeLeft == 0 {
            if firstTimerRunning == true{
            firstTimerRunning = false
                timer?.invalidate()
                secondTimer()

            }
            else {
                firstTimerRunning = true
                timer?.invalidate()
                firstTimer()
            }
            // play notification here

            sendNotification(neega: Double(timeLeft))

            let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "alarm_sound", ofType: "mp3")!)
            try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            try! AVAudioSession.sharedInstance().setActive(true)
            try! audioPlayer = AVAudioPlayer(contentsOf: alertSound)
            audioPlayer?.prepareToPlay()
            if soundEnabled {
            // play sound
            audioPlayer?.play()
            }



                }
            }

        }


func sendNotification(neega: Double){
        let content = UNMutableNotificationContent()
        content.title = "Timer up!"
        content.body = "Switch up the pace now!"
        content.sound = UNNotificationSound.default
        content.categoryIdentifier = "timer.category"

        let trigger = UNTimeIntervalNotificationTrigger(
                       timeInterval: Double(neega), repeats: false) //close to immediate as we can get.

        let request = UNNotificationRequest(identifier: "timer.request", content: content, trigger: trigger)
             UNUserNotificationCenter.current().add(request) { (error) in
                 if let error = error{
                     print("Error posting notification:\(error.localizedDescription)")
                }
        }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...