Swordz
Swordz

Reputation: 35

UIView animation doesn't work if app goes to background

I have a little questions game where if the user takes too long to answer, it times out and automatically triggers a custom segue to a certain screen.

    let firstClassView = self.sourceViewController.view
    let secondClassView = self.destinationViewController.view
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height
    firstClassView.clipsToBounds = true
    secondClassView.clipsToBounds = true
    let secondClassFrame = CGRect(x: screenWidth, y: 0, width: screenWidth, height: screenHeight)
    secondClassView.frame = secondClassFrame
    guard let window = UIApplication.sharedApplication().keyWindow else {
        return
    }
    window.insertSubview(secondClassView, aboveSubview: firstClassView)
    if let questionVC = self.destinationViewController as? QuestionResultViewController {
        questionVC.prepareResultView()
    }
    UIView.animateWithDuration(0.4, animations: { () -> Void in
        firstClassView.frame = CGRectOffset(firstClassView.frame, -screenWidth, 0)
        secondClassView.frame = CGRectOffset(secondClassView.frame, -screenWidth, 0)
    }) {_ -> Void in
        self.sourceViewController.presentViewController(self.destinationViewController, animated: false, completion: nil)
    }

This code and the segue works fine, EXCEPT if the user sends the app to the background (and opens it again) before the segue. In this case, the UIView.animate block is reached, but it's contents seem to never be called, so no animation plays! (I got a print command in there, and it was not being triggered)

If my description was confusing:

Case 1:

Case 2:

Why is this happening? I tried using layoutIfNeeded and it's variations, but nothing worked. The animation block's contents are never called. From my tests using breakpoints, the app stops completely before it reaches the UIView line (and ends up crashing after ~10 seconds).

Upvotes: 0

Views: 463

Answers (1)

Swordz
Swordz

Reputation: 35

It turns out it had nothing to do with the UIView block. I had a custom UILabel class, and it's layoutSubviews method was entering an undetectable infinite loop after the app went to background.

Sorry for the confusion.

Upvotes: 1

Related Questions