how to trigger sequence of animations in swift - ios

In Swift 4 i am loaded/holding a set of animations from dae files in an array:
var animations = [String: CAAnimation]()
loadAnimation(withKey: "stepL", sceneName: "art.scnassets/StepL", animationIdentifier: "StepL-1")
loadAnimation(withKey: "stepR", sceneName: "art.scnassets/StepR", animationIdentifier: "StepR-1")
func loadAnimation(withKey: String, sceneName:String, animationIdentifier:String) {
let sceneURL = Bundle.main.url(forResource: sceneName, withExtension: "dae")
let sceneSource = SCNSceneSource(url: sceneURL!, options: nil)
if let animationObject = sceneSource?.entryWithIdentifier(animationIdentifier, withClass: CAAnimation.self) {
// The animation will only play once
animationObject.repeatCount = 1
// To create smooth transitions between animations
animationObject.fadeInDuration = CGFloat(0.8)
animationObject.fadeOutDuration = CGFloat(0.6)
// Store the animation for later use
animations[withKey] = animationObject
}
}
Later on i am playing the animation by adding it to my scene:
func playAnimation(key: String) {
print("fire animation: " + key)
scnView.scene?.rootNode.addAnimation(animations[key]!, forKey: key)
}
This seems to work when doing them individually from touches, but i want to be able to trigger a sequence of these with very specific timing.
I've tried building a loop and sending them off to a DispatchQueue with specific timing outlined:
var delaytime = state.steptime!
for _ in 0..<state.trCount! {
for wSide in state.walkSeq! {
walkQ.asyncAfter(deadline: .now() + delaytime){
self.playAnimation(key: wSide)
}
delaytime += state.steptime! + 1.0
}
}
And i've tried a similar, but slightly different approach using wallDeadline:
let wt = DispatchWallTime.now() + state.pausetime!
//build sequence
var train_seq = [(name:"stepL", time:wt), (name:"stepR",time:wt + state.pausetime! + state.steptime!)]
for _ in 0..<state.trCount! {
let lasttime = train_seq[ train_seq.count - 1 ].time
train_seq += [(name:"stepL", time:lasttime + state.steptime!)]
train_seq += [(name:"stepR", time:lasttime + state.pausetime! + state.steptime!)]
}
//send it
for i in 0..<train_seq.count {
walkQ.asyncAfter(wallDeadline: train_seq[i].time){
self.playAnimation(key: train_seq[i].name)
}
}
What inevitably happens is that the first few run as expected, then around the 4th set of sequences they start to stack on top of each other and fire at the same time, no longer adhering to the timing that i've defined
What is the best way to trigger animations in a sequence on an expected timeline? Is there a way to pause/sleep a loop until the previous animation stops, then trigger the next in the series?
Thanks!

i ended up making a sequence of SCNActions in the order i needed, including a wait
var seq = [SCNAction]()
for _ in 0..<state.trCount!{
let act1 = SCNAction.run {_ in
self.playAnimation(key: "stepL")
}
seq.append(act1)
let act2 = SCNAction.wait(duration: state.steptime!)
seq.append(act2)
let act3 = SCNAction.run { _ in
self.playAnimation(key: "stepR")
}
seq.append(act3)
seq.append(act2)
let act4 = SCNAction.run { _ in
self.playAnimation(key: "idle")
}
seq.append(act4)
let act5 = SCNAction.wait(duration: state.pausetime!)
seq.append(act5)
}
let sequence = SCNAction.sequence(seq)
scnView.scene?.rootNode.runAction(sequence, completionHandler:nil )

Related

An array of a value not being properly displayed in the label

I am using xcode 8 and swift 3. I have made a mini game where you have to answer questions as fast as you can. You are timed by a stopwatch. I have the code to actually store the times(eg 23 seconds) but instead of storing the time, it replaces it with "Label". My stopwatch label is called down and the label that displays the values is called resultLabel I have been told the problem is when i set the text of the label. Any ideas on where i need to fix it. An example is ["Label", "Label", "Label"]
Stopwatch code:
if timerSecond != nil {
timerSecond?.invalidate()
timerSecond = nil
} else {
timerSecond = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
self.currentTime += 1
let minutePortion = String(format: "%02d", self.currentTime / 60 )
let secondsPortion = String(format: "%02d", self.currentTime % 60 )
self.down.text = "\(minutePortion):\(secondsPortion)"
}
}
extension for User Defaults:
extension UserDefaults {
var timesSecond: [String] {
get {
if let times = UserDefaults.standard.object(forKey: "times") as? [String] {
return times
} else {
return []
}
}
set {
UserDefaults.standard.set(newValue, forKey: "times")
}
}
}
Button code to display the array of values:
let arrayOfTimes = UserDefaults.standard.timesSecond
resultLabel.text = "\(arrayOfTimes)"
code for storing the data:
UserDefaults.standard.timesSecond.append(resultLabel.text!)

Argument labels "(attributes:)" do not match any available overloads in DispatchQueue

I am trying to make the enemy in my game move using DispatchQueue. I tried fixing this error and it keeps telling me attributes do not match any available overloads.
func makeAIMove() {
let strategistTime = CFAbsoluteTimeGetCurrent()
DispatchQueue.global(attributes: .qosUserInitiated).async { [unowned self] in
guard let move = self.strategist.bestMoveForActivePlayer() as? Move else { return }
let delta = CFAbsoluteTimeGetCurrent() - strategistTime
DispatchQueue.main.async{ [unowned self] in
self.rows[move.row][move.col].setPlayer(.choose)
let aiTimeCeiling = 2.0
let delay = min(aiTimeCeiling - delta, aiTimeCeiling)
DispatchQueue.main.after(when: .now() + delay) { [unowned self] in
self.makeMove(row: move.row, col: move.col)
}
}
}
}
I think what you want is DispatchQueue.global(qos: .userInitiated); indeed, there is no overload taking an attributes argument.

UIImageView wait for animation complete

I'm trying to execute 2 different animations, after the first complete, using isAnimating.
but, I see only the first animation...
if anims[0] == 1{
startAnimation(image : #imageLiteral(resourceName: "first"))
}
if anims[1] == 2{
while myView.isAnimating {
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.05))
}
}
startAnimation(image : #imageLiteral(resourceName: "second") , time : Int)
spriteSheet returns UIImage array after cropping..
func startAnimation(image : UIImage , time : Int){
myView.animationImages = image.spriteSheet(cols: 19, rows: 1)
myView.animationDuration = 1
myView.animationRepeatCount = time
myView.startAnimating()
}
You can always chain animations like
UIView.animate(withDuration: 1, animations: {
//do your animation here
}) { (state) in
UIView.animate(withDuration: 1, animations: {
//do your second animation
})
}
If you are using CABasicAnimations then you can use beginTime and duration to chain them up :)
var totalDuration = 0
let baseicAnim1 = CABasicAnimation()
baseicAnim1.beginTime = CACurrentMediaTime()
totalDuration += 10
baseicAnim1.duration = CFTimeInterval(totalDuration)
let basicAnim2 = CABasicAnimation()
basicAnim2.beginTime = CACurrentMediaTime() + CFTimeInterval(totalDuration)
totalDuration += 10
basicAnim2.duration = CFTimeInterval(totalDuration)
EDIT
Using while loop to keep checking if animation has completed its execution or not is never a suggested approach
EDIT :
Try this,
func startAnimation(image : UIImage , time : Int,completionBlock : (()->())?){
let animationDuration = 1
myView.animationImages = image.spriteSheet(cols: 19, rows: 1)
myView.animationDuration = animationDuration
myView.animationRepeatCount = time
myView.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + animationDuration, execute: {
if let block = completionBlock {
block()
}
})
}
Now your startAnimation function takes completion block as its parameter and executes the completion block after animationDuration. So you can get to know when animation ends :)
to chain simply call
self.startAnimation(image: #imageLiteral(resourceName: "first"), time: 1) {
self.startAnimation(image: #imageLiteral(resourceName: "second"), time: 1, completionBlock: nil)
}
Hope it helps

How to chain Facebook pop Animations in a continuous repeatForever?

SITUTATION:
I have created a pulsating animation and it works.
Using the repeatForever property, I was able to make it continuous as I wanted.
But one issue remains that I wasn't able to fix after doing A LOT of research.
EXPLANATION:
The only problem is that I don't know how to add one more animation that makes the Image go back to it's original size before pulsating again.
The challenge for me resides in the fact that if I declare it after the other one, it will not be called as it will not be included in the repeatForeverloop.
Therefore, the animation I have right now is not smooth as once it completes, the image instantly goes back to it's original size before repeating itself.
WHAT HAPPENS:
1) Image pulsates to 1.2 of current size thx to animation.
THIS IS NOT SMOOTH:
2) Animation finishes at 1.2 and Image instantly "warps" back to 1.0
3) Animation repeats itself. Image pulsates to 1.2 again.
PROBLEM: How can I change my pulsatingAnimation so that my image goes back to it's original size in a smooth way before pulsating again ?
CODE:
import Foundation
import pop
class AnimationEngine {
func pulsate(object: UIImageView) {
let pulsateAnim = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
pulsateAnim.velocity = NSValue(CGSize: CGSizeMake(0.1, 0.1))
pulsateAnim.toValue = NSValue(CGSize: CGSizeMake(1.2, 1.2))
pulsateAnim.springBounciness = 18
pulsateAnim.dynamicsFriction = 20
pulsateAnim.springSpeed = 1.0
pulsateAnim.repeatForever = true
// pulsateAnim.autoreverses = true
object.layer.pop_addAnimation(pulsateAnim, forKey: "layerScaleSpringAnimation")
}
}
I found the Solution.
SOLUTION:
func pulsate(object: UIImageView) {
let pulsateAnim = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
let returnToSizeAnim = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY)
object.layer.pop_addAnimation(pulsateAnim, forKey: "layerScaleSpringAnimation")
pulsateAnim.velocity = NSValue(CGSize: CGSizeMake(0.1, 0.1))
pulsateAnim.toValue = NSValue(CGSize: CGSizeMake(1.2, 1.2))
pulsateAnim.springBounciness = 30
pulsateAnim.dynamicsFriction = 20
pulsateAnim.springSpeed = 1.0
pulsateAnim.completionBlock = {(animation, finished) in
object.layer.pop_addAnimation(returnToSizeAnim, forKey: "layerScaleSpringAnimation")
}
returnToSizeAnim.toValue = NSValue(CGSize: CGSizeMake(1.0, 1.0))
returnToSizeAnim.duration = 0.5
returnToSizeAnim.completionBlock = {(animation, finished) in
object.layer.pop_addAnimation(pulsateAnim, forKey: "layerScaleSpringAnimation")
}
}
func pulsate2(object: UIImageView) {
let pulsateAnim = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
let returnToSizeAnim = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY)
object.layer.pop_addAnimation(pulsateAnim, forKey: "layerScaleSpringAnimation")
pulsateAnim.velocity = NSValue(CGSize: CGSizeMake(0.1, 0.1))
pulsateAnim.toValue = NSValue(CGSize: CGSizeMake(1.2, 1.2))
pulsateAnim.springBounciness = 30
pulsateAnim.dynamicsFriction = 20
pulsateAnim.springSpeed = 1.0
pulsateAnim.completionBlock = {(animation, finished) in
object.layer.pop_addAnimation(returnToSizeAnim, forKey: "layerScaleSpringAnimation")
}
returnToSizeAnim.toValue = NSValue(CGSize: CGSizeMake(1.0, 1.0))
returnToSizeAnim.duration = 0.5
returnToSizeAnim.completionBlock = {(animation, finished) in
object.layer.pop_addAnimation(pulsateAnim, forKey: "layerScaleSpringAnimation")
}
}
N.B.:
I need to declare one pulsate function for each object I want to use it on. If I don't do that, the second time I call the function, it won't work properly because an instance of the animations is already running.
I'm a huge ReactiveCocoa nerd so I built a class around POPAnimation so I could deal with animations in a more functional manner.
import Foundation
import ReactiveCocoa
import pop
import Result
/**
`UIView` wrapper for performing reactive-based pop animations.
*/
public struct ReactivePOPView<View: UIView> {
/// View object
private weak var view: View?
/// `SignalProducer` object when the wrapper is about to deallocate.
private let willDealloc: SignalProducer<Void, NoError>
/// Wrapper on the view property.
private var animator: View? { return self.view }
/**
Create an animation wrapper with a view.
- parameter view: `UIView` object.
*/
public init(_ view: View) {
self.view = view
self.willDealloc = view
.willDeallocSignalProducer()
}
}
/**
Binds a `Signal` that emits an animation object to a `ReactivePOPView`.
- parameter view: `ReactivePOPView` object.
- parameter signal: `Signal` object.
- returns: `Disposable` object.
*/
public func <~ <T, Animation: POPAnimation>(view: ReactivePOPView<T>, signal: Signal<Animation, NoError>) -> Disposable {
let disposable = CompositeDisposable()
let viewDisposable = view.willDealloc.startWithCompleted {
disposable.dispose()
}
disposable.addDisposable(viewDisposable)
let signalDisposable = signal.observe(Observer(next: {
view.animator?.pop_addAnimation($0, forKey: $0.name ?? "")
}, completed: {
disposable.dispose()
}))
disposable.addDisposable(signalDisposable)
return disposable
}
/**
Binds a `SignalProducer` that emits an animation object to a `ReactivePOPView`.
- parameter view: `ReactivePOPView` object.
- parameter producer: `SignalProducer` object.
- returns: `Disposable` object.
*/
public func <~ <T, Animation: POPAnimation>(view: ReactivePOPView<T>, producer: SignalProducer<Animation, NoError>) -> Disposable {
var disposable: Disposable!
producer.startWithSignal { signal, signalDisposable in
view <~ signal
disposable = signalDisposable
view.willDealloc.startWithCompleted {
signalDisposable.dispose()
}
}
return disposable
}
/**
Bind a reactive animation property to a `ReactivePOPView` property.
- parameter destinationProperty: `ReactivePOPView` property.
- parameter sourceProperty: Animation property.
- returns: `Disposable` object.
*/
public func <~ <T, P: PropertyType where P.Value == POPAnimation>(destinationProperty: ReactivePOPView<T>, sourceProperty: P) -> Disposable {
return destinationProperty <~ sourceProperty.producer
}
With this class, you can do things like:
ReactivePOPView<UIButton>(self.loginButton) <~ self.someSignal.signal
.flatMap(.Concat) { _ in SignalProducer<POPBasicAnimation, NoError> in
let animation ...
// construct animation here
return SignalProducer(value: animation)
}
.repeat(0)
I also have a wrapper class for constraints if you want that.
I dont know Facebook pop , so I speak only about the analysis and logic to how to implement this feature (pulse effect)
As I've write in comments, what you want to do seems exactly what happened many times in SpriteKit where you , to make a specific animation (SKAction), have to build a series of actions.
Just to make a SpriteKit example, this is what I do to make a specific pulse effect:
let titleForward = runTitleForward()
let wait = SKAction.waitForDuration(5.0)
let titleBackward = runTitleBackward()
let titleAnim = SKAction.repeatActionForever((SKAction.sequence([titleForward, wait, titleBackward,wait ])))
title.runAction(titleAnim, withKey:"titleAnimation")
func runTitleForward()-> SKAction {
let atlascTexturesArray = self.myManager.atlascTexturesDictionary["title-anim"]
let texturesAction = SKAction.animateWithTextures(atlascTexturesArray!,timePerFrame: 0.09)
return texturesAction
}
func runTitleBackward()-> SKAction {
let texturesAction = runTitleForward()
let texturesReverseAction = SKAction.reversedAction(texturesAction)
return texturesReverseAction()
}
Hope you help to do the same thing in UIKit.
UPDATE: (I don't test it..)
func delayAnimation(duration:NSTimeInterval)-> CABasicAnimation {
let animation : CABasicAnimation = CABasicAnimation(keyPath: "opacity");
animation.delegate = self
animation.fromValue = 1
animation.toValue = 1 // fake animation, just to obtain duration delay..
animation.duration = duration
return animation
}
func pulseElements () -> (POPSpringAnimation,POPSpringAnimation) {
// zoom in
let pulsateInAnim = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
pulsateInAnim.velocity = NSValue(CGSize: CGSizeMake(0.1, 0.1))
pulsateInAnim.toValue = NSValue(CGSize: CGSizeMake(1.2, 1.2))
pulsateInAnim.springBounciness = 18
pulsateInAnim.dynamicsFriction = 20
pulsateInAnim.springSpeed = 1.0
// zoom out
let pulsateOutAnim = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
...
return (pulsateInAnim,pulsateOutAnim)
}
func pulseAnimation() {
let (pulsateInAnim,pulsateOutAnim) = pulseElements()
let wait = delayAnimation(1.0)
var pulseAnimationGroup: CAAnimationGroup = CAAnimationGroup()
pulseAnimationGroup.animations = [pulsateInAnim, wait, pulsateOutAnim, wait]
pulseAnimationGroup.duration = 0.5
pulseAnimationGroup.repeatCount = Float.infinity
object.layer.addAnimation(pulseAnimationGroup, forKey: layerScaleSpringAnimation)
}

stopping an asynchronous call once it's out in the wild in swift

I have some problems with my version of this loadingOverlay singleton.
What's supposed to happen, is it comes onto the screen, with a view and a label that has the text, "Loading, please wait." or something like that. then if loading is longer than 2 seconds (i've changed it to 10 for debugging) the text changes to a random cute phrase.
first of all the animation that should change the text doesn't seem to happen. instead, the text just instantly changes.
more importantly, If, for some reason, my asynchronous call block is executed multiple times, I only want the most recent call to it to run, and I want the previous instances of it to terminate before running.
I was reading about callbacks and promises, which look promising. Is that a swifty pattern to follow?
by the way, as I'm learning swift and iOS, I've been experimenting, and I tried [unowned self] and now i'm experimenting with [weak self], but I'm not really certain which is most appropriate here.
// from http://stackoverflow.com/questions/33064908/adding-removing-a-view-overlay-in-swift/33064946#33064946
import UIKit
class LoadingOverlay{
static let sharedInstance = LoadingOverlay()
//above swifty singleton syntax from http://krakendev.io/blog/the-right-way-to-write-a-singleton
var overlayView = UIView()
var spring: CASpringAnimation!
var springAway: CASpringAnimation!
var hidden = false
private init() {} //This line prevents others from using the default () initializer for this class
func setupSpringAnimation(startY: CGFloat, finishY: CGFloat) {
overlayView.layer.position.y = startY
spring = CASpringAnimation(keyPath: "position.y")
spring.damping = 10
spring.fromValue = startY
spring.toValue = finishY
spring.duration = 1.0
spring.fillMode = kCAFillModeBackwards
}
func showOverlay() {
print("show overlay")
overlayView.alpha = 1
hidden = false
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate,
let window = appDelegate.window {
setupSpringAnimation(-window.frame.height / 2, finishY: window.frame.height / 2)
let overlayViewFramesize = 0.65 * min(window.frame.height, window.frame.width)
overlayView.frame = CGRectMake(0, 0, overlayViewFramesize, overlayViewFramesize)
overlayView.center = window.center
overlayView.backgroundColor = UIColor.greenColor()
overlayView.clipsToBounds = true
overlayView.layer.cornerRadius = overlayViewFramesize / 8
let label = UILabel(frame: CGRectMake(0,0,overlayViewFramesize * 0.8 , overlayViewFramesize))
label.text = " \nLoading, please wait\n "
label.tag = 12
overlayView.addSubview(label)
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0 //as many as needed
label.sizeToFit()
label.textAlignment = NSTextAlignment.Center
label.center = CGPointMake(overlayViewFramesize / 2, overlayViewFramesize / 2)
overlayView.bringSubviewToFront(label)
window.addSubview(overlayView)
overlayView.layer.addAnimation(spring, forKey: nil)
RunAfterDelay(10.0) {
if self.hidden == true { return }
//strongSelf boilerplate code technique from https://www.raywenderlich.com/133102/swift-style-guide-april-2016-update?utm_source=raywenderlich.com+Weekly&utm_campaign=ea47726fdd-raywenderlich_com_Weekly4_26_2016&utm_medium=email&utm_term=0_83b6edc87f-ea47726fdd-415681129
UIView.animateWithDuration(2, delay: 0, options: [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.BeginFromCurrentState, UIViewAnimationOptions.TransitionCrossDissolve], animations: { [weak self] in
guard let strongSelf = self else { return }
(strongSelf.overlayView.viewWithTag(12) as! UILabel).text = randomPhrase()
(strongSelf.overlayView.viewWithTag(12) as! UILabel).sizeToFit()
print ((strongSelf.overlayView.viewWithTag(12) as! UILabel).bounds.width)
(strongSelf.overlayView.viewWithTag(12) as! UILabel).center = CGPointMake(overlayViewFramesize / 2, overlayViewFramesize / 2)
}, completion: { (finished: Bool)in
print ("animation to change label occured")})
}
}
}
func hideOverlayView() {
hidden = true
UIView.animateWithDuration(1.0, delay: 0.0, options: [UIViewAnimationOptions.BeginFromCurrentState], animations: { [unowned self] in
//I know this is clunky... what's the right way?
(self.overlayView.viewWithTag(12) as! UILabel).text = ""
self.overlayView.alpha = 0
}) { [unowned self] _ in
//I know this is clunky. what's the right way?
for view in self.overlayView.subviews {
view.removeFromSuperview()
}
self.overlayView.removeFromSuperview()
print("overlayView after removing:", self.overlayView.description)
}
//here i have to deinitialize stuff to prepare for the next use
}
deinit {
print("Loading Overlay deinit")
}
}
What I basically wanted, was to be able to delay a block of code, and possibly cancel it before it executes. I found the answer here:
GCD and Delayed Invoking

Resources