Swift Wait for Current Animation to Finish Before Doing Animation Again
If you're reading this, information technology means you're set to add that bit of extra magic to your iOS apps. It's time to sprinkle on those little bits that volition give your app the edge and make your users cry with joy when they see it because it's just so darn beautiful.
It's time to sprinkle on some Lottie animations to your iOS apps.
And how can you practise this I hear you ask? Well there are many ways of class, but the one that we're going to look at hither is Lottie.
What nosotros'll cover in this article
Past the end of this article, you will empathise and be able to build your ain iOS app with custom Lottie animations. And here's what we are building together:
What is Lottie?
A Lottie is a JSON-based animation file format that enables designers to ship animations on any platform as easily as aircraft static assets. You tin can read more about it here.
Ok, I'm gear up! How exercise I start?
Awesome, let's beginning past opening Xcode and creating a new iOS project.
- Open Xcode, select "Create new Xcode projection"
- Select iOS, then "Single View App"
- Add together the name of the project, organization and identifier. Select Swift and Storyboard. Tap Next and Create.
Awesome, we have the project ready, now let's add together the Lottie library. There are a few ways to add Lottie to our project, in this tutorial, we'll be using the most popular one, CocoaPods.
To start, close the project, open terminal and navigate to your project's root binder. Type and run the post-obit:
pod init
Notice that a file called Podfile will be created in the root folder of your project. Open information technology using whatever text editor (Xcode also works). Change its content with the following code:
# ane. Uncomment the next line to define a global platform for your project platform :ios, '13.0' # 2. Target to add frameworks to target 'LottieTutorial' do # 3. Frameworks to be imported pod 'lottie-ios' end
Save, and open the terminal in your Mac and navigate to the project root binder, so type and run:
pod install
As shortly every bit it'south finished, double tap to open the xcworkspace file:
Navigate to ViewController.swift, add the following line to the top of the file.
import Lottie
CMD+B and make sure everything is ok.
Cracking, now for the fun function! Let's get animated!!!
You can choose from 1000s of costless blitheness on LottieFiles but for the purpose of this tutorial we'll be doing together, we'll be using this animation to start with.
As sometimes not all Lottie features are supported by iOS, it'southward super important to test that your chosen Lottie works on iOS. To do this, make sure y'all download the LottieFiles app for iOS and scan the QR lawmaking that is generated at the bottom under whatsoever animation that is either uploaded to or tested on LottieFiles. Once you're confident your blitheness looks and plays how it should, download the Lottie file.
Once downloaded, drag and driblet to the project, making certain our project is selected every bit target and copy items if needed is selected.
Adding a Lottie animation view by code
In the ViewController.swift file, supercede the method viewDidLoad with the following:
// 1. Create the AnimationView private var animationView: AnimationView? override func viewDidLoad() { super.viewDidLoad() // 2. Start AnimationView with animation name (without extension) animationView = .init(name: "coffee") animationView!.frame = view.bounds // 3. Fix animation content way animationView!.contentMode = .scaleAspectFit // 4. Gear up animation loop mode animationView!.loopMode = .loop // 5. Adapt animation speed animationView!.animationSpeed = 0.5 view.addSubview(animationView!) // 6. Play animation animationView!.play() }
You did it! Press CMD+R and here's what you lot should see:
At this point, I really encourage you to play around with dissimilar configurations.
Adding a Lottie blitheness view using Interface Builder
In your Storyboard or Xib file, elevate and drop a UIView to your ViewController, add together the desired constraints and position as you like. Then on the top right corner, navigate to Identity Inspector, change class to AnimationView and set module to Lottie.
Then in the top right corner, navigate to Attribute Inspector and add the proper noun of the animation file (without the extension).
In your Keyboard, press CTRL+Pick+CMD+ENTER to open up ViewController grade and Selection+Drag view to tiptop of the ViewController Enclosure.
In one case linked, close the right side Editor and navigate to ViewController.swift. Supplant the function viewDidLoad with the post-obit:
override func viewDidLoad() { super.viewDidLoad() // one. Set animation content fashion animationView.contentMode = .scaleAspectFit // 2. Set animation loop mode animationView.loopMode = .loop // 3. Suit animation speed animationView.animationSpeed = 0.5 // 4. Play animation animationView.play() }
And exam information technology out by pressing CMD+R. The results should be similar to the ones above, considering how you placed the view.
Using Progress animations
Nifty, and so now yous know how to use Lottie animations, but next your application needs a touch of actress magic, to enable you to control how your animation plays, such every bit having progress bars or animations that have unlike states. For this example, we'll exist building a download progress animation with this file. Same as earlier, download the file and drag and driblet to the project.
When opening the file in LottieFiles, yous'll be able to slide through the animation progress.
If you lot are careful plenty, you'll exist able to locate the exact frame of each part of the animation (located in the left bottom corner). In the example above, we've located three central frames:
- start of progress: 140
- end of progress: 187
- download complete: 240
What about the remaining frames?
- 0->140: start of animation
- 240->320: reseting to original country
Having those values, we will create an enum to go far easier for us to use:
enum ProgressKeyFrames: CGFloat { case start = 140 case end = 187 case complete = 240 }
And now, setup the AnimationView in viewDidLoad:
private var progressView: AnimationView? override func viewDidLoad() { super.viewDidLoad() // brand sure the proper name of the animation matches the imported file progressView = .init(proper noun: "download") progressView!.frame = view.premises progressView!.contentMode = .scaleAspectFit view.addSubview(progressView!) }
And nosotros add 3 more functions, to start the download, to progress to completion and finally to complete the download.
// starting time the download private func startProgress() { // play from frame 0 to the showtime download of progress progressView?.play(fromFrame: 0, toFrame: ProgressKeyFrames.get-go.rawValue, loopMode: .none) { [weak self] (_) in self?.startDownload() } } // progress from 0 to 100% private func startDownload() { // play animation from first to end of download progress progressView?.play(fromFrame: ProgressKeyFrames.first.rawValue, toFrame: ProgressKeyFrames.end.rawValue, loopMode: .none) { [weak cocky] (_) in self?.endDownload() } } // download is completed, we show the completion land private func endDownload() { // download is completed, we show the completion state progressView?.play(fromFrame: ProgressKeyFrames.cease.rawValue, toFrame: ProgressKeyFrames.complete.rawValue, loopMode: .none) }
And finally, to test it out, add the post-obit subsequently the end of the method viewDidLoad.
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) startProgress() }
That'due south information technology, y'all may now run the application and here's what you should see:
Awesome! We have the total blitheness! However, you lot might exist interested in knowing how looks like when downloading a file. Here'south how:
First, we'll supplant startDownload part with the post-obit:
// showtime download private func startDownload() { // one. URL to download from let url = URL(cord: "https://archive.org/download/SampleVideo1280x7205mb/SampleVideo_1280x720_5mb.mp4")! // 2. Setup download task and start download let configuration = URLSessionConfiguration.default permit operationQueue = OperationQueue() permit session = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue) let downloadTask = session.downloadTask(with: url) downloadTask.resume() }
Then, to handle the download task events, add together this code to the lesser of your ViewController.swift file.
// Marking: - Download Delegate extension ViewController: URLSessionDownloadDelegate { // handles download progress func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let percentDownloaded: CGFloat = CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) DispatchQueue.primary.async { self.progress(to: percentDownloaded) } } // finishes download func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { DispatchQueue.chief.async { self.endDownload() } } }
Finally, to show the blitheness in the right progress, we add together the following code later on startDownload function:
// sets download progress private func progress(to progress: CGFloat) { // i. We become the range of frames specific for the progress from 0-100% allow progressRange = ProgressKeyFrames.stop.rawValue - ProgressKeyFrames.offset.rawValue // 2. Then, we become the exact frame for the current progress permit progressFrame = progressRange * progress // three. And so we add the get-go frame to the progress frame // Because the case that nosotros start in 140, and we moved 30 frames in the progress, we should show frame 170 (140+30) allow currentFrame = progressFrame + ProgressKeyFrames.start.rawValue // 4. Manually setting the current animation frame progressView?.currentFrame = currentFrame print("Downloading \((progress*100).rounded())%") }
Press CMD+R again to run the code and you should run into the same upshot equally before, only this time, showing the progress of a real download. Pretty groovy ey?
This concludes our tutorial. Past at present, yous should be able to play with animations and command their progress. Imagine the possibilities that prevarication ahead of you lot. So don't waste any more time, let the magic flow in your iOS applications!
The consummate code for this tutorial tin can be found here.
Happy coding!
Learn more than most what else you can do with Lottie on our Working with Lottie weblog section.
dementwhintaked45.blogspot.com
Source: https://lottiefiles.com/blog/working-with-lottie/how-to-add-lottie-animation-ios-app-swift
0 Response to "Swift Wait for Current Animation to Finish Before Doing Animation Again"
Postar um comentário