Swift Other
Clone or download
danthorpe Fixes minor issues with new logging system (#870)
* Removes old logger tests

* Fixes issue where global log level was ignored

* Fixes issues with logs
Latest commit 0d9e3d7 Jul 16, 2018
Permalink
Failed to load latest commit information.
.ci Moves TryProcedureKit integration tests into main repo (#867) Jul 15, 2018
.github 4.0.0-beta-1 (#469) Sep 16, 2016
Documentation Result Injection improvements (#833) May 3, 2018
Integrations/CocoaPods Moves TryProcedureKit integration tests into main repo (#867) Jul 15, 2018
Presentations 4.0.0 Beta 4 (#560) Oct 30, 2016
ProcedureKit.xcodeproj Fixes minor issues with new logging system (#870) Jul 16, 2018
Sources Fixes minor issues with new logging system (#870) Jul 16, 2018
Supporting Files Refactors Procedure to only finish with one optional error (#851) Jun 28, 2018
Tests Fixes minor issues with new logging system (#870) Jul 16, 2018
.gitignore Moves TryProcedureKit integration tests into main repo (#867) Jul 15, 2018
.jazzy.json 4.3.0 (#780) Aug 3, 2017
.ruby-gemset Update for Xcode 9.2 and Swift 4.0 (#816) Jan 29, 2018
.ruby-version Update for Xcode 9.2 and Swift 4.0 (#816) Jan 29, 2018
.swift-version Swift 4.1 improvements (#837) May 8, 2018
.swiftlint.yml 4.1.0 (#702) Apr 9, 2017
.travis.yml Rewrites CI pipeline (#850) Jun 7, 2018
CHANGELOG.md [4.5.0]: Fixes incorrect PR reference Feb 13, 2018
CODE_OF_CONDUCT.md 4.3.0 (#780) Aug 3, 2017
Gemfile Rewrites CI pipeline (#850) Jun 7, 2018
Gemfile.lock Rewrites CI pipeline (#850) Jun 7, 2018
LICENSE Swift 4.1 improvements (#837) May 8, 2018
Package.swift [OPR-826]: Updates Package.swift (#826) Mar 8, 2018
ProcedureKit.podspec Sets the version to 5.0.0 🚀 (#859) Jul 2, 2018
README.md Sets the version to 5.0.0 🚀 (#859) Jul 2, 2018
TestingProcedureKit.podspec Sets the version to 5.0.0 🚀 (#859) Jul 2, 2018
header.png 4.0.0-beta-1 (#469) Sep 16, 2016
header@2x.png 4.0.0-beta-1 (#469) Sep 16, 2016

README.md

Build status Coverage Status Documentation CocoaPods Compatible Platform Carthage compatible

ProcedureKit

A Swift framework inspired by WWDC 2015 Advanced NSOperations session. Previously known as Operations, developed by @danthorpe with a lot of help from our fantastic community.

Resource Where to find it
Session video developer.apple.com
Old but more complete reference documentation docs.danthorpe.me/operations
Updated but not yet complete reference docs procedure.kit.run/development
Programming guide operations.readme.io
Example projects danthorpe/Examples

Version 5 🚀

The development branch, or the bleeding edge is the current state of ProcedureKit v5 work. Handle with care - but migration issues are welcome! The focus for v5 is:

  • Swift 4.2 & Xcode 10 support (on xcode/10.0/development branch)
  • Documentation, guides & sample code (currently published to http://procedure.kit.run/development/)
  • Errors & easier error handling (breaking changes on development branch)
  • Improved debugging & logging
  • Simplified BlockProcedure API
  • Simplified ProcedureKitNetwork classes (this was done a while ago, the generic session has been removed)

Compatibility

ProcedureKit supports all current Apple platforms. The minimum requirements are:

  • iOS 9.0+
  • macOS 10.11+
  • watchOS 3.0+
  • tvOS 9.2+

The current released version of ProcedureKit (4.5.0) supports Swift 4.0+, and the use of Xcode 9 is strongly recommended.

(If you need Swift 2.3 support, see version 3.4.1 or the swift/2.3 branch.)

Framework structure

ProcedureKit is a "multi-module" framework (don't bother Googling that, I just made it up). What I mean, is that the Xcode project has multiple targets/products each of which produces a Swift module. Some of these modules are cross-platform, others are dedicated, e.g. ProcedureKitNetwork vs ProcedureKitMobile.

Installing ProcedureKit

See the Installing ProcedureKit guide.

Usage

Procedure is a Foundation.Operation subclass. It is an abstract class which must be subclassed.

import ProcedureKit

class MyFirstProcedure: Procedure {
    override func execute() {
        print("Hello World")
        finish()
    }
}

let queue = ProcedureQueue()
let myProcedure = MyFirstProcedure()
queue.add(procedure: myProcedure)

the key points here are:

  1. Subclass Procedure
  2. Override execute but do not call super.execute()
  3. Always call finish() after the work is done, or if the procedure is cancelled. This could be done asynchronously.
  4. Add procedures to instances of ProcedureQueue.

Observers

Observers are attached to a Procedure subclass. They receive callbacks when lifecycle events occur. The lifecycle events are: did attach, will execute, did execute, did cancel, will add new operation, did add new operation, will finish and did finish.

These methods are defined by a protocol, so custom classes can be written to conform to multiple events. However, block based methods exist to add observers more naturally. For example, to observe when a procedure finishes:

myProcedure.addDidFinishBlockObserver { procedure, errors in 
    procedure.log.info(message: "Yay! Finished!")
}

The framework also provides BackgroundObserver, TimeoutObserver and NetworkObserver.

See the wiki on [[Observers|Observers]] for more information.

Conditions

Conditions are attached to a Procedure subclass. Before a procedure is ready to execute it will asynchronously evaluate all of its conditions. If any condition fails, it finishes with an error instead of executing. For example:

myProcedure.add(condition: BlockCondition { 
    // procedure will execute if true
    // procedure will be ignored if false
    // procedure will fail if error is thrown
    return trueOrFalse // or throw AnError()
}

Conditions can be mutually exclusive. This is akin to a lock being held preventing other operations with the same exclusion being executed.

The framework provides the following conditions: AuthorizedFor, BlockCondition, MutuallyExclusive, NegatedCondition, NoFailedDependenciesCondition, SilentCondition and UserConfirmationCondition (in ProcedureKitMobile).

See the wiki on [[Conditions|Conditions]], or the old programming guide on Conditions| for more information.

Capabilities

A capability represents the application’s ability to access device or user account abilities, or potentially any kind of gated resource. For example, location services, cloud kit containers, calendars etc or a webservice. The CapabiltiyProtocol provides a unified model to:

  1. Check the current authorization status, using GetAuthorizationStatusProcedure,
  2. Explicitly request access, using AuthorizeCapabilityProcedure
  3. Both of the above as a condition called AuthorizedFor.

For example:

import ProcedureKit
import ProcedureKitLocation

class DoSomethingWithLocation: Procedure {
    override init() {
        super.init()
        name = "Location Operation"
        add(condition: AuthorizedFor(Capability.Location(.whenInUse)))
    }
   
    override func execute() {
        // do something with Location Services here
        
        
        finish()
    }
}

ProcedureKit provides the following capabilities: Capability.CloudKit and Capability.Location.

In Operations, (a previous version of this framework), more functionality existed (calendar, health, photos, address book, etc), and we are still considering how to offer these in ProcedureKit.

See the wiki on [[Capabilities|Capabilities]], or the old programming guide on Capabilities for more information.

Logging

Procedure has its own internal logging functionality exposed via a log property:

class LogExample: Procedure {
   
    override func execute() {
        log.info("Hello World!")
        finish()
    }
}

See the programming guide for more information on logging and supporting 3rd party log frameworks.

Dependency Injection

Often, procedures will need dependencies in order to execute. As is typical with asynchronous/event based applications, these dependencies might not be known at creation time. Instead they must be injected after the procedure is initialised, but before it is executed. ProcedureKit supports this via a set of protocols and types which work together. We think this pattern is great, as it encourages the composition of small single purpose procedures. These can be easier to test and potentially enable greater re-use. You will find dependency injection used and encouraged throughout this framework.

Anyway, firstly, a value may be ready or pending. For example, when a procedure is initialised, it might not have all its dependencies, so they are in a pending state. Hopefully they become ready by the time it executes.

Secondly, if a procedure is acquiring the dependency required by another procedure, it may succeed, or it may fail with an error. Therefore there is a simple Result type which supports this.

Thirdly, there are protocols to define the input and output properties.

InputProcedure associates an Input type. A Procedure subclass can conform to this to allow dependency injection. Note, that only one input property is supported, therefore, create intermediate struct types to contain multiple dependencies. Of course, the input property is a pending value type.

OutputProcedure exposes the Output associated type via its output property, which is a pending result type.

Bringing it all together is a set of APIs on InputProcedure which allows chaining dependencies together. Like this:

import ProcedureKitLocation

// This class is part of the framework, it 
// conforms to OutputProcedure
let getLocation = UserLocationProcedure()

// Lets assume we've written this, it
// conforms to InputProcedure
let processLocation = ProcessUserLocation()

// This line sets up dependency & injection
// it automatically handles errors and cancellation
processLocation.injectResult(from: getLocation)

// Still need to add both procedures to the queue
queue.add(procedures: getLocation, processLocation)

In the above, it is assumed that the Input type matched the Output type, in this case, CLLocation. However, it is also possible to use a closure to massage the output type to the required input type, for example:

import ProcedureKitLocation

// This class is part of the framework, it 
// conforms to OutputProcedure
let getLocation = UserLocationProcedure()

// Lets assume we've written this, it
// conforms to InputProcedure, and 
// requires a CLLocationSpeed value
let processSpeed = ProcessUserSpeed()

// This line sets up dependency & injection
// it automatically handles errors and cancellation
// and the closure extracts the speed value
processLocation.injectResult(from: getLocation) { $0.speed }

// Still need to add both procedures to the queue
queue.add(procedures: getLocation, processLocation)

Okay, so what just happened? Well, the injectResult API has a variant which accepts a trailing closure. The closure receives the output value, and must return the input value (or throw an error). So, { $0.speed } will return the speed property from the user's CLLocation instance.

Key thing to note here is that this closure runs synchronously. So, it's best to not put anything onerous onto it. If you need to do more complex data mappings, check out TransformProcedure and AsyncTransformProcedure.

See the programming guide on Injecting Results for more information.