animateWithDuration lacks completion block, WatchOS 2

1.2k views Asked by At

watchOS 2 does not have any kind of completion block in its animateWithDuration function. I'm working on a game that requires running code after an animation is completed. Are there any work arounds? Perhaps using key-value observation? The alternative would be to use a timer that matches up with the length of the animation but that's non-ideal for obvious reasons.

4

There are 4 answers

2
Puneet Sethi On BEST ANSWER

NSOperation didn't work for me too. I am just using the following solution for now until Apple officially adds a completion block. Not ideal but it works. I have opened a Radar. Maybe Apple would add a completion block in a future seed of watchOS 2.

This extension adds an animateWithDuration method that takes a completion block. And the completion block is called after the duration of the animation block.

extension WKInterfaceController {
    func animateWithDuration(duration: NSTimeInterval, animations: () -> Void, completion: (() -> Void)?) {
        animateWithDuration(duration, animations: animations)
        let completionDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Double(NSEC_PER_SEC)))
        dispatch_after(completionDelay, dispatch_get_main_queue()) {
            completion?()
        }
    }
}
0
Matheus Sousa On

You can use this extension. It's a better solutions because it doesn't rely on time like dispatching a block of code after the same amount of time as your animation with a delay. And it's elegant.

extension WKInterfaceController {
    func animate(withDuration duration: TimeInterval,
                 animations: @escaping () -> Swift.Void,
                 completion: @escaping () -> Swift.Void) {

        let queue = DispatchGroup()
        queue.enter()

        let action = {
            animations()
            queue.leave()
        }

        self.animate(withDuration: duration, animations: action)

        queue.notify(queue: .main, execute: completion)
    }
}

And you can use it, easily like this:

self.animate(withDuration: 0.2, animations: {
    //your animation code
}, completion: {
    //to do after you animation 
})
0
Alchi On

Swift 4

advanced animate() method for watchOS:

  • Repeatable
  • Reversible
  • Stoppable
  • with completion block

import Foundation
import WatchKit



protocol Animatable: class {

func animate(forKey key: String,duration: TimeInterval, repeatCount count: CGFloat, autoreverses: Bool, animations: @escaping () -> Void, reverseAnimations: (() -> Void)?, completion: (() -> Void)?)
func stopAnimations()
}

extension Animatable {

func animate(forKey key: String, duration: TimeInterval, repeatCount count: CGFloat, autoreverses: Bool, animations: @escaping () -> Void, reverseAnimations: (() -> Void)?, completion: (() -> Void)?) {}

func stopAnimations() {}
}

extension WKInterfaceController: Animatable {

private struct AssociatedKeys {
    static var animsDesc = "_animsDesc"
    static var stopDesc = "_stopDesc"
}

var animations: [String: (() -> Void)?] {
    get {return objc_getAssociatedObject(self, &AssociatedKeys.animsDesc) as? [String: (() -> Void)?] ?? [:]}
    set {objc_setAssociatedObject(self, &AssociatedKeys.animsDesc, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)}
}

var animationStopStates: [String: Bool] {
    get {return objc_getAssociatedObject(self, &AssociatedKeys.stopDesc) as? [String: Bool] ?? [:]}
    set {objc_setAssociatedObject(self, &AssociatedKeys.stopDesc, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)}
}

func animate(forKey key: String, duration: TimeInterval, repeatCount count: CGFloat = 1.0, autoreverses: Bool = false, animations: @escaping () -> Void, reverseAnimations: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
    let isStopped = self.animationStopStates[key] ?? false
    if isStopped {
        completion?()
        return
    }
    self.setAnimations(key, reverse: reverseAnimations)
    let count = count - 1
    let deadline = DispatchTime.now() + duration
    self.animate(withDuration: duration, animations: animations)
    DispatchQueue.main.asyncAfter(deadline: deadline) {
        var deadline2 = DispatchTime.now()
        if autoreverses, let rev = reverseAnimations {
            self.animate(withDuration: duration, animations: rev)
            deadline2 = DispatchTime.now() + duration
        }
        DispatchQueue.main.asyncAfter(deadline: deadline2, execute: {
            if !count.isEqual(to: .infinity) && count <= 0 {
                completion?()
            } else {
                self.animate(forKey: key, duration: duration, repeatCount: CGFloat(count), autoreverses: autoreverses, animations: animations, reverseAnimations: reverseAnimations, completion: completion)
            }
        })
    }
}


/// Stops all the currently playing animations
func stopAnimations() {
    for key in self.animations.keys {
        guard let rev = self.animations[key] else {return}
        self.animationStopStates[key] = true
        self.animate(forKey: key, duration: 0, repeatCount: 0, autoreverses: false, animations: {}, reverseAnimations: rev)
    }
    self.animations.removeAll()
}


private func setAnimations(_ key: String, reverse: (() -> Void)?) {
    if self.animations[key] == nil {
        self.animations[key] = reverse
    }

}
}

How to use:

self.animate(forKey: "custom_anim1", duration: 1.0, repeatCount: .infinity, autoreverses: true, animations: {[unowned self] in
        self.myButton.setHeight(100)
    }, reverseAnimations: { [unowned self] in
        self.myButton.setHeight(120)
    }) {
        print("Animation stopped!")
    }

To stop all the animations:

self.stopAnimations()
0
Reyes Magos On

Try to extend animateWithDuration method with a completion block in your WKInterfaceController

Obj-C version (Thanks @PunnetSethi):

- (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(void))completion{

    [self animateWithDuration:duration animations:animations];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), completion);

}

Working on real Watch with WatchOS2