animateWithDuration lacks completion block, WatchOS 2
Asked Answered
Z

4

5

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.

Zinnia answered 13/6, 2015 at 22:42 Comment(5)
I haven't tested this yet, but using NSOperation sounds like a good way to deal with this problem. WWDC '15 just did a brilliant talk about it. Encapsulate the animation into a NSOperation and put the completion stuff in another NSOperation, then add a dependancy such that the completion stuff depends on the the animation finishing. That'll act as a completion block.Elegit
I'll give it a shot, thanks! Any chance you remember the name of the talk, on the off chance it was recorded?Zinnia
Titled: "Advanced NSOperations"Elegit
Sadly didn't seem to work :( Animation just runs and completion block runs immediately after animation starts.Zinnia
That's odd. Can you post your code with the NSOperationsElegit
O
6

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?()
        }
    }
}
Olivette answered 21/6, 2015 at 2:58 Comment(2)
Indeed, this is the conclusion I came to as well. It's not ideal by any means...But it works :/Zinnia
I have seen this works well on the simulator but not on the real device though. :(Olivette
M
2

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

Mathes answered 5/10, 2015 at 20:27 Comment(0)
D
0

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()
Denominationalism answered 5/4, 2018 at 13:50 Comment(0)
C
0

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 
})
Colo answered 30/7, 2018 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.