Implementing features with ReactiveFeedback

Some time ago there was an explosion of articles and talks in the iOS community about "unidirectional flow" architectures, inspired by Redux library from JavaScript. The dust has settled since then but as a result of this storm, we now have ReSwift and other implementations of this approach. Reactive programming adepts didn't stay away for long and came up with RxFeedback. At Babylon, we use ReactiveCocoa so we've built ReactiveFeedback. In this article, you'll see how we use it to build the whole features in our app, not just increment counters so there will be a lot of »

iOS UI Automation Tests at Babylon

This article is based on the talk I gave at iOS Astronauts meetup that was held on 03.10.2018 at Babylon. You can check out this talk and other videos as well as join the meetup group here. Probably every iOS developer nowadays knows what UI tests are and how to write them. Sometimes we don't even have to write them ourselves because Xcode can do that for us. Of course, the result is far from ideal and probably you don't want to keep it as it is in your tests, but point is that it's not hard to »

Parameterized jobs in CircleCI

The title is a lie - there is no such thing as parameterized jobs (at the time of writing, but seems it’s going to be improved in 2.1) when we are talking about CircleCI 2.0 workflows, which are (almost) awesome by the way. But with some tricks, we can achieve something close to that. Here is the problem. Let's say we have a bunch of jobs which are exactly the same except what build or test command they invoke in the end. They all need to perform the same sequence of actions: checkout code install dependencies (different »

Codable in practice

One of the first tasks I got in my new team was to convert entire code base from in-house JSON encoding/decoding solution (in fact two of them) to Swift native Codable protocols. What may sound like an easy task, on practice means a lot of work taking into account inconsistencies in API. That lead to the situation when apart from really simple data structures holding just few properties of primitive types, everything required custom decoding or encoding. Here are few of the use cases that I encountered and their possible solutions. In the end I will talk a bit »

URL parser in functional style. Part 2.

In previous part we started to write base components of URL parser. Time to extend it and add some additional functionality, like conditional, optional and wildcard patterns. Conditional pattern This pattern should parse either one pattern or another. This kind of parameter type can be expressed with Either<A, B> type defined as a simple generic enum with two cases. enum Either<A, B> { case left(A), right(B) } Using this type we can compose parser and printer. Parser will try to parse left pattern first and return matched value wrapped in Either.left, otherwise it »

URL parser in functional style. Part 1.

When I published one of my previous posts about deeplinks and then decided to turn it into a framework it turned out that Brandon Williams was working on a similar thing for his Point-Free project, but related to parsing http requests for web framework. As parsing URLs is a subset of this problem I decided to go through his implementation and apply the same technique to rewrite parser that I have written in imperative way (and probably not in the best way) in a functional style. Just to see where it goes and as exercise in a functional programming. So »

Swift 4 tricky filters

This is a short story of a regression in Swift 4 that I've recently had to deal with. It can seem as a simple problem, but I think it's a good example of unexpected regression caused by a positive change in a language standard library. First - a bit of a context. In my current project we extensively use Eureka framework to build forms. Most of the time values in our forms are selected from a list of options. For this purpose Eureka has a special type of section - SelectableSectionType. There is also a base class Section that represents »

Deep links with no brainer

Very often in my practice deep links were something that no one cares much, they work somehow and its fine. Or there are just few of them and its really not hard to maintain. But working for a long time on one product that targets several very different markets reveals all the importance of deep links in a long run. There are always requests from marketing teams to support new kind of deep link for a new marketing campaign, to open some new screen in the app from push notification, or with some specific parameters, when existing deep link can't »

Swift enums with associated values defaults

In Swift enums are much more powerful than we got used to in other languages. One of the features that makes them more interesting to use is associated values - values that each instance of enum case can carry along with it. We can not have stored properties in the enum, so associated values is basically the only way to store additional data with enum value. Creating an enum value with associated value has a similar semantics as a method call. The difference is - we can not define defaults for parameters which represent associated values. Here is a real-life »

Xcode Source Editor Extension superpowered with SourceKitten

With Xcode 8 Apple finally provided developers with first party API to develop plugin-like Xcode extensions, at the same time closing all the doors for in-process plugins. At this moment unfortunately we are provided with a very limited tools. We can only manipulate the content of currently selected file, have no (official) access to any project metadata and other sources. There are also no first-party tools for code analysis, so we have to parse the code manually. Luckily thanks to OSS community we have such projects as SourceKitten that fills this gap and gives us some foundation to build cool »

Extending native code with JavaScriptCore

This week there were a lot of articles around the web about React Native and its place in a current iOS dev ecosystem. I was also playing with JavaScript lately, but in somewhat different context - JavaScriptCore. JavaScriptCore is a really great way to make your apps extensible by your users. There are some cool live examples of awesome tools leveraging it. As developers we are in a better position than our users as most of the time we can extend and patch our tools to our needs using native code. But our users can not. For example if you »

Going back to the roots

As Roy Marmelstein said in his recent presentation at dotSwift - "We love to be excited". Can not agree more. When we read a blog post that describes the concept or architectural pattern that is somewhat new for us and feels exciting we tend to accept it as something good. We can go really far away this rote and sometimes we don't notice that we already have all the tools to solve the problems they address. For iOS developers this tool is a framework that we inevitably use every day - UIKit. That's what I was thinking about »

Adaptive text styles

Textual content is the essential part of any app and text handling in iOS has been improving through last years. Starting with iOS 7 we have dynamic types and text styles, then in iOS 8 we got self sizing cells that help a lot when you want to adopt dynamic type. With trait collections we also expanded the ways how we can adapt text to different environments. And Apple was constantly extending those APIs exposing new font styles, font wights and so on. There is one "but" here. I don't have official statistics and will be glad to »

Inout variables with side effects

Every app has some kind of caching. Let's say our caching strategy is very simple: check if data is in the memory cache and return it if not - make a network call and cache the result when it's done For that you can write code that will probably look something like this: if let cached = store.menuPreferences { dispatch_async(dispatch_get_main_queue()) { completion(preferences: cached, error: nil) } } else { repository.getMenuPreferences({ (preferences, error) in if let preferences = preferences { } completion(preferences: preferences, error: error) }) } Pretty simple and straight forward. But what if you need to add »

Objective-C headers in Swift framework & custom build configurations

It's already 2 years of Swift and its interoperability with Objective-C as well. When app extensions were released we've got a way to share our code across targets using frameworks. I used to build lots of frameworks since then, sometimes I even worked full-time just on frameworks. But as I had written almost none of Objective-C in around a year now and I've never dived deep enough in Swift and Objective-C interoperability in frameworks here is the lesson I had to learn hard this time. Setup Lets say you've decided to make a framework that combines all UIKit related extensions »

Frameworks, Keychain, NSCoding and Swift

One of the strategies that we use at HelloFresh to reduce compile time, improve code reuse and overall codebase health is breaking our code into frameworks. We've started with two core layers - domain and network. We broke these layers into four different frameworks: domain, generic API client, implementation of API client based on Alamofire and endpoints containing collections of requests that we can make to our API. Simply breaking these layers into frameworks already gave us a lot - it was easier to concentrate on particular parts of the code, define seams between them, cover them with tests and »

Xcode & cross-platform frameworks

Recently I came across an article by Max Howell describing how he had setup PromiseKit project to use just a single target instead of a separate target for each platform. As I have a side-project framework I'm working on I was interested to try this setup. Here is what I've found out. In general there is nothing special in the setup and it works both in Xcode 7 and Xcode 8. First you need to specify that the framework target supports all the platforms, not forgetting about simulators. If you already have separate framework targets, like I had, you can »

Douglas-Peucker algorithm

This post is a part of the series about shapes recognition. This post is also available as a part of a playground. Curve preprocessing. When drawing by hand, especially in a slow manner, we will get a lot of touch points and the resulting curve will contain lots of close points. Also we can not draw ideally, so resulting curve can contain artifacts like hooklet at the end of the curve, closed shapes can not be ideally closed. These artifacts are insignificant for recognizing a shape and only complicate calculations. To eliminate deviation from "ideal" curve there are »

Freehand drawing

This post is a part of the series about shapes recognition. This post is also available as a part of a playground. Naive implementation of rendering user's freehand drawing is strait forward. We need to listen to touch events from view and construct the path appending lines to each subsequent point. public class LineDrawing: Drawing { public var canvas: DrawableView? public var path = UIBezierPath() public init() {} public func touchesBegan(at point: CGPoint) { path.removeAllPoints() path.moveToPoint(point) } public func touchesMoved(to point: CGPoint) { path.addLineToPoint(point) } public func touchesEnded(at point: CGPoint) { path.addLineToPoint(point) } public func touchesCancelled(at point: CGPoint) »

Dependency Injection (DI) in Swift

This post is a script of the talk that I've made on UIKonf'16. That was a first time for me to present on such a big conference and honestly I'm not even close to a public speaker so you may enjoy just reading it more. Anyway here is the video. And slides are here. For many of us Swift opened up a world of functional programming. But it is still much more object oriented language than functional. And our main tools - Cocoa frameworks - are object oriented. So probably we ourselves will still keep writing object oriented code. The »

Mixing optional binding and boolean expressions

There were few times already when I used this little-known feature of Swift in real code and it improved (in my opinion) readability a lot and much better described the intention of the code. Here is the original code from the real app: if let cutoffDate = menu?.cutoffDate where menu?.mealSwapEnabledForProduct == true { ... } else { ... } Very trivial piece of code. But it contains one problem - it communicate wrong intention. When optional binding comes first and is followed by where it may seem that we make decision based on the value in this optional and the boolean expression is secondary. But in »

~= vs Range.contains(_:)

Today I was working on simple validators that we use for forms (backed by awesome Eureka) and had to implement validator that validates string length. So I did it like this: struct StringValidator: Validator { typealias ValueType = String let stringRange: Range<Int> init(stringRange: Range<Int> = 1..<Int.max) { self.stringRange = stringRange } func validate(value: String?) -> Bool { guard let value = value?.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) else { return true } return stringRange.contains(value.characters.count) } } The idea is simple. Form field can have a validator with default range (1..<Int.max) that will validate any not »

On package managers

My 5 cents on package managers. I definitely agree with those who say that you should not depend on code from external source (meaning where and how it is hosted). You should check in any code or binaries, used by your project to your own repo. But in fact it is not enough. Speaking specifically about iOS/OS X development if you are using CocoaPods or Carthage and work in a team you will end up, ironically, with managing versions of your package manager. The main problem of these tools is that you need them to be installed on the »

Creating a simple OS X app

OS X developers are kind of rare developer species. I don't know about you but among my fellow developers there is only one who is doing OS X. I'm not sure if Swift's popularity will (or already does) change something, most likely we will have more Swift backend developers instead. Anyhow. Recently I came up with an idea of a simple app that can help me and my colleagues in our daily work. At HelloFresh when it comes to dates everything becomes very special. We don't use gregorian calendar week - instead our week starts on Saturday and ends on »

Intermediate action segues

Storyboards segues are very cool. They are very easy yet powerful. They help to incapsulate presentation logic and move it out from view controllers. And adaptive segues are state of the art. There is only one thing (almost) left if view controller - managing segue performance using those two commonly used methods: func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) And those methods are the place where we usually screw up everything with our custom logic based on tons of if or switch statements. Then we introduce different routers, coordinators and God knows »

Properties of types conforming to protocols in Swift

In Objective-C it's very natural to have a property of type that also conforms to one or few protocols. In Swift that becomes tedious cause you can not simply combine types and protocols. You can use generics: class MyClass<T: MyOtherType where T: MyProtocol> { var property: T } But you will notice soon that this approach has more drawbacks then advantages. First if you need to have another such property it will become a mess. Second is that you can not use this type in Interface Builder anymore, as well as you can not see it from Objective-C environment. »

Dependency injection with Dip

Note (15.04.16): This post is updated to reflect some of the latest changes in Dip. In some of my previous posts I wrote about using dependency injection with Typhoon framework and described some internals of analogous pure-Swift framework called Dip. Here I want to illustrate how Dip can be used in a real project using the same example that I used before. Also this post will contain a sneak peak of some upcoming extensions of Dip (probably they will be released as separate projects). You can check out source code here. Note that it uses my fork of »

IoC container in Swift. Circular dependencies and auto-injection

Note (15.04.16): This post is updated to reflect some of the latest changes in Dip. In my previous post I wrote about Dip, lightweight IoC written in Swift. Here I would like to describe how some other of it's features were implemented. They are not yet available in original repo, but you can check them out in my fork. Circular dependencies Let's say we have a server-client model where client has reference to server and server has backward weak reference to it's client. First problem is that we can not have two objects that have reference to each »

IoC container in Swift

Note (15.04.16): This post is updated to reflect some of the latest changes in Dip. In my previous post I talked about dependency injection framework for Objective-C called Typhoon. You can skip this paragraph discussing why it matters and jump straight to the point of this post. It's very easy to start to use it, yet it's very powerful (maybe even too much cause there are so much stuff you can do with it). When I first time saw it it was not love at first sight. I though: "Pfff, I don't need all these crazy swizzling »

View controller thinning. Dependency injection.

In my previous post I described how you can break business and presentation logic in small PONSO's to achieve better separation of concerns and think view controller. To wire up dependencies, particularly those PONSO instances with view elements and actions I heavily used Interface Builder. In this post I will show how you can do the same using IoC-container instead of Interface Builder. As example of such IoC container implementation I will use Typhoon framework. To checkout the full code you can use this repo. First lets start with defining what IoC-container ("Inversion-Of-Control-Container") is. I will not dive »

View controller thinning. Behaviors and Interface Builder.

In previous post I showed how you can move some presentation logic from view controller to view. Now view controller is responsible only for business logic, in this case making login request and handling its result. But now you would say: "You just moved presentation logic from controller to view. Now you have Massive View!" And you will be right. Though view is a perfect place for presentation logic that leads to that view should know everything about its subviews and it will probably change when we change something in its subviews. So in this post I will »

View themes

In my previous post you could see that I've used ColorTheme and ThemedView protocol to easily customize view appearance. Though that solution works I was not satisfied with it from very beginning. Here I try to find another solution. What I really didn't like about my that solution was a check of tag type (if let tag = tag as? FormTextField.ThemeColorTag). Usually I try to avoid any kind of type checking. But here I have nothing to do but to check the type of tag. The problem is that I tried to define some base protocol for color them. That »

View controller thinning

"Massive view controller" is one of the most favorite topic for iOS developers when they talk about architecture. A lot have been said on this topic already, even more will be said in future cause unfortunately there is no silver bullet and view controller still stay massive in many projects. Recently Andy Matuschak presented here and there a live coding session on this topic. So you can see it's a well know and still actual problem. The real problem is that there are a lot of responsibility in UIViewController already defined in UIKit. So why to add even »

Path to Carthage. Real-life experience.

When it comes to dependency management in Cocoa world you have three options: Cocoapods Carthage Don's use dependency management First one, Cocoapods, have been around for quiet a long time already and is default tool for most of developers. It was designed from the beginning not just as dependency management tool, but as ecosystem for third party open-source components. It is easy to use in most cases. But it can be very painful to manage especially when it comes to customization and your lack of Ruby experience. Once I had few very hard days trying to make it work for »

Networking in Swift

Recently I've updated my post on how you can implement lightweight networking in Objective-C. Now it's time to look at the same problem from perspective of Swift. If you want to check out code right away you can do it on Github. As AFNetowrking is the default tool of choice for most of Objective-C developers, Alamofire became such in Swift community. But it's always useful to practice and find your own solutions. So let's look how we can do networking by ourselves and what we can achieve there using powerful Swift features like generics, structs and enums. Endpoints When you »

Lightweight networking in Objective-C

AFNetworking is the most popular networking library for iOS. Chances are high that it's the first pod you add to your Podfile. It's used as a standalone network layer and as a part of some other frameworks, like RestKit. For me it has earned it's popularity for few reasons. It's well maintained, what is very important for open source project (thought it still has long living issues). And it has well thought architecture and interface, so it is easy to use and extend to your needs. When we perform a request using AFNetworking we can receive serialized JSON object, either »

Testing Sync Engine

Here is a small presentation that I've made about two weeks ago for our Wire team that provides some overview of Sync Engine testing (by Sync Engine we call our in-house framework that does all networking and data base management). It covers main problems we have to solve and what we still have to do and how we plan to do it. If you want dive deep in code and know i.e. how we deal with Core Data in our tests - checkout this great article for by Daniel Eggert. »

Swift 2. Part 1.

This year I was lucky enougth to go to WWDC as part of Wire team. For me the most exciting stuff Apple introduced this year was Swift 2. I went almost to every session about programming languages, ignoring watchOS sessions and games completely. Though the main inspiration I've got from WWDC was to learn game development using Apple tools, like new GameKit. But that's not the point of this post. After comming back from WWDC we had a tech talk at Wire and talked with our colleagues about the conference. I've presented about Swift and Objective-C and here is what »

Swift interesting features

or What Swift Language Guide do not tell you. This post contains the list of interesting features of Swift that I find while using it. To make it more interactive I've put it in a playground that you can checkout here. The list is intended to be updated in future. If you have something you want to share, pull requests are welcome. Contents: Var in for-in loop Property observers for local variables ~= operator Curried functions Subscript with more than one parameter (by AirspeedVelocity) Var in for-in loop If you have an array of reference type objects you can mutate them »

Custom UITextView in Swift

In this article I want to describe how I developed custom UITextView component in Swift using TextKit, Playgrounds and IBDesignable and IBInspectable directives. You can check out source code on github. In this component we will add "read more" behaviour to text view. It will have two modes - full mode and trimmed mode. In full mode it will behave like standard UITextView. In trimmed mode it will trim text to some maximum numbers of lines and trim text with a string (like "Read more"). When user taps on "Read more" the component will »

Quick overview of Swift Playgrounds in iOS Simulator

Probably lately you've seen few posts on this subject like this or that. Both of described techiques share the same secret - how playground is run in Simulator. Actually it's quite easy, but not obviouse as all windows needed for that are hidden by default - you just need to open up File Inspector for your playground file, select iOS platform and check "Run in Full Simulator". This will run iOS simulator and run your playground almost like ordinary application. But this techniques differ in a way they present "interactivity" of playgrounds. The latter uses XCPlayground »

Info.plist preprocessing

This is quiet interesting XCode feature I was not aware of until last week. Maybe you will find it not so interesting and definitely will not use this on everyday basis but sometimes it can be helpfull. For example it can be convenient for separation of production and test configurations (some of them). In project Build settings you can find section called "Packaging" and there are several keys we are interested in: Preprocess Info.plist File (INFOPLIST_PREPROCESS) Info.plist Preprocessor Prefix File (INFOPLIST_PREFIX_HEADER) Info.plist Preprocessor Definitions (INFOPLIST_PREPROCESSOR_DEFINITIONS) To enable Info.plist preprocessing »

iOS storyboards: segregation

Recently here at Rambler&Co mobile team we decided to try technique of storyboards segregation (separation in other words). We came to the conclusion that this simple technique together with other techniques we use can help us to improve our's projects architecture, code readability and stability. Here is what we came up with. Many techniques of applications development are based on user stories (or use cases), in short - small logically connected pieces of functionality that application provides to user. Developers too also use the term of 'use cases' in application architecture design. So why not to use this »