One building block for navigating from one view to another is NavigationView which is a representation of UINavigationController in UIKit. This time, let's take a look on how to transition from one SwiftUI view to another one without NavigationView. AppFlowCoordinator managing choosing the view The idea is to have a root SwiftUI view with only …
Injecting dependencies using environment values and keys in SwiftUI
Instead of initializing SwiftUI views with dependencies, SwiftUI also offers other ways for injecting dependencies. This time let's take a look on EnvironmentKey which defines a key for inserting objects to environment and vise-versa. We need to create a EnvironmentKey, adding an object to environment and then getting the object in SwiftUI view. Creating EnvironmentKey …
Continue reading "Injecting dependencies using environment values and keys in SwiftUI"
Adding custom attribute to NSAttributedString on iOS
NSAttributedString is used for displaying rich text on Apple platforms. There are many attributes available for styling the text. Let's see how to add new attribute and how to draw it in UITextView. Drawing custom attribute Defining a new attribute is just a matter of extending NSAttributedString.Key and defining a new static variable. Difficult part …
Continue reading "Adding custom attribute to NSAttributedString on iOS"
Persistent reusable container for item collections in Swift
Let's build a container where we can store collections of items conforming to a protocol. All the collections are identified by a case in enum. For making the container reusable, we'll use protocols as requirements on keys and items in collections. Moreover, the container should be archivable and unarchivable. Creating a reusable container Container's implementation …
Continue reading "Persistent reusable container for item collections in Swift"
Embedding a view in UIScrollView on iOS
This time we are going to look into how to embed custom view in UIScrollView and setting up autolayout constraints for different scenarios. Setting up view controller with scroll view We'll gonna create a new view controller what contains UIScrollView as it's subview. UIScrollView will cover the whole view area. Everything is set up in …
Replacing multiple text tokens in Swift
Let's see how to replace multiple tokens in string. As an example problem to solve we will use this string:The quick <color_1> <animal_1> jumps over the lazy <animal_2> String extension for replacing tokens Token's format is < text _ numbers > what can be turned into regular expression: <[:alpha:]+_{1}[:digit:]+>. We'll extend string and add a …
NavigationLink and presentationMode environment value property for dismissing a view in SwiftUI
How to navigate to a new view in SwiftUI and then dismissing it? Let's set up a main view in NavigationView and NavigationLink for opening detail view. NavigationLink is a button triggering a navigation to a specified view. Detail view will contain a button for navigating back to the first view. But how do we …
Loading URL previews using LinkPresentation framework in Swift
iOS and macOS got a new framework in WWDC'19 named LinkPresentation. LinkPresentation enables fetching URL previews. Adding LPLinkView for presenting preview LPLinkView is a view subclass meant for rendering LPLinkMetadata. LPLinkMetadata contains information about the link: title, icon, image, video. https://gist.github.com/laevandus/62c9d1d2987652cb0af149aaa4f38985 Adding LPLinkView to stack view Fetching previews with LPMetadataProvider Instances of LPLinkMetadata are fetched …
Continue reading "Loading URL previews using LinkPresentation framework in Swift"
Animating GIFs and APNGs with CGAnimateImageAtURLWithBlock in SwiftUI
This year Apple added CGAnimateImageAtURLWithBlock and CGAnimateImageDataWithBlock for animating GIFs and APNGs on all the platforms to the ImageIO framework. We can pass in URL or data and get callbacks when animation changes the current frame. In Xcode 11 beta 7 implicit bridging to Swift is disabled for those APIs and therefore we need to …
Continue reading "Animating GIFs and APNGs with CGAnimateImageAtURLWithBlock in SwiftUI"
Property wrapper for validating email using NSDataDetector
Property wrappers allow property declaration to state what kind of property wrapper is used for implementing the property. We can use it for implementing transformations on properties like validating if string is email or not. This is what we will do: creating a property wrapper for email properties and validating emails using NSDataDetector. If value …
Continue reading "Property wrapper for validating email using NSDataDetector"
Key-value observing without NSObject and dynamic modifier in Swift
When writing code in Swift it is often needed to observe changes in other objects. We can use Apple's key-value observation but it has some implications: requires to use NSObject and dynamic dispatch through Objective-C runtime. This time, let's build a simple key-value observation in Swift what does not require to use NSObject at all. …
Continue reading "Key-value observing without NSObject and dynamic modifier in Swift"
Displaying menus with UIContextMenuInteraction on iOS
iOS 13 added a new class named UIContextMenuInteraction what is used for attaching menus to views. When adding menu interaction to a view and user uses 3D Touch or long press gesture on devices not supporting it, a menu is presented alongside with the highlighted content view. Therefore depending on the available space, not all …
Continue reading "Displaying menus with UIContextMenuInteraction on iOS"
Scanning text using SwiftUI and Vision on iOS
Apple's Vision framework contains computer vision related functionality and with iOS 13 it can detect text on images as well. Moreover, Apple added a new framework VisionKit what makes it easy to integrate document scanning functionality. For demonstrating the usage of it, let's build a simple UI what can present the scanner and display scanned …
Continue reading "Scanning text using SwiftUI and Vision on iOS"
Creating chat view with Combine and SwiftUI
Let's build a conversation view which shows a list of messages and has input text field with send button. Sent and received messages are managed by Conversation object. Conversation object manages a Session object which is simulating networking stack. This kind of setup allows us to look into how to propagate received messages from Session …
Continue reading "Creating chat view with Combine and SwiftUI"
Hashing data using CryptoKit
So far we have been using CommonCrypto when it has come to creating hashes of data. I even wrote about it some time ago and presented a thin layer on top of it making it more convenient to use. In WWDC'19 Apple presented a new framework called CryptoKit. And of course, it contains functions for …
Testing networking code with custom URLProtocol on iOS
Testing networking code might sound tricky at first but in reality, it just means using custom URLProtocol what returns data we would like to. This allows testing the networking module without mocking URLSession. Using this approach we could do so much more, even integrating a third party networking library. Networking class wrapping URLSession Firstly, let's …
Continue reading "Testing networking code with custom URLProtocol on iOS"
Storing struct in UserDefaults
Structs can't be directly stored in UserDefaults because UserDefaults does not know how to serialize it. As UserDefaults is backed by plist files, struct needs to be converted representation supported by it. The core idea boils down to the question, how to convert struct into Dictionary. Converting struct to Dictionary The most straight-forward way would …
Interactive animation with UIViewPropertyAnimator on iOS
UIViewPropertyAnimator enables configuring animations which can be modified when running. Animations can be paused and progress can be changed allowing to build interactive animations. UIViewPropertyAnimations are in stopped state by default. If we want to run the animation immediately, we can use class method runningPropertyAnimator(withDuration:delay:options:animations:completion:). UIViewPropertyAnimator gives us a lot of flexibility when it comes …
Continue reading "Interactive animation with UIViewPropertyAnimator on iOS"
UICollectionViewFlowLayout and auto layout on iOS
UICollectionViewFlowLayout is layout object supplied by UIKit and enables showing items in grid. It allows customising spacings and supports fixed size cells and cells with different sizes. This time I am going to show how to build a collection view containing items with different sizes where sizes are defined by auto layout constraints. Cell sizes …
Continue reading "UICollectionViewFlowLayout and auto layout on iOS"
Instantiating view controllers from UIStoryboard on iOS
There are several ways how to create user interfaces on iOS: programmatically, xib per view or using storyboard for multiple views. Personally I tend to use xibs and programmatically created layouts more but sometimes I also use UIStoryboard - depends on the situation on hand. Therefore I like to present two small additions to UIStoryboard …
Continue reading "Instantiating view controllers from UIStoryboard on iOS"
Supporting dynamic type on iOS
Dynamic type is a feature on iOS what allows users to customise size of the text on screen. Supporting dynamic type enables users with low vision condition to still use your app. It defines a set of APIs for getting font sizes matching with users text size choice in the settings. There are two ways …
Uniform Type Identifiers on iOS
UTIs come up pretty quickly when working with files. Unfortunately APIs used for checking for conformance and creating UTIs is pretty old and does not fit well into Swift ecosystem. Uniform Type Identifiers Uniform type identifiers define abstract data types what can be used to describe the type of an entity. Entities include pasteboard data, …
Basic debugging in Xcode
Printing object description Probably the most used command when debugging apps is po. It evaluates the expression and prints out the object description. When printing custom objects, it should be noted that the format of the result can be customised by implementing debugDescription in CustomDebugStringConvertible protocol. Modifying code in runtime LLDB's expression command allows executing code when …
UITableView swipe actions on iOS
Since iOS 11 it is easy to add swipe actions in a table view. What we need to do, is to implement UITableView delegate methods for providing actions for leading and trailing edge. Let's jump right into it. Default swipe actions Swipe actions are provided by two delegate methods which return UISwipeActionsConfiguration. It should be …
Circle shaped collection view layout on iOS
UICollectionViewLayout's responsibility is to define layout: all the cell locations and sizes. It acts like a data source object which provides layout related information to the collection view. Collection view then uses that information for creating cells and placing them on screen. This time we'll take a look on how to create a custom circle …
Continue reading "Circle shaped collection view layout on iOS"
Particle emitters for apps with CAEmitterLayer on iOS
Particle emitters are encountered the most often in games. Apple's SpriteKit framework contains SKEmitterNode for this exact purpose. Moreover, Xcode even has a live editor for configuring SKEmitterNode. As SKEmitterNode can only be added to SKScene, it is not a good fit for apps. But no worries, apps can take advantage of CAEmitterLayer which is …
Continue reading "Particle emitters for apps with CAEmitterLayer on iOS"
Most visited posts in 2018
It is this time of the year when to look back. In total I published 22 blog posts and had 2765 views by 1632 people. Together with 3 posts from the 2017 I now have 25 blog posts. In the end of the July I posted Sharing UI code with protocol extension what marked the …
Displaying images efficiently on iOS
Loading an image and displaying it on a screen consists of several steps. Firstly, we need to load the image data into memory, then decoding it to pixel data and finally, telling GPU to display it on screen. The whole process can be as short as two lines of code: creating an instance of UIImage …
Observing keyboard visibility on iOS
Almost every app needs a way of inserting information using keyboard. When keyboard shows up, we do not want to keep content behind the keyboard hidden and instead, allow user to see it. UIResponder contains several notifications we can use to adjust the layout. Keyboard change notifications UIResponder contains a list of notifications and user …
Navigating using flow controllers and responder chain on iOS
Every app consists of different flows for achieving a specific goal. For example, there is a sequence of views for sign up. When sign up flow ends, we need to move to so called main view what represents the main functionality of the app. There are definitely a lot of different ways how to handle …
Continue reading "Navigating using flow controllers and responder chain on iOS"
Text input in UITableView
This time we are going to take a look on how to create a form with text input using UITableView. Displaying static text in UITableView is easy but for enabling text input in UITableView and propagating the change back to a model object requires a couple of steps. Introduction In this example project we are …
Creating persistent data store on iOS
Storing data persistently on iOS is something what is needed quite often. In this post, we are going to look into how to build a persistent data store and how to store image data. Initialising the persistent data store Persistent data store is an object managing a folder on disk. It allows writing and reading …
Random unification in Swift 4.2
In the beginning of this year I blogged about how to generate random float and integers. Meanwhile, SE-0202 "Random Unification" got implemented in Swift 4.2 making my additions unnecessary. Let's take a look how to use new API for getting random numbers. Random integers, floats and booleans In my own implementation I was extending range …
Deforming sprites with SKWarpGeometryGrid in SpriteKit
SKWarpGeometryGrid is a grid based deformation what can be applied to nodes conforming to SKWarpable protocol. It defines normalised vertex positions for source and destination where source positions are un-warped geometry and destination warped geometry. Therefore, if destination vertex positions are not equal to source, the node will look deformed. Vertex positions Here is a …
Continue reading "Deforming sprites with SKWarpGeometryGrid in SpriteKit"
Taking photos on iOS
This time we will take a look on how to take photos and browse them on iOS. Using UIImagePickerController Creating user interface for taking photos consists of presenting an instance of UIImagePickerController. Controller needs a delegate and source type what defines if we are going to take a photo or pick a photo from the …
Custom non-interactive transition in iOS
In iOS view transitions can be interactive and non-interactive. In this post we are going to take a look on how to implement a custom non-interactive transition. Setting up a custom transition For setting up a custom non-interactive transition it is needed to create an animator object defining the transition and feeding it into UIKit. …
Singly linked list with generics in Swift
In this post we will go over basic usage of generics in Swift by building a simple singly linked list. Introduction to generics Generic code is code where the functionality is described without using specific types. Meaning, the code can use any types what match with constraints (if there are any). It's best to take …
Continue reading "Singly linked list with generics in Swift"
Sharing UI code with protocol extension
In this blog post we are going to look into how to share UI code between view controllers using protocol extension. Problem setup Let's say we have two view controllers: one showing a list of items and another one showing items in a collection view. In iOS development it is common to use UITableViewController and …
Storing data with CoreData
CoreData is a framework for managing object graphs and storing them on disk. It is much more than just offering a persistent storage, therefore the rich API it provides, is meant to be used app-wide. In this blog post we'll look into how to initialise CoreData storage, store some data in it and fetching it. …
View coordination with responder chain
When building iOS apps it is important to think about how to structure an app and how to connect all the pieces. A typical app has multiple interaction flows and in this post I am going to represent a way of how to decouple views and how to navigate from one view to another using …
Using CCHmac for creating message authentication codes
This is a second part of the first post about hashing data using SHA256. Here we will look into CCHmac (Hash-based Message Authentication Code) functions and see how to use it for creating authentication codes what can be used for data integrity checks and authentication of a message. Message authentication codes Hash-based message authentication code …
Continue reading "Using CCHmac for creating message authentication codes"
Hashing data using CommonCrypto and SHA256
Looking for hashing data using CryptoKit? Please navigate to here. In this post we will look into how to add CommonCrypto to a Xcode project and how to generate hash using SHA256. Adding CommonCrypto as a module Note: Since Swift 4.2, this step is not necessary and manually added CommonCrypto module must be removed. CommonCrypto …
Continue reading "Hashing data using CommonCrypto and SHA256"
Making a property observable from outer scope using generic class Observable
We will look into how to make a property observable using a separate class managing the observers. It is an alternative and simple way of observing property changes without using ReactiveSwift, Key-Value Observing or anything else similar. It can be an excellent glue between Model and View Model in MVVM or between View and Presenter …
Continue reading "Making a property observable from outer scope using generic class Observable"
Getting started with ReactiveSwift
Aim of the tutorial is to get started with ReactiveSwift without any previous setup except having Xcode installed. We will go through how to install it using Carthage package manager, add it to an iOS project and then observing a change of a property. Installing Carthage First we need to have Carthage installed. If it …
Light Xcode Theme
I got tired of using dark themes and as there were no light themes I liked, I decided to create my own. I present a light Xcode theme to you: Augmented Code. Go ahead and give it a try!
RawRepresentable and associated values
RawRepresentable is a protocol in Swift standard library and enables converting from a custom type to raw value type and back. In this post we'll be looking into how to implement RawRepresentable for enumeration containing an associated value. Conforming to RawRepresentable Implementing RawRepresentable requires three steps: firstly, choose RawValue type; secondly, implement initialiser where RawValue …
Random float and integer in Swift
Getting a random number within a range is a very common operation. There are multiple ways of extending Swift language to add support for getting random values within a specified range. After experimenting with different implementations like utility functions, integer and float extensions I have found that the most natural way of doing it is …
Adding an animating glow to SKSpriteNode
Having a glow behind a sprite can give game a move lively environment. In this blog post I am going to present a way of adding a glow to SKSpriteNode using an instance of SKEffectNode. Node Tree First of all let's take a look on the node tree needed for achieving the end result. SKSpriteNode …
Clamping numbers in Swift
Clamping a value is an operation of moving the value to a range of allowed values. It can be achieved by comparing the value with allowed minimum and maximum values. For example I was deforming SKWarpGeometryGrid from the direction of a point outside the grid and needed to constrain angles between grid points and the …
Positioning a node at the edge of a screen
iOS devices have several screen sizes and aspect ratios. This is something to keep in mind when building a game in SpriteKit because placing a node at the edge of a screen is not straight forward. But first let's take a quick look on managing scenes. One way for it is to use scene editor …
Continue reading "Positioning a node at the edge of a screen"