I am asynchronously running a CAAnimation (animated gradient) in my app as the background image. When the home button is clicked (going to the home screen w/o closing the app) and then you re-enter the app, there is a UIApplicationEndBackgroundTaskError. I would really appreciate if someone could figure this out. A side effect of this error is the animation stops playing/it pauses. Thanks! (look below for more info)
I used a symbolic break to see the error and the result is the image below:
The code for the background is here (used in a SwiftUI View) as GradientView():
struct GradientView: UIViewControllerRepresentable {
typealias UIViewControllerType = GradientBackground
func makeUIViewController(context: UIViewControllerRepresentableContext<GradientView>) -> GradientView.UIViewControllerType {
return GradientBackground()
}
func updateUIViewController(_ uiViewController: GradientView.UIViewControllerType, context: UIViewControllerRepresentableContext<GradientView>) {
}
}
class GradientBackground : UIViewController {
let gradient = CAGradientLayer()
var gradientSet = [[CGColor]]()
var currentGradient = 0
let gradOne = #colorLiteral(red: 0.4620226622, green: 0.8382837176, blue: 1, alpha: 1).cgColor
let gradTwo = #colorLiteral(red: 1, green: 0.8323456645, blue: 0.4732058644, alpha: 1).cgColor
let gradThree = #colorLiteral(red: 0, green: 0.3285208941, blue: 0.5748849511, alpha: 1).cgColor
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
animatedGradient()
}
override func viewDidLoad() {
super.viewDidLoad()
gradientSet.append([gradOne, gradTwo])
gradientSet.append([gradTwo, gradThree])
gradientSet.append([gradThree, gradOne])
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.drawsAsynchronously = true
//gradient.colors = [gradOne, gradTwo]
view.layer.addSublayer(gradient)
}
override func viewDidLayoutSubviews() {
gradient.frame = view.bounds
}
func animatedGradient() {
var prevGrad: Int!
if currentGradient < gradientSet.count - 1 {
currentGradient += 1
prevGrad = currentGradient-1
}
else {
currentGradient = 0
prevGrad = gradientSet.count-1
}
let gradChangeAnim = CABasicAnimation(keyPath: "colors")
gradChangeAnim.duration = 1.5
gradChangeAnim.fromValue = gradientSet[prevGrad]
gradChangeAnim.toValue = gradientSet[currentGradient]
gradient.setValue(currentGradient, forKeyPath: "colorChange")
gradChangeAnim.delegate = self
gradient.add(gradChangeAnim, forKey: nil)
}
}
extension GradientBackground: CAAnimationDelegate {
func animationDidStart(_ anim: CAAnimation) {
//if anim.
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
if let colorChange = gradient.value(forKey: "colorChange") as? Int {
var number = colorChange + 1
if number == gradientSet.count {
number = 0
}
gradient.colors = gradientSet[number]
animatedGradient()
}
}
}
}