The Startup
Published in

The Startup

Using Lottie Animations in iOS

If you are reading this, it means you are ready to add that magic touch to your iOS apps, that sprinkled salt to the top of your masterpiece, that one thing that will make your users cry of joy when they see it, because it’s just, beautiful.

And how to do it, you wonder? Well there are many ways, of course, but the one that we’ll talk about here today is Lottie.

What will we be doing here?

By the end of this article, you will understand and be able to build your own app with custom Lottie animations. And here’s what we are building:

What is Lottie?

It’s an iOS library by Airbnb that transforms JSON files into beautiful easy-to-use animations. And you can find a whole bunch of free awesome animations in here.

Ok, I’m ready!! How do I start?

Awesome, let’s start by opening Xcode and Creating a new iOS project.

  1. Open Xcode, select "Create new Xcode project"
  2. Select iOS, then "Single View App"

3. Add 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 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 folder. Type and run the following:

pod init

Notice that a file called Podfile will be created in the root folder of your project. Open it using any text editor (Xcode also works 🙂). Change it’s content with the following code:

# 1. Uncomment the next line to define a global platform for your project
platform :ios, '13.0'
# 2. Target to add frameworks totarget '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 folder, then type and run:

pod install

As soon as it’s 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.

Great, now to the fun part! Let’s animate!!!

We’ll be using this animation to start with. Once downloaded, drag and drop to the project, making sure our project is selected as target and copy items if needed is selected.

Adding a Lottie animation view by code

In the ViewController.swift file, replace 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. Set animation content mode animationView!.contentMode = .scaleAspectFit // 4. Set animation loop mode animationView!.loopMode = .loop // 5. Adjust 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 should see:

At this point, I encourage you to play around with different configurations :)

Adding a Lottie animation view using Interface Builder

In your Storyboard or Xib file, drag and drop a UIView to your ViewController, add 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, yet in the top right corner, navigate to Attribute Inspector and add the name of the animation file (without the extension).

In your Keyboard, press CTRL+OPTION+CMD+ENTER to open ViewController class and OPTION+Drag view to top of the ViewController Enclosure.

Once linked, close the right side Editor and navigate to ViewController.swift. Replace the function viewDidLoad with the following:

override func viewDidLoad() {  super.viewDidLoad()
// 1. Set animation content mode animationView.contentMode = .scaleAspectFit // 2. Set animation loop mode animationView.loopMode = .loop // 3. Adjust animation speed animationView.animationSpeed = 0.5 // 4. Play animation animationView.play()}

And test it out by pressing CMD+R :) The results should be similar to the ones above, considering how you placed the view.

Using Progress animations

Great, so now you know how to use Lottie animations, but then your application requires an extra touch of magic, and this requires you to be able to control what to play in animations, such as progress bars or animations that have different states. For this example, we’ll be building a download progress animation with this file. Same as before, download the file and drag and drop to the project.

When opening the file in LottieFiles, you’ll be able to slide through the animation progress.

If you are careful enough, you’ll be 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 3 key 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 state

Having those values, we will create an enum to make it 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()

// make sure the name of the animation matches the imported file
progressView = .init(name: "download") progressView!.frame = view.bounds progressView!.contentMode = .scaleAspectFit view.addSubview(progressView!)}

And we add 3 more functions, to start the download, to progress to completion and finally to complete the download.

// start the downloadprivate func startProgress() {  // play from frame 0 to the start download of progress  progressView?.play(fromFrame: 0, toFrame: ProgressKeyFrames.start.rawValue, loopMode: .none) { [weak self] (_) in    self?.startDownload()  }}// progress from 0 to 100%private func startDownload() {  // play animation from start to end of download progress  progressView?.play(fromFrame: ProgressKeyFrames.start.rawValue, toFrame: ProgressKeyFrames.end.rawValue, loopMode: .none) { [weak self] (_) in    self?.endDownload()  }}// download is completed, we show the completion stateprivate func endDownload() {  // download is completed, we show the completion state  progressView?.play(fromFrame: ProgressKeyFrames.end.rawValue, toFrame: ProgressKeyFrames.complete.rawValue, loopMode: .none)}

And finally, to test it out, add the following after the end of the method viewDidLoad.

override func viewDidAppear(_ animated: Bool) {  super.viewDidAppear(animated)  startProgress()}

That’s it, you may now run the application and here’s what you should see:

Awesome! We have the full animation! However, you might be interested in knowing how it would look like when downloading a file. Here’s how:

First, we’ll replace startDownload function with the following:

// start downloadprivate func startDownload() {  // 1. URL to download from  let url = URL(string: "https://archive.org/download/SampleVideo1280x7205mb/SampleVideo_1280x720_5mb.mp4")!  // 2. Setup download task and start download  let configuration = URLSessionConfiguration.default  let operationQueue = OperationQueue()  let session = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)  let downloadTask = session.downloadTask(with: url)  downloadTask.resume()}

Then, to handle the download task events, add this code to the bottom of your ViewController.swift file.

// MARK: - Download Delegateextension 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.main.async { self.progress(to: percentDownloaded) } }
// finishes download
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { DispatchQueue.main.async { self.endDownload() } }}

Finally, to show the animation in the right progress, we add the following code after startDownload function:

// sets download progressprivate func progress(to progress: CGFloat) {  // 1. We get the range of frames specific for the progress from 0-100%  let progressRange = ProgressKeyFrames.end.rawValue - ProgressKeyFrames.start.rawValue  // 2. Then, we get the exact frame for the current progress  let progressFrame = progressRange * progress  // 3. Then we add the start frame to the progress frame
// Considering the example that we start in 140, and we moved 30 frames in the progress, we should show frame 170 (140+30)
let 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 see the same effect as before, but this time, showing the progress of a real download. Pretty neat, huh?

This concludes our tutorial. By now, you should be able to play with animations and control their progress. Can you imagine the possibilities? 😀 So don’t waste any more time! Let the magic flow in your applications!

The complete code for this tutorial can be found here.

Happy coding! 😎

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store