AwaitKit 4.0.0 with Swift 5 support

Related tags

Animation AwaitKit
Overview

AwaitKit

Carthage Compatible Supported Platforms Version Build Status codecov.io codebeat badge Awesome

Have you ever dream to write asynchronous code like its synchronous counterpart?

AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.

Internally it uses PromiseKit to create and manage promises.

RequirementsGetting StartedUsageInstallationContributionContactLicense

Requirements

  • iOS 8.0+
  • Xcode 8.0+
  • Swift 4.0+

Getting Started

If you want have a quick overview of the project take a look to this blog post.

Put simply, write this:

let user = try! await(signIn(username: "Foo", password: "Bar"))
try! await(sendWelcomeMailToUser(user))
try! await(redirectToThankYouScreen())

print("All done!")

Instead of:

signIn(username: "Foo", password: "Bar")
  .then { user in
    return self.sendWelcomeMailToUser(user)
  }
  .then { _ in
    return self.redirectToThankYouScreen()
  }
  .then { _ in
    print("All done!")
  }

Or worse, using the completion block imbrication hell style:

signIn(username: "Foo", password: "Bar") { user in
  self.sendWelcomeMailToUser(user) { _ in
    self.redirectToThankYouScreen() { _ in
      print("All done!")
    }
  }
}

Usage

Async

The async method yields the execution to its closure which will run in a background queue and returns a promise which will be resolved at this end of block.

Here a small example :

func setupNewUser(name: String) -> Promise<User> {  
  return async {
    let newUser = try await(self.createUser(name))
    let friends = try await(self.getFacebookFriends(name))

    newUser.addFriends(friends)

    return newUser
  }
}

Here the setupNewUser returns a promise with a user as value. If the end of async block is executed the promise will be resolved, otherwise if an error occurred inside the async block the promise will be rejected with the corresponding error.

The async block will catch the error thrown to reject the promise so you don't need to manage the await exceptions. But if necessary, you can:

async {
  do {
    try await(self.loginOrThrown(username: "yannickl"))
  }
  catch {
    print(error)
  }

  try await(self.clearCache())
}

Await

The await method will executes the given promise or block and await until it resolved or failed.

do {
  let name: String = try await {
    Thread.sleep(forTimeInterval: 0.2)

    if Int(arc4random_uniform(2) + 1) % 2 == 0 {
      return "yannickl"
    }
    else {
      throw NSError()
    }
  }

  print(name)
}
catch {
  print(error)
}

Custom queues

The async and await methods runs by default on a background concurrent queue. Of course, you can choose your own queues and call the following methods:

DispatchQueue.global(qos: .default).ak.async {

}

try DispatchQueue.global(qos: .default).ak.await {

}

When you use these methods and you are doing asynchronous, be careful to do nothing in the main thread, otherwise you risk to enter in a deadlock situation.

Installation

The recommended approach to use AwaitKit in your project is using the CocoaPods package manager, as it provides flexible dependency management and dead simple installation.

CocoaPods

Install CocoaPods if not already available:

$ [sudo] gem install cocoapods
$ pod setup

Go to the directory of your Xcode project, and Create and Edit your Podfile and add AwaitKit:

$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
pod 'AwaitKit', '~> 4.0.0'

Install into your project:

$ pod install

If CocoaPods did not find the PromiseKit 4.5.1 dependency execute this command:

$ pod repo update

Open your project in Xcode from the .xcworkspace file (not the usual project file)

$ open MyProject.xcworkspace

Swift Package Manager

You can use The Swift Package Manager to install AwaitKit by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .Package(url: "https://github.com/yannickl/AwaitKit.git")
    ]
)

Note that the Swift Package Manager is still in early design and development, for more information checkout its GitHub Page.

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate AwaitKit into your Xcode project using Carthage, specify it in your Cartfile:

github "yannickl/AwaitKit" ~> 4.0

Run carthage update to build the framework and drag the built AwaitKit.framework into your Xcode project.

Manually

Download the project and copy the AwaitKit folder into your project to use it in. Note that you also need to download the PromiseKit library and import it to your project.

Contribution

Contributions are welcomed and encouraged .

Contact

Yannick Loriot

License (MIT)

Copyright (c) 2016-present - Yannick Loriot

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You might also like...
Swift library for choreographing animations on the screen.
Swift library for choreographing animations on the screen.

Spruce iOS Animation Library (and Android) What is it? Spruce is a lightweight animation library that helps choreograph the animations on the screen.

A fantastic Physical animation library for swift
A fantastic Physical animation library for swift

A fantastic Physical animation library for swift(Not Just Spring !!!), it is base on UIDynamic and extension to it, friendly APIs make you use it or c

 A slider widget with a popup bubble displaying the precise value selected written on Swift.
A slider widget with a popup bubble displaying the precise value selected written on Swift.

A slider widget with a popup bubble displaying the precise value selected written on Swift. We specialize in the designing and coding of

Navigation toolbar is a Swift slide-modeled UI navigation controller.
Navigation toolbar is a Swift slide-modeled UI navigation controller.

Navigation toolbar is a Swift slide-modeled UI navigation controller. We specialize in the designing and coding of custom UI for Mo

Animate easy and with less code with Swift
Animate easy and with less code with Swift

JDAnimationKit is designed to be extremely easy to use. You can animate your UI withe less lines of code. This library use internally POP framework, a

A simple animated progress bar in Swift
A simple animated progress bar in Swift

DSGradientProgressView Introduction DSGradientProgressView is a simple and customizable animated progress bar written in Swift. Inspired by GradientPr

Composable animations in Swift

Composable animations in Swift. Blog Installation Cocoapods The easiest way to get started is to use CocoaPods. Just add the following line to your Po

Gravity is a simple Swift Package Manager to add gravity to UI objects easily.
Gravity is a simple Swift Package Manager to add gravity to UI objects easily.

Gravity -- Gravity is a simple Swift Package to add gravity to UI objects easily. -- How to use: Add a new Swift Package from XCode and paste the url

Swift animation made easy
Swift animation made easy

Fluent Swift Animations made Easy Installation Add the following to your Podfile and run pod install pod 'Fluent', '~ 0.1' or add the following

Owner
null
A library for building an internal/development support app easily

Scenarios A library supporting fast prototyping for iOS Projects. Introduction Challenges of mobile frontend development Stories with multiple require

An Tran 29 Sep 15, 2022
☄️Comets: Animating Particles in Swift

Comets ☄️ Comets: Animating Particles in Swift animation made by kevin as part of Voicy design implements Bennet van der Linden medium Comets: Animati

Cruz 593 Dec 28, 2022
A DSL to make animation easy on iOS with Swift.

This project is highly inspired by JHChainableAnimations, If you project is developed with Objective-C, use JHChainableAnimations instead. With DKChai

Draven 1.9k Dec 9, 2022
A Swift library to take the power of UIView.animateWithDuration(_:, animations:...) to a whole new level - layers, springs, chain-able animations and mixing view and layer animations together!

ver 2.0 NB! Breaking changes in 2.0 - due to a lot of requests EasyAnimation does NOT automatically install itself when imported. You need to enable i

Marin Todorov 3k Dec 27, 2022
Elegant SVG animation kit for swift

Elephant This is SVG animation presentation kit for iOS. Example You can run example app. Please open Example-iOS/Elephant-iOS.xcworkspace! Usage You

Kazumasa Shimomura 127 Dec 14, 2022
Gemini is rich scroll based animation framework for iOS, written in Swift.

Overview What is the Gemini? Gemini is rich scroll based animation framework for iOS, written in Swift. You can easily use GeminiCollectionView, which

Shohei Yokoyama 3k Dec 27, 2022
Swift interpolation for gesture-driven animations

Interpolate Interpolate is a powerful Swift interpolation framework for creating interactive gesture-driven animations. Usage The ?? idea of Interpola

Roy Marmelstein 1.8k Dec 20, 2022
Pulse animation for iOS written with Swift.

Pulsator Pulse animation for iOS written with Swift. Great For: Pulses of Bluetooth, BLE, beacons (iBeacon), etc. Map Annotations Installation CocoaPo

Shuichi Tsutsumi 1.3k Jan 6, 2023
A library to simplify iOS animations in Swift.

Updated for Swift 4.2 Requires Xcode 10 and Swift 4.2. Installation Drop in the Spring folder to your Xcode project (make sure to enable "Copy items i

Meng To 14k Jan 3, 2023
Better Easing for SpriteKit in Swift

This easing library began life as a port of buddingmonkey's Objective C SpriteKit Easing library to Swift. This library extends upon the basic easing

Craig Grummitt 110 Dec 17, 2022