This is my archive

Serverless architecture with AWS explained

There is no better way to explain the boom for serverless architecture and cloud computing than to quote Gartner’s words:

“Serverless architectures enable developers to focus on what they should be doing — writing code and optimizing application design — making way for business agility”. 

A serverless architecture (or serverless computing, in other words) is a hot technology with a catchy yet slightly misleading name. Though it may imply a completely server-free approach, serverless services and applications de facto run on servers. The magic beneath is that organizations and app creators don’t have to worry about managing the physical servers that host their codes.

How does serverless architecture work, what are its benefits, when to use it, and what are the most popular vendors? Let’s consider the answers in this short guide.

serverless architecture benefits
Serverless architecture benefits

What is serverless architecture? 

Long story short, it is a model of cloud services in which the developer focuses solely on creating business logic and not the infrastructure on which it is to be executed. As mentioned before, physical servers do actually exist. The point is that when creating a serverless solution, you don’t have to hire a highly specialized DevOps engineer responsible for setting up the machines, configuring networks, or updating operating systems. This leads to a significant cost saving, as DevOps are currently almost the most high-paid specialists on the market.

The whole responsibility of server management is handed over to serverless service providers, with Amazon, Microsoft, and Google being the Big Three. At the same time, serverless architecture is a different approach to software development. App builders combine various services (building blocks) that are available in the public cloud. This way, code written by developers is run using only precisely the number of resources that are necessary to support them. 

When a predefined event occurs, the serverless platform runs the task. Thus, the developers or platform owners don’t have to predict how many times the function or event will be used – they simply pay a minimal fee each time the core is run. 

This approach delivers highly scalable solutions with improved app performance at optimized costs. 

To put this more straightforwardly, it’s usually a cheaper solution. 

The whole system relies on cloud vendors and we can distinguish between two models: 

When to use a serverless architecture? 

Serverless architecture is an excellent solution for online business needs. It allows quick scaling, faster and cheaper software development, as well as improved performance. All of these are great news to business-oriented IT professionals because all of the resources saved on back-end development can be furtherly invested in future development. 

Including serverless architecture in your business may benefit your goals, especially if you’re planning your app to:

About Amazon Web Services (AWS)

AWS is the largest and most popular public cloud in the World. Currently, it includes over 160 services from an extensive range. Examples include computing power, storage, artificial intelligence, blockchain, Internet of Things, Augmented Reality, and even the Amazon Ground Station service for satellites.

What made AWS so famous? Amazon claims a couple of possible reasons:

advantages of the Amazon Web Services
advantages of the Amazon Web Services

Six reasons to go serverless

Although serverless architecture is not a magic solution for any organization’s problems, it does offer several substantial advantages. 

A significant increase in go-to-market speed

Let’s state the obvious: less time spent on development, deployment, and other operations mean that your users will be able to enjoy your app much sooner. FaaS functions are a lot easier and faster to deploy than whole dedicated servers.

Cutting an app’s operational costs 

When deciding on the serverless approach, you outsource some part of the development and maintenance to a third-party provider. Then, for a fee, they manage the servers and databases of thousands of companies, with which you share servers and hardware, etc. This sharing economy solution appears to be much cheaper and more efficient when it comes to the time your developers need to maintain your application. Plus, you pay only for what is used.

Reduced development costs

The serverless BaaS approach comes down to sharing whole application components with other companies that use the exact same logic in their products. There’s no need to spend more time and money on reinventing the wheel. Serverless allows you to utilize ready-to-use back-end mechanisms that have been polished to perfection by many developers and are proven in battle. 

Reduced scaling costs

The Feature-as-a-Service model allows your application to scale automatically, growing together with your customer base. The process is completely taken care of by a provider and, importantly, you can start small then let the server costs grow proportionally to your business development. After all, you only pay for the capacity that you need at any given moment. 

Easier operation management

Without any back-end infrastructure to worry about (as this is entirely the vendor’s responsibility), you don’t even have to think about the infrastructure maintenance tasks that would keep you up at night. Neither, software updates, security, nor any system administration are your problems any longer.

More efficient capacity management

With the old approach, you would have to make decisions regarding the capacity you might need for a while, based on, at best, predictions by your team. Unfortunately, this often means underestimating or overestimating. The former creates a problem for your users and potential server crashing issues. The latter means not utilizing the total capacity that you are paying for. In both cases, you lose money. Fortunately, such problems won’t occur with serverless architecture. 

Top serverless alternatives to Amazon Web Services

Although AWS is the reigning king of serverless solutions, there are plenty of others you can choose from. Let’s consider a few of the most frequently used ones.

Google Cloud Platform

Google Cloud’s serverless solution allows developers to build applications using containers, making the dev experience easier. Google Cloud Platform is perfect for apps that use Big Data, advanced analytics, and machine learning. One of its most significant advantages is fast response times. 

Microsoft Azure Serverless

Azure holds the market tightly, especially when it comes to enterprise customers – most of which utilize Windows and Microsoft software. So when they entered the cloud market, Microsoft simply took its old on-premises software like Windows Server, Office, Sharepoint, .Net, and others, then moved them to the cloud. 

Qinling

Qinling is a FaaS for OpenStack. The main goal of this project was to create a platform that would support serverless functions (like AWS Lambda), function package storage solutions (such as local, Swift, or S3), and container management platforms (Kubernetes, for example).

Serverless frameworks

Anyone who enters the world of serverless architecture must learn about serverless frameworks. Building serverless platforms demand a tool for developing and deploying, which is what serverless frameworks are for. There are a couple of frameworks for building serverless apps including Apex, Gordon, or ClaudiaJS for Javascript; Sparta for Golang; or the most universal Serverless Framework that works well for Javascript, Golang, and Python. 

Serverless’s users praise its easy learning curve and rapid development, which is reflected in the numbers – over 36.6K stars on GitHub and 15M downloads at the time of writing (with numbers still growing!).

Is the future serverless? 

According to a survey conducted by O’Reilly on 1.5K programmers, 40% of them have faced serverless architecture in their companies.

In 2020, a DataDog survey showed us that over 50% of AWS users are now using the serverless AWS Lambda Function as a Service (FaaS). 

The global forecast for 2021 indicates that:

The Function-as-a-Service (FaaS) market size is estimated to grow from USD 1.88 billion in 2016 to USD 7.72 billion by 2021, at an estimated Compound Annual Growth Rate (CAGR) of 32.7%.”

And those numbers shouldn’t shock anyone. We’re all surrounded by software daily, and the market is getting more competitive than ever before. So software developers, investors, Venture Capitals, and even business owners need solutions to make releasing app iterations faster and cheaper. 

Serverless architecture seems to be the perfect solution to that, with a vibrant community constantly testing, building, and improving existing solutions as well as creating new ones. 

Summing up

Here at CrustLab, we sincerely believe that the future is serverless. It makes creating software more affordable and inclusive, which boosts creativity and the quality of the market. In addition, optimizing development, deployment, and maintenance processes as well as conveying part of the responsibility to third-party solutions lowers costs both financially and environmentally (shared-economy solutions are proven to reduce the amount of energy required to maintain servers).

We’re not saying that this solution comes with no limitations, and it’s not the way for everyone to go. But if you think your business could benefit from implementing a FaaS or a BaaS model or have any other questions, please contact our team.

What is React.js and how can that technology be used to build a custom web application?

Anyone that is at least slightly interested in the web development world must have heard about React.js. It’s a powerful and popular front-end JavaScript library (not framework!). React is used to create many everyday use applications including Netflix, Facebook, Instagram, Airbnb, and Dropbox. 

What’s more, according to research by the State of JS, for a good couple of years it has held a strong position among other technologies in terms of developers’ satisfaction, awareness, interest, and usage.

And no wonder, since it lets entrepreneurs build custom web apps with beautiful interfaces and a remarkable User Experience. Compared to other technologies such as Angular.js, React brings excellent results when it comes to app performance and development speed (hence, development costs). 

With that in mind, let’s dive into the story that will answer your React-related questions, such as:

What is React.js?

The React library was created by Facebook developers in response to an issue that Facebook developers were facing. They were on the lookout for a way to build dynamic, interactive, and visually appealing interfaces with no loss in efficiency or performance. And that’s how React.js was born. 

Originally intended for internal projects, it was launched as open-source in 2013 and has taken the Javascript community by storm. It is still maintained by Facebook and now has millions of developers and hundreds of contributors. 

React.js is an efficient and elastic JavaScript library for building user interfaces. It allows engineers to quickly build complex UIs for web and mobile applications. Its approach to building a User Interface is component-based, meaning that a developer creates separate and isolated component pieces of code with their own properties and functions, making the whole code easier to debug.

This structure guarantees a number of business-friendly benefits. Here are a few of them:

Except for the component structure, the uniqueness of React lies in two features – the usage of a JSX language and a Virtual DOM. Those who are interested in how it works will find a short, explanatory React.js Dictionary at the end of this article.

About the benefits of React.js

Vibrant open-source community

By choosing React.js, you get access to thousands of passionate React developers who keep contributing to its growth in the package. As one of the most popular open-source technologies, it has over 2M repositories on Github. However, React is now considered an established and stable technology. The community still creates new frameworks and tools, such as  Storybook and React Bootstrap. They also provide support for anyone who is new in the React world. Plus, it has the giant of Facebook standing beneath it.

It will save you time and money

There are thousands of reusable components available as open-source libraries. Developers can put them in various project slots, working more efficiently and not ‘reinventing the wheel’. This approach pushes much higher code quality while significantly decreasing the amount of time needed to build apps (therefore saving developers’ time and reducing project costs).

Better performance

React was created to solve the issue of lousy performance in the context of more complex applications. Long story short, it worked. Thanks to Virtual DOM, given its number of features and utility, it scores excellently when it comes to web performance, guaranteeing lightning-fast apps with low loading times.

Great UX and UI

React.js makes it easy to create dynamic web applications because it guarantees more functionalities with less coding, which is a direct benefit of its component structure. Virtual DOM offers a unique and effective way of updating an app’s views by only updating single components when changes are detected. This allows for the creation of advanced apps with interactive User Interfaces. The vast majority of components have been previously coded and placed in the Github repository.

One-way data flow

In React.js, how a user sees a component depends on its state. Any of their actions (such as clicking on a button or filling up a field) can change the component’s state. This change is transmitted to its view and, in sequence, to the inheriting components. 

This approach makes the application more efficient (as the relationship between particular elements of the interface is clearly defined), less prone to errors, and easier to debug (as a developer has greater control over the data flow). One-way data flow also makes it easy to analyze an app’s performance, since any slow-downs can be detected in the blink of an eye as the changes to a component affect only that component itself.

SEO-friendly

Crucial as it is, not many JavaScript frameworks deal well with search engine optimization. React.js drastically improves page load speeds, one of the primary criteria for the Google index algorithm. In addition, apps built with React are lightweight, offer server-side rendering, and can load in the blink of an eye. 

The benefits of React.js
The benefits of React.js

Cross-platform development with React Native

React Native is a framework created by Facebook to speed up the process of mobile app development. Previously written React code allows you to simultaneously build apps for both Android and iOS platforms. As it uses bridges to translate JavaScript into native components, code is used to build both iOS and Android native apps once it has been written.

This is perfect if you need to build an uncomplicated mobile app without many resources. The more complex the app’s features are, the more native code snippets need to be written. The code created for a web application may be reused for mobile ones – developers build a reusable library that can be leveraged in both web and mobile apps. 

Is it possible to create a server-side rendered app with React? 

First, we need to clarify the main differences between client-side rendering and server-side rendering.

In client-side rendering, a browser downloads a basic HTML web page then renders the JS parts and fills them with content. Server-side rendering means the React components are rendered directly on the server, delivering HTML content. 

Combining it into a web application that can be rendered on multiple platforms simultaneously, we get an isomorphic application that renders on both the server and the client (web browser) sides. Creating such an application, developers build one common component tree, which is rendered on a server after the request. This results in sending an HTML code with all the data to the browser, which later loads the JavaScript in the client version of a React application. 

There are two main advantages of such an approach:

Search engines don’t read JavaScript. If the content is not in HTML, they see it as a blank page, no matter how helpful it is. 

In server-side rendered applications, their performance depends only on the server’s resources and the capabilities of the users’ network. And it’s been said multiple times that improving the speed of an app improves the overall user experience drastically. 

When should you use React for web development?

React has proven its capabilities when building both Custom Web Applications (just take a look at Netflix, Instagram, PayPal, and many more) and simple single-page apps (SPAs). The main difference between a single-page application and a traditional multi-page app is that navigating a SPA does not require moving to an entirely new page. Instead, views load within the same page. When having a proper routing configured, single-page apps tend to be even faster and better optimized.

Getting back to the types of apps you can build with React.js… Well, there are a lot. 

Social Networks

Single Page App - Pinterest
Single Page App – Pinterest

Why does it work so well?

Examples:

Video Platforms

Video Platform - Netflix
Video Platform – Netflix

Why does it work so well?

Examples:

Sharing economy platforms

Shared economy platform - AirBNB
Shared economy platform – AirBNB

Why does it work so well?

Examples:

SaaS platforms

SaaS platform - Invision
SaaS platform – Invision

Why does it work so well?

Examples:

E-commerce platforms

Ecommerce platform - Shopify
Ecommerce platform – Shopify

Why does it work so well?

Examples:

Communication platforms

Communication platform - Skype
Communication platform – Skype

Why does it work so well?

Examples:

What is a JSX language?

HTML files are the core of every basic website. They are read by web browsers and translated to appear on your devices as web pages with the desired UX and UI. To make it possible, browsers create a Document Object Model (DOM) – a structure of how the particular components are arranged on the website. 

Web developers may add dynamic content to the web pages by adjusting the DOM with programming languages like JavaScript and additional extensions. 

JSX (JavaScript eXtension) is a React extension for JavaScript that gives its users the opportunity to change the DOM with ready-to-use components written in simple HTML code. It is known to save them lots of time and significantly improve site performance. 

Virtual DOM in React.js

When not using JSX to modify the DOM, a website will probably go with HTML. And for basic, static websites, that is absolutely fine. However, things get tricky when you host a complex, dynamic website that requires lots of user interaction. In that case, the entire DOM has to reload every time a user clicks on a button or fills in some field(s) on a form.

In a scenario when a developer uses JSX to update the DOM of their website, React.js creates the Virtual DOM (VDOM). It’s a virtual image of a UI that is saved in the memory and synchronized with the real DOM by a library (such as ReactDOM). Using React’s declarative API, you can notify the DOM about which components need to be selectively refreshed and which ones should stay the same. This way, the page load speed improves, computer and internet memory usage decreases, and this results in a faster, more user-friendly site. 

Wrapping up

React.js is a powerful JS library that brings many benefits such as component reusability, Virtual DOM, performance, and stability, unidirectional data flow, and many others. Although it is not the perfect solution for any case, it has helped many great businesses like Skype, Instagram, and Shopify to achieve their successes.

It’s up to you to decide which technologies will take part in your own success – we hope this article has imparted some wisdom to you. Feel free to contact us if you have any doubts about React or picking the right technology stack for your project!

Flutter for cross-platform applications development: nuts and bolts

In order to develop effective cross-platform applications, a number of factors need to be considered, and one of them is the approach it is implemented in. While some companies rely on native technologies and use React Native in their development processes, others are increasingly interested in Flutter. Today, we will examine why that is the case.  

What is Flutter, actually?

Flutter is a set of software development tools that are used to develop cross-platform applications on devices with Android and iOS operating systems simultaneously. The technology was developed by Google and is widely considered to be in practice a way to increase speed, quality, and lower cost of the entire project.

The language that Flutter is based on is Dart, which is an object-oriented and statically typed language. Further, Dart has become relatively straightforward to master, since the Dart developers assumed that their goal was to create a similarity with other programming languages rather than to create innovative solutions. Mobile applications written in Dart may appear and behave almost exactly the same on both platforms with performance comparable to native applications. 

Knowing Dart allows a developer to take advantage of all Flutter’s features – both the implementation of views and application logic. A widget is an important element of this framework since it is the component from which the application view is built. A widget can be anything, from text to images and anything else. It is possible to nest widgets within other widgets, giving you the ability to compose very complex objects in a relatively short amount of time.

Furthermore, the Flutter ecosystem is already quite advanced and very rapidly developing, despite its relatively short history.

Native versus cross-platform applications

As Michal Sulek, Mobile Development Lead in Crustlab indicates: 

Flutter is, in my view, the best platform for the creation of cross-platform applications since the development is relatively simple and straightforward. Its primary competitor, React Native, is more challenging (but cannot be described as difficult). React Native has undergone a number of changes over the past few years, which complicate its development.

Whenever Flutter is mentioned, its biggest competitor – with regard to cross-platform applications – is React Native. What is a better alternative? React is without a doubt a more mature tool, and its advantage right now is definitely the large community and a large number of libraries that are available. Certainly, both platforms have their advantages and disadvantages, but both guarantee a fast and solid application.

However, there are certain factors that may tilt the scale in favor of Flutter in the future. The Fuchsia operating system has been developed by Google for a few years and uses Flutter as a user interface layer. The rumor already circulating on the web is that this system would eventually replace Android, erasing its greatest defect. Importantly, it would also support all existing Android applications.

Shall you develop a mobile app using only one method, or can you mix them? Check Michal’s take on this one. 

Cross-platform applications? Well, it usually depends. Flutter apps are always a bit behind their original counterparts, so if something new urgent comes out for either Android or iOS, it might be that hybrids will have to wait until it is ready for them. In a Flutter framework, like React Native, the module developers have a lot of input. It is beneficial that they are so open-source, and everyone may contribute their own plugin, but on the other hand, it sometimes affects the overall quality of these plugins. There are also many minor mishaps or bugs in Flutter itself, resulting in some UI glitches. If we want to develop a serious application or a larger project, we shouldn’t rely on the hybrid architecture, as there’s always room for error.

Technical and business bits on cross-platform applications

Flutter can optimize costs

Theoretically, simple apps written in Flutter can result in significant financial savings (even up to 30%). How does it actually work? What makes Flutter so powerful (and cost-effective) is that it is based on one, unified code-sharing. All the platforms use the same common code, which is also written in a single language, Dart.

Importantly, this rule applies equally to each part of the application, including the UI. As Flutter relies on one common source code to build cross-platform applications rather than two separate native apps (that would often require hiring more people or allocating more resources), Flutter offers significant cost optimization.

Flutter is efficient

Flutter isn’t much different from native applications in terms of efficiency.

Thanks to the Skia engine for rendering views, applications using this technology are able to run as fast as native applications. A typical application in this technology ought to run at 60 FPS (frames per second).

As a result, the pace of project development and the speed of responding to changes is greatly accelerated, allowing programmers to focus on their business logic without fumbling around with the specifics of a particular platform. Since Flutter applications use only one syntax, they have a consistent and transparent implementation, which makes them easier to test and understand.

Flutter is trustworthy

Since Flutter technology is developed, maintained, and promoted by Google, a global technology player whose products are used by thousands of people worldwide, it inspires trust and is constantly updated, not only by Google itself. Flutter is based on contributions from the community, which is what largely determines its strength and popularity. Consequently, it is extremely dynamic, and it is very important that it incorporates the comments of the community when it is being developed.

Flutter challenges

It goes without saying that Flutter has a bunch of advantages, but there is no such thing as an ideal technology. The challenges listed below should be considered when determining whether a given project would be better served by native development or still should go with Flutter. 

Technical and business bits on cross-platform applications
Technical and business bits on cross-platform applications

Flutter cross-platform applications you may know

Alibaba cross-platform app

A team of developers at Alibaba Group’s Xianyu created an app with Flutter. 

Alibaba already had an existing app. Thus, the first step in the process was to implement Flutter’s features and then add additional functionalities based on the framework. 

Over 50 million downloads have resulted in over 10 million daily active users. By choosing Flutter, they were able to save time because the application can easily be created and maintained with a single codebase. 

The use of Flutter was not a replacement for native application development, but rather a means of supplementing cross-platform solutions. Alibaba integrates Flutter into their native applications in order to provide the best experience.

Groupon hybrid app

Groupon, another example of a company that utilized a pre-made application, chose to integrate the Flutter technology with an existing system rather than entirely re-build it. 

Groupon decided to create two types of apps in Flutter, one for customers and one for merchants.

Groupon apps allow merchants to track campaign performance and track customer feedback. They also assist customers with the provision of customer support and enhance their experience.

Philips Hue app

Philips Hue is a lighting system for smart homes and provides accessories for customers who desire intelligent lighting. Hue Sync and Hue Bluetooth are both apps built with Flutter. Using these controllers, Philips’ clients can set the mood and alter the light’s color and synchronize lamps with their media sets, and quickly and easily control them with their mobile devices.

Philips has been using Flutter since 2018 and found it to be a good fit for their project even though a number of other suitable alternatives were available. Flutter seems to fit their needs perfectly, so they continued using it. 

SpaceX Go mobile app

All SpaceX information is accessible through this app, which has a detailed list of both previous and upcoming rocket launches. In addition to that, there’s a catalog of all the vehicles and more information about rockets, capsules, and ships built by SpaceX over the years.

This application includes a ship locator that allows users to view the status, position, and speed of the active SpaceX spaceships. It also provides Tesla location data.

Grab cross-platform application

Grab mobile app enables people to order food for delivery to their homes. Flutter has been used to develop Grab’s merchant application for restaurants. This software provides local businesses the opportunity to grow by adding menu items, managing orders, and displaying their earnings. The burgeoning food delivery business has been able to grow even more rapidly as a consequence of that.

My BMW hybrid app

Within the BMW Group, the software platform for the My BMW app is referred to as the Mobile 2.0 App Core. Developed in-house, it adopts the very latest technologies and includes a broad data ecosystem. Developed with the open-source Flutter framework and written in the Dart programming language, the My BMW app can be used on iOS and Android devices. 

Fun fact: with over 300 developers, the Flutter/Dart team at BMW Group is the second-largest in the world.

Wrap it up

The use of Flutter is definitely a viable solution for mobile app development in many business cases. 

It is undeniable that Flutter has provided added value and considerable proliferation for the mobile industry. This is without question a significant step towards developing cross-platform applications.

It is not necessary to engage two independent development teams anymore to write two different sets of codes. The result is a reliable product that is developed in a significantly shorter time and for a much lower cost than native methods alone. Accordingly, if your anticipated mobile product meets these criteria, Flutter could be a great option for you. 

Although this technology is not without disadvantages and is not suitable for all applications, it has already established itself as a real competitor. From the pace at which these technologies are growing, it is not impossible to expect that it may become a leader in its field in the near future.

Why is headless CMS the future of web development? Comparison of Headless CMS systems

The growing number of headless CMS systems encouraged me to dive into the topic and present my experience in CMS systems for web and mobile development. Before we go through all the pros and cons of this approach to managing content, it’s a good idea to explain what headless CMS is.

What is the headless CMS?

A lot of customers are electrified by the “headless CMS” buzzword. I didn’t find the phrase origin but the meaning can get across very easily. The old well-known CMS systems (AKA coupled CMS) consist of two main layers: the admin panel – where an editor can add some content and the UI part that displays the content of the website. According to Wikipedia, the term “headless” comes from chopping the head off the body. In this context “head” is a frontend part of the app and the “body” is a backend part. So headless CMS is a system that contains only the backend part. There is no graphical interface that represents the content entered by an editor to the admin panel.

Traditional CMS vs. Headless CMS comparison chart
Traditional CMS vs. Headless CMS comparison chart

Headless CMS doesn’t have a graphical interface

Now you are probably thinking: why the heck do I need a CMS that cannot display any information to the user? At first glance, a headless Content Management System looks like an unfinished project. Actually, it’s not. This new (old) approach to the CMS lets us resolve one issue that occurs frequently. What if I want to build my back-end and front-end sides of the app in different technologies? Now it’s possible. You can grab your favorite frontend framework and just consume the content from the headless CMS API.

Why is WordPress not always the best choice for my website?

First of all, WordPress CMS is a great Content Management System. Both huge companies and small businesses decide to use this solution. The number of plugins and the project’s maturity make it the first choice in case of choosing a platform for a wide variety of the company’s websites. Dozens of available themes and optimization for SEO are the most important factors why WordPress is chosen as a solution for landing pages and blogs. Definitely, it’s a fantastic tool from the editor’s perspective.

On the other hand, WordPress is a vast CMS not only from the editor’s perspective but also from the development team. Do you really need all these features on your simple landing page? What if you want to use different technologies on the front-end side? WordPress is a monolith project. As I said earlier, the backend and front-end sides are strictly coupled. There are a bunch of cases where a monolith architecture is not the best choice. Let’s imagine that you want to implement a landing page for the app. Your app is written in React but you also need an editable landing page. So if you are going to use WordPress, you need to move your branding to totally different technology and write all your components once again. Additionally, every time you change something in the app’s header or footer, you probably need to do the same on the landing page because you want to be consistent across the whole app. There are probably a number of workarounds that help you omit the above problems but do you really need a workaround? What about using headless CMS in such scenarios?

What are the pros and cons?

Pros

Cons

Which solution should I choose?

Suppose you want to choose the best solution for your business. You need to consider a couple of things. First of all, do you want to host your system on your server (Strapi, Ghost), or do you want to use a cloud solution (Contentful, Sanity)? What functionalities are you looking for? Do you want headless CMS to create posts on your blog, or need a more advanced system to store data in relations? How do you want to return data to your frontend app? Do you want to use REST or GraphQL? Below you can find a quick overview of the most popular solutions.

Headless CMS comparison
Headless CMS comparison

Strapi

Strapi is a self-hosted, database agnostic, open-source headless Content Management System. This CMS supports both SQL and NoSQL databases (PostgreSQL, MySQL, MariaDB, SQLite, MongoDB). The Admin panel looks like a customized DB client. You can create tables, add relations, and adjust responses to your needs. It’s a great choice if your application requires mostly CRUD operations.

Ghost

Ghost is a modern publishing platform. It’s the right choice for news apps or blogs and the post entity is the primary data type. You can create drafts/ schedule your publications and even inject custom code to your site’s header and footer directly from the admin panel. The ghost text editor supports Markdown. There is an option to embed cards from e.g. YouTube or Spotify but also create custom HTML elements. You can organize your content using tags. The platform automatically generates RSS feeds for collections, tags, and authors’ archives. A lot of SEO aspects have been implemented directly into the core – usually, there is no need to use external plugins. You can add an alt attribute to images and link tags to the RSS feed. Additionally, there is an option to customize metadata separately for every post.

Contentful

Contentful support real-time team collaboration. The text editor has a feature called “Rich Text Commands” – it lets you quickly embed entries using a command panel without leaving the editor context (you just need to type “/”). All your content is served via JSON API. Contentful supports versioning – there is a way to revert content to the previous version.

Is it the right for my company?

In my opinion, headless Content Management Systems are the future of web development. The popularity of omnichannel solutions changed the way we have to think about content management. Coupled CMS systems like WordPress are no longer the best choice if you want to use the same backend for both web and native mobile apps. When it comes to making a decision, you should ask yourself: Do I need to create my digital product for web and (native) mobile? How often would I need to change my website? Am I going to reuse the data in other products? Do I need a complex CMS system?

I fully realize that the choice is difficult. The best approach would be to ask a partner with technical expertise to support you in making such a dissection. We are always happy to help you!

Top 10 Web Development Frameworks To Consider In 2021

The knowledge of HTML and CSS has invariably been the basis of web development for years. These skills are still essential, but as in every modern programming technology, things have been covered by a higher level of abstraction to give developers tools that would let them create better software in a more performant and safe way. There are many frameworks designed to support web application development. But what exactly is a web development framework? It is a solution that helps construct internet applications and functions according to the architectural rules of browsers and mostly HTTP communication protocols.

Frameworks or development libraries are nothing more than packages or collections of programmable solutions and programs that help develop an application. Thanks to the framework or library, developers could easily use web resources and APIs to build web services. As a result, development time has been significantly shortened by, for example, facilitated everyday activities performed in web development compared to the standard way of building and deploying web applications. Most frameworks have their own libraries enabling access to the database, which contains information about the structure of the templates used, and session management. It can be useful in both cases, dynamic websites, and static websites.

Typically, frameworks act as an extension of the capabilities of a given programming language or a tool or a set of solutions for an application of a given type, e.g., CMS, mobile development tools, or web application.

The following statistics are the best proof of the popularity of the usage of frameworks and development libraries:1,850,673 detections of frameworks in the Top 1 million sites from around the world – according to BuiltWith,

the total number of React downloads in the last two years exceeds 6 million. For Vue and Angular, this value is over a million downloads – according to Tecla,

in 2018, almost 80% of the surveyed developers declared that they use or want to start using React, over 70% with Vue, and over 30% with Angular – according to stateofjs.

If you work as a programmer, you certainly use various frameworks on a daily basis, and you are familiar with the subject of this article. However, it is possible that you are just starting to be interested in this topic or are looking for additional information that will bring you closer to the world of web development frameworks. If so, below is a list of the top web development frameworks that will rule 2021.

React JS – a JavaScript library considered as a web development framework

React JS is not a frameworkAs per its official website, It is a Javascript library for building user interfaces. Although it is not a framework, many developers consider it as a framework.

React was developed by Facebook and maintained and supported with the help of a community of individual developers and companies. Facebook and Instagram applications use this library, so it is understandable that React is that popular.

Fundamental concepts of React are declarative programming, component-based, Virtual DOM, and it could be used in NodeJS or mobile apps as React Native.

Thanks to React’s decorativeness, simple views will be rendered efficiently, i.e. only when the data changes. The process happens with Reconciliation. Moreover, it improves code predictability.

The component-based approach builds encapsulated components that manage their state and make a composition. It could be easily used by passing data through the application without involving the DOM.

According to hotframeworks.com, interest in React has been growing steadily since 2016.

Vue.js is one of the newest and most popular frameworks in web development.

It is known as a progressive framework for building user interfaces, which means that it could be used in small parts of a project without any problems.

Also, Vue.js could act as the primary and only front-end framework in web development. The framework has specific libraries that provide functionalities to build the application in just Vue.js.

Vue.js’ main concepts are the Component system, Two-way binding, and the same as React – Virtual DOM.

The component system is one of the main concepts in Vue.js. It provides the possibility to build large-scale applications with reusable, self-contained smaller components.

Two-way binding is supported, which reduces the complexity of keeping user input consistent with the application data model.

Unlucky, this framework is not supported by significant commercial communities like React or Angular. However, Vue.js’ popularity in web development is continually growing, so it will be a big chance for some more prominent companies like Google or Facebook.

According to 2019.stateofjs.com, the use of Vue.js among developers worldwide increased by as much as 33 percent from 2016 to 2019.

Angular – an application design framework and development platform

Angular is an application design framework and development platform for creating efficient SPAs. It is developed and maintained by Google.

The main concepts of Angular are components, templates, directives, and dependency injection.

Components are basic UI blocks of an Angular application. The application contains a tree of components. Also, a component is a subset of directives, which is always associated with a template. Only one component can be instantiated for a given element in a template.

The template is an HTML section that could be included as part of the browser’s displayed page.

Directives are markers on a DOM element (attribute, element name, CSS class, or comment) and tell Angular’s compiler to attach particular behavior to this element in DOM or even modify this element and its children in DOM.

Dependency Injection is a software design pattern in which one object receives other objects that it depends on. In Angular, an injector subsystem is responsible for creating components, resolving their dependencies, and providing them to other components if needed.

Angular occurs as AngularJS framework and Angular 2, but they are separate entities.

Express – a trendy framework used in back-end web development

Express is a prevalent framework used in back-end web development. The framework is a minimal and flexible Node.js web application framework that provides fundamental web application features without limiting Node.js.

The main features of the express are Routing, Middlewares, Templating, and much faster server-side development.

Because of the minimalism of express, some developers implemented many middleware packages that solve almost every web development problem.

Besides that, Express is based on Javascript and is chosen by many developers who want to keep their back-end applications at a high level of development.

Spring is the most popular back-end web application framework in Java.

This framework offers an extensive development and configuration pattern for the latest Java-based enterprise applications on different deployment platforms.

The framework is used not only in big complex projects in the biggest companies but also by individual programmers who want to create scalable web applications.

Spring has many useful features, but the most powerful are dependency injection, events, data binding, and resources.

Dependency injection is a pattern through which to implement IoC, where the control being inverted is the setting of the object’s dependencies.

Events in Spring are by default synchronous. It means that the listener can participate in the publisher’s transaction context.

Data Binding is useful for allowing user input to be dynamically bound to an application’s domain model.

Aspect-Oriented Programming (AOP) separates cross-cutting concerns from the business logic of the application. For example, it could be used in logging or security.

Django – a high-level Python Web framework

Django is an advanced web framework based on Python programming language that relies on fast development thanks to a clean and practical approach to the design. Its creators are experienced programmers who were aware of most of the most common problems related to web development, which is why the framework they created is a response to well-known needs. This allows you to save time and focus completely on writing the application.

Django is fast, fully loaded, reassuringly secure, incredibly versatile, and exceedingly scalable.

Companies and organizations of all sizes use Django in a variety of ways. This framework is useful when building science platforms, content management systems, or other applications.

Laravel is a PHP framework that became popular in a short period of time. It helps to create web applications more shortly and easily.

Laravel is extremely easy to use. Some amenities help develop apps from scratch with the database, security, and testing sections.

All that is needed to start is for the Composer to manage its dependencies. After a specific setting configuration, the application is ready to make some changes without implementing basic authentication or DB connection.

Laravel has many built features like authentication, template engine, database migration system, a command-line tool called Artisan.MVC architecture is also supported, which means that it helps separate business logic and presentation layers.

Rails – a web app development framework written in the Ruby programming language

Rails – a framework for web app development that uses a specific programming language – Ruby. It is designed to make programming web applications more accessible by making assumptions about what every developer needs to start. It allows developers to write less code while having more features than many other languages and frameworks.

Rails only have two major principles :

Also, Rails was implemented in MVC architecture, the most famous architecture in the back-end side of web development.

Flask – a micro-framework written in Python

Flask is written in Python and is known as a micro-framework because it does not need any specific tools and libraries. There is no database abstraction, verification of correctness of forms, or other components, but it operates extensions that could add some functionalities like Flask.

Flask aims to keep the core extensible but straightforward and does not force anything particular, so this framework could be everything you need and nothing you do not.

Besides Flask is a micro-framework, it is used in applications like LinkedIn and Pinterest.

Symfony – a PHP web application framework based on MVC architecture

Symfony is a PHP web application framework based on MVC architecture and a set of reusable PHP components and libraries.

This framework’s main advantages are that it is one of the fastest PHP frameworks and allows developers to code in the Object-Oriented Programming paradigm with the possibility to use sessions.

Additionally, Symfony uses a scaffolding method that builds applications using databases. This concept assumes that developers create specifications describing the structure of databases and compilers generate code that can read or update records in the database.

A crucial feature of Symfony is that it has a Bundle System. It provides a choice of specific bundles (known as plugins in other programming languages). Developers can implement fully functional web applications with an easy way to optimize the full implementation.

Summarizing

The above ranking is a subjective list of popular and most useful web development frameworks in our opinion. We hope that the information collected here has allowed you to broaden your knowledge about frameworks and will encourage you to get acquainted with some of them. The use of frameworks is the bread and butter of a web developer. The ability to use selected frameworks can significantly facilitate and speed up your work. Their popularity is growing year by year, and knowing some of them is a fundamental skill required of a developer. The efficient use of frameworks will allow you to improve your work on web development, stand out from most developers, and get more exciting employment and better earnings.

The State of Progressive Web App in 2020/2021

Is the Progressive Web App approach ready for production apps? It’s been a long time since Steve Jobs for the first time presented the vision of

The full Safari engine is inside the iPhone. And so, you can create amazing Web 2.0 and Ajax apps that look exactly the same and behave exactly like apps on the iPhone. And these apps can integrate perfectly with iPhone services. And guess what? There’s no SDK that you need.

During this time, a bunch of things changed in the web world, but the question is, is the Progressive Web App approach ready for production apps?

What is a Progressive Web App?

Before we start our journey through the benefits and drawbacks of using Progressive Web App in 2020/2021, I’d like to explain what I understand by PWA. I don’t want to copy/paste what Wiki says about PWA – you can read it – if you wish. PWA app is a web application that behaves almost exactly like a native app that you can download from the official market (either App Store or Play Store). From the user’s perspective, the differences shouldn’t be discernible.

A brief history of Progressive Web App

As I mentioned in the opening statement, Steve Jobs was probably one of the first people that presented that idea to a broader audience. The concept was introduced during the iPhone introduction in 2007 (what’s interesting Apple frozen a vision for ten years! – I’ll explain the reason in summary). Mozilla released Firefox OS in 2013. The system could run web apps as native apps on mobile devices via Gaia (an HTML5 layer and user-interface system). In December 2015, Mozilla announced that it would stop sales of Firefox OS smartphones. In 2015, Russell (Google) and Berriman coined the term “Progressive Web Apps”.

So as you can see, there is no one person, and there’s not even one company responsible for the project. As usual, the work of many amazing people and a simple coincidence allowed for the emergence of a new idea that is gaining more and more popularity.

The most important PWA features

Progressive Web App under the hood

One of the critical features of the PWA is a service worker. The worker is a small script that can handle offline mode to prior visited websites. Additionally, SW is responsible for delivering push messages. Behind the scenes browser runs it separately from the main thread, intercepting network requests, caching, and retrieving resources from the cache. Moreover, you can preview the service worker using, e.g. developer tools in Google Chrome.

Support for the selected feature

Based on the table below, you can notice that many things are already done, but many things need to be added to ensure that PWA is a fully cross-platform solution.

Progressive Web Apps cheat sheet
Progressive Web Apps cheat sheet

How can I transform my web app into a progressive one?

As always, it depends on how complicated your app is and what progressive features you are looking for. However, adding a web app manifest file should be the first step in the process. It’s the core technical requirement. This file provides information about your web application in JSON format. PWA manifest can contain details about web app name, description, background color, icon, or display mode (fullscreen/standalone/minimal-ui/browser).

How can I install a PWA app?

Unfortunately, there is no one answer to this question, and the way you can do that strictly depends on your operating system and browser. On the other hand, the whole process is quite simple and very similar between OSs/browsers.
In the case of iOS/Safari, the following steps should be done:

Open an application that supports PWA, for example, Twitter.com, and press the Share button.

PWA app installation step first
PWA app installation step first

Select “Add to Home Screen” from the menu.

PWA app installation step two
PWA app installation step two

Confirm the action by clicking “Add”.

PWA app installation step three
PWA app installation step three

An app icon should be added to the home screen.

PWA app installation step four
PWA app installation step four

Does Progressive Web App support desktop users as well?

Yes, it does! The most popular browsers/OSs support PWA features.

PWA vs. Native Application

What should I choose? – It’s one of the most frequently asked questions, and I agree that it’s always a tough decision, but it’s crucial from your product’s perspective. Before you start the implementation phase of your project, you must compare both technologies. Below I presented a few points that should be taken into consideration before you make a decision. Before challenging yourself with this difficult question, let’s highlight the most important factors.

Hardware features

I always recommend preparing a list of mobile features that are required to launch your product. The more hardware you want to use, the more you should go towards to native solution. The previous sentence doesn’t sound like a PWA recommendation. Still, the truth is how many apps use Bluetooth/gyroscope/accelerometer and others? Do you really need them in, as an example, an e-commerce app?

Cross-platform support

A lot of people think that PWA is the only cross-platform solution. You can create a single codebase and use it across different devices. Is it true that it’s impossible to develop a native app that would work on both Android and iOS devices? Of course, it’s not. You can take a look at Flutter or React Native solutions.

Performance

There are two areas where the native app takes over PWA:

Updates policy

In the case of a Progressive Web App, most logic is placed on the server-side, so you don’t need to engage additional layers, like marketplace. On the other hand, if you want to update a native app, the whole process is much more complicated and time-consuming because you not only need to update an app in the store, but also you must force users to download a new version.

Tech Stack

PWA uses well-known technologies in the web world. There are no limits. You can use React, Vue, Svelte, Angular, or any other library supported by browsers. Another benefit of using a progressive approach is writing your code in pure JS or any other superset of JavaScript – TypeScript, ReasonML, or Elm. Currently, JS is the only language that allows you to use the same technology on the back-end, web, and mobile (one language to rule them all!). On the contrary native Android app can be created in Java or Kotlin, but iOS supports only Swift.

The total cost of the product

Last but not least. People love cross-platform solutions, and the reason is straightforward. I can pay only once and have support for Android and iOS. It’s not always accurate, and one other important factor should be taken into account. Do you know that the app’s maintenance in many cases is much more expensive than the creation phase? Keep that in mind, when you need to make a decision. Maintaining a single application for multiple platforms can cost you more if you think about your project from a long-term perspective.

Is it possible to add a PWA application to the store?

In the third paragraph, I presented how we can install a Progressive Web Application on our phones. As you probably noticed from a technical perspective, it’s not rocket science – just a few clicks. From a marketing/sales perspective, it was a huge drawback – how many of our customers know about that hidden option in the browser? Fortunately, there is a way to publish the app in the official marketplaces.

Publishing Progressive Web App in the Google Play – Trusted Web Activity

In 2019 Google announced a new concept – Trusted Web Activity. TWA gives developers the possibility to publish web content in the Google Play store. Under the hood, TWA wraps the PWA application into an Android container (activity). TWA displays a full-screen Chrome browser inside of an Android app without browser UI elements, like a well-known URL bar. TWA gives you one more feature – transitions between the web and native content are between activities – so it lets you create an app that uses PWA features only for selected views. The whole process of creating a TWA application is clearly described in the official Google docs.


One more thing needs to be clarified – what does trusted mean in the context of TWA? Google decided to introduce a restriction that you must confirm that you are an owner of the website that you want to pack into TWA, and you can prove this by setting up Digital Asset Links. Fortunately, it’s nothing hard – the only thing you need to do is to upload a file to your server that points to your app and some data in your app that points to your website.

Publishing Progressive Web App in the App Store

In the case of Apple devices, it’s not so straightforward. In general, Apple’s review process is much more strict. But still, there is a way to wrap your PWA app into WebView using CordovaPWA Builder, or some other similar solution. It’s important to note here that officially there is a rule in the Apple Store Review Guidelines (4.2) that gives them the right to reject your submission.

Your app should include features, content, and UI that elevate it beyond a repackaged website.

On the other hand, there is a lot of stuff in the Apple Store that can be affected by this clause, but they are still there.

Publishing Progressive Web App in the Microsoft Store

In contrast to Apple, Microsoft informs about this new feature in their docs. The company also prepared an official tool to transform your PWA app into a native counterpart – PWA Builder. In the docs, they even listed the advantages of such a move:

PWA application is run in a lightweight native app wrapper, which is independent of the Microsoft Edge browser window.

What’s the state of PWA?

It seems to me there are a bunch of reasons that it never happens. I don’t want to paraphrase everything I’ve written in the “PWA vs. Native App” paragraph, but I need to highlight a couple of points. Native SDKs are optimized not only in performance but also in UX/UI way. Another aspect is that PWA was a buzzword in 2017/2018, but during this time, and it’s almost three years, many things have changed, but several features are still missing. Three years in the IT world is like a decade or two in other aspects of our life.

In my opinion, the progress of work is not satisfying. Mainly because we are talking about the biggest and the most powerful IT companies like Apple, Google, or Microsoft – randomly ordered? For me, the winner in hiding work on PWA improvements is an Apple company. On one side, they implement missing things. On the other hand, very frequently, the company doesn’t even inform developers about new options. It’s easy to guess what is the root cause of this strategy – money.  According to CNBC analysis, Apple’s App Store grossed around $50 billion in 2019. That means that the App Store alone would be no. 64 on the Fortune 500 (ahead of Nike or Coca-Cola). Nevertheless, with all these aspects, I’d like to emphasize that PWA is an excellent choice for many businesses, and frequently it’s the first and the easiest step to the mobile world for your app.

iOS development SwiftUI experiment – building custom chart part 2

Here we are, in the second part of our iOS development SwiftUI experiment! In the first part, you have created a basic black&white chart with some nice curves. You are going to spice your work up and make it pleasing to the eye. It’s ANIMATIONS & GRADIENTS time! ????

How to add animations & gradients for your iOS app with SwiftUI

To kick-off building new functionalities, you have to do a small refactor to keep the project clean. SwiftUI is heavily forcing view structure to be composed of smaller pieces, so let’s follow this guideline and move your grid to a completely separate view.

struct GridView: View {
    let xStepsCount: Int
    let yStepsCount: Int
    
    var body: some View {
        GeometryReader { geometry in
            Path { path in
                let xStepWidth = geometry.size.width / CGFloat(self.xStepsCount)  
                let yStepWidth = geometry.size.height / CGFloat(self.yStepsCount)      
                
                // Y axis lines
                (1...self.yStepsCount).forEach { index in
                    let y = CGFloat(index) * yStepWidth
                    path.move(to: .init(x: 0, y: y))
                    path.addLine(to: .init(x: geometry.size.width, y: y))
                }
                
                // X axis lines
                (1...self.xStepsCount).forEach { index in
                    let x = CGFloat(index) * xStepWidth
                    path.move(to: .init(x: x, y: 0))
                    path.addLine(to: .init(x: x, y: geometry.size.height))
                }
            }
            .stroke(Color.gray)
        }
    }
}

OK, it’s time for real work. You would like to animate the drawing of the chart path. When the view appears it should nicely slide on the screen. You can use the trim(from: to:) method to achieve this. Let’s make some adjustments in the chartBody:

private var chartBody: some View {
        GeometryReader { geometry in
            Path { path in
                path.move(to: .init(x: 0, y: geometry.size.height))
                
                var previousPoint = Point(x: 0, y: geometry.size.height)
                
                self.data.forEach { point in
                    let x = (point.x / self.maxXValue) * geometry.size.width
                    let y = geometry.size.height - (point.y / self.maxYValue) * geometry.size.height   
                    
                    let deltaX = x - previousPoint.x
                    let curveXOffset = deltaX * self.lineRadius
                    
                    path.addCurve(to: .init(x: x, y: y),
                                  control1: .init(x: previousPoint.x + curveXOffset,
                                                  y: previousPoint.y),
                                  control2: .init(x: x - curveXOffset,
                                                  y: y ))
                    
                    previousPoint = .init(x: x, y: y)
                }
            }
            .trim(from: 0, to: self.isPresented ? 1 : 0)
            .stroke(
                Color.black,
                style: StrokeStyle(lineWidth: 3)
            )
            .animation(.easeInOut(duration: 0.8))
        }
        .onAppear {
            self.isPresented = true
        }
    }

There is not much to explain. Just trim a path from 0 to 1 in specified animation duration (in this case 0.8s).

To make it work you need @State property which will maintain the animation

@State private var isPresented: Bool = false

Wow! That was super easy and the outcome is awesome! ????

But you can’t leave the chart black&white, how about adding some gradients? Let’s start with the chart line. To fill it in with gradient just change stroke’s Color.black

.stroke(
  LinearGradient(gradient: Gradient(colors: [.primaryGradient, .secondaryGradient]),     
                 startPoint: .leading,
                 endPoint: .trailing),
  style: StrokeStyle(lineWidth: 3)
)

.primaryGradient, .secondaryGradient are my custom colors added to the Color extension, they can be whatever you want, just use your imagination.

You can do even better by adding the background to the chart. To do so you can draw a closed path below the actual chart line and fill it with gradients. But first, you have to abstract away a path drawing.

struct LineChartProvider {
    let data: [Point]
    var lineRadius: CGFloat = 0.5
    
    private var maxYValue: CGFloat {
        data.max { $0.y < $1.y }?.y ?? 0
    }
    
    private var maxXValue: CGFloat {
        data.max { $0.x < $1.x }?.x ?? 0
    }
    
    func path(for geometry: GeometryProxy) -> Path {
        Path { path in
            path.move(to: .init(x: 0, y: geometry.size.height))
            
            drawData(data, path: &path, size: geometry.size)
        }
    }
    
    func closedPath(for geometry: GeometryProxy) -> Path {
        Path { path in
            path.move(to: .init(x: 0, y: geometry.size.height))
            drawData(data, path: &path, size: geometry.size)
            
            path.addLine(to: .init(x: geometry.size.width, y: geometry.size.height))               
            path.closeSubpath()
        }
    }
    
    private func drawData(_ data: [Point], path: inout Path, size: CGSize) {
        var previousPoint = Point(x: 0, y: size.height)
        
        self.data.forEach { point in
            let x = (point.x / self.maxXValue) * size.width
            let y = size.height - (point.y / self.maxYValue) * size.height
            
            let deltaX = x - previousPoint.x
            let curveXOffset = deltaX * self.lineRadius
            
            path.addCurve(to: .init(x: x, y: y),
                          control1: .init(x: previousPoint.x + curveXOffset, y: previousPoint.y),
                          control2: .init(x: x - curveXOffset, y: y ))
            
            previousPoint = .init(x: x, y: y)
        }
    }
}

So, the drawing logic is now part of LineChartProvider. It has two accessible methods: pathand closedPath. The only difference between them is one additional step for closedPath which makes it a closed shape (this lets us fill it properly with gradient). The private drawData method is an actual drawing part of the provider, it’s abstracted away to easy reuse between the path and closedPath methods.

Also, you have moved some of the supporting computed properties from ChartView to LineChartProvider.

With those improvements ready, you can use it in the chart:

private var chartBody: some View {
        let pathProvider = LineChartProvider(data: data, lineRadius: lineRadius)
        return GeometryReader { geometry in
            ZStack {
                pathProvider.closedPath(for: geometry)
                    .fill(
                        LinearGradient(gradient: Gradient(colors: [.white, Color.primaryGradient.opacity(0.6)]),    
                                       startPoint: .bottom,
                                       endPoint: .top)
                    )
      
                pathProvider.path(for: geometry)
                    .trim(from: 0, to: self.isPresented ? 1 : 0)
                    .stroke(
                        LinearGradient(gradient: Gradient(colors: [.primaryGradient, .secondaryGradient]),
                                       startPoint: .leading,
                                       endPoint: .trailing),
                        style: StrokeStyle(lineWidth: 3)
                    )
                    .animation(.easeInOut(duration: 0.8))
            }
            .onAppear {
                self.isPresented = true
            }
        }
}

Neat! But you can do even better. So far the animation doesn’t look natural. You have to add animation to the background as well!

ZStack {
    // Background
    pathProvider.closedPath(for: geometry)
      .fill(
        LinearGradient(gradient: Gradient(colors: [.white, Color.primaryGradient.opacity(0.6)]), 
                       startPoint: .bottom,
                       endPoint: .top)
      )
      .opacity(self.isPresented ? 1 : 0)
      .animation(Animation.easeInOut(duration: 1).delay(0.6))
                
      // Chart
      pathProvider.path(for: geometry)
        .trim(from: 0, to: self.isPresented ? 1 : 0)
        .stroke(
          LinearGradient(gradient: Gradient(colors: [.primaryGradient, .secondaryGradient]),
                         startPoint: .leading,
                         endPoint: .trailing),
          style: StrokeStyle(lineWidth: 3)
        )
        .animation(Animation.easeInOut(duration: 0.8).delay(0.2))
}

This is way better! Manipulate the opacity of the background to fade it in nicely. Moreover, you are using the delay method to chain animations.

In the beginning, it seemed very complicated and complex but it quickly turned out to be easy peasy thanks to the SwiftUI magic. Although I am satisfied with the overall outcome, there are plenty of things that can be improved. It was the last part of the iOS development SwiftUI experiment, but you have tons of other possibilities to discover. Good luck.

iOS development SwiftUI experiment – building custom chart

SwiftUI is the future of iOS development, right? We are all excited about how it will influence our mobile development process. At the same time, we are wondering if SwiftUI is ready to shine right now. We are going to find out! In the upcoming blog posts, we’ll try to build a completely custom line chart with extraordinary animations and Hollywood-like effects  This part is all about building a simple chart with a background grid.

How to build a new chart for your iOS app

But let’s start simple. You need to define some kind of data model for our new chart. Let’s start with a raw Point model, nothing too sophisticated just simple X/Y coordinates. You can extend its capabilities in the future if needed.

struct Point {
	let x: CGFloat
	let y: CGFloat
}

Use CGFloat instead of Double to get rid of conversion (the drawing system of SwiftUI is based on CGFloat).

You need some temporary mock data as well:

let data: [Point] = [

    .init(x: 1, y: 5),

    .init(x: 2, y: 4),

    .init(x: 3, y: 15),

    .init(x: 4, y: 6),

    .init(x: 5, y: 9),

    .init(x: 6, y: 12),

    .init(x: 7, y: 14),

    .init(x: 8, y: 11)

]
struct ChartView: View {
    let xStepValue: CGFloat
    let yStepValue: CGFloat
    let data: [Point]
    
    private var maxYValue: CGFloat {
        data.max { $0.y < $1.y }?.y ?? 0
    }
    
    private var maxXValue: CGFloat {
        data.max { $0.x < $1.x }?.x ?? 0
    }
    
    private var xStepsCount: Int {
        Int(self.maxXValue / self.xStepValue)    
    }
    
    private var yStepsCount: Int {
        Int(self.maxYValue / self.yStepValue)
    }
    
    var body: some View {
    
    }
}

We initialize our ChartView with an array of Point models and values of the X/Y axis step. Add some computed properties which will be handy in the grid/chart calculations. Finally, let’s get our hands dirty in the actual drawing. You have to calculate line positions relative to view size. But how do you get the size of view in SwiftUI? Fortunately, here comes a GeometryReader to the rescueIt is a container view that gives you access to information about its size and coordinates. You are going to use it to calculate the position of the grid lines.

var body: some View {
    ZStack {
        gridBody
    }
}
    
private var gridBody: some View {
        GeometryReader { geometry in
            Path { path in
                let xStepWidth = geometry.size.width / CGFloat(self.xStepsCount)     
                let yStepWidth = geometry.size.height / CGFloat(self.yStepsCount)     
                
                // Y axis lines
                (1...self.yStepsCount).forEach { index in
                    let y = CGFloat(index) * yStepWidth
                    path.move(to: .init(x: 0, y: y))
                    path.addLine(to: .init(x: geometry.size.width, y: y))
                }
                
                // X axis lines
                (1...self.xStepsCount).forEach { index in
                    let x = CGFloat(index) * xStepWidth
                    path.move(to: .init(x: x, y: 0))
                    path.addLine(to: .init(x: x, y: geometry.size.height))
                }
          }
          .stroke(Color.gray)
      }
}

Pretty straightforward, calculate X/Y step width then iterate over steps count drawing vertical/horizontal lines. It’s a bit better but still, there is no chart at all  Let’s add one more variable:

private var chartBody: some View {
        GeometryReader { geometry in
            Path { path in
                path.move(to: .init(x: 0, y: geometry.size.height))
                self.data.forEach { point in
                    let x = (point.x / self.maxXValue) * geometry.size.width
                    let y = geometry.size.height - (point.y / self.maxYValue) * geometry.size.height    
                    
                    path.addLine(to: .init(x: x, y: y))
                }
            }
            .stroke(
                Color.black,
                style: StrokeStyle(lineWidth: 3)
            )
      }
}
SwiftUI chart
Your first very own chart!

Here it is! Your first very own chart! Nothing too fancy, once more you have used GeometryReader to get the size of the view. With the size in the hand, you have to calculate coordinates of the next point. To do so you have to get a proportion of the x/y value of the point to the max values. The result is a part of the whole available width/height. Keep in mind that .zero point of view is in the top left corner while you are drawing from the bottom left corner. So to get the correct value of y you have to subtract the result from the view height. Then you simply draw a line to the calculated point.

How to modify your iOS app new chart with SwiftUI

Your chart is almost ready but it looks a bit too… sharp.

What about making it a bit more curved? Let’s modify the chartBody like this:

private var chartBody: some View {
        GeometryReader { geometry in
            Path { path in
                path.move(to: .init(x: 0, y: geometry.size.height))
                // 1
                var previousPoint = Point(x: 0, y: geometry.size.height)
                
                self.data.forEach { point in
                    let x = (point.x / self.maxXValue) * geometry.size.width
                    let y = geometry.size.height - (point.y / self.maxYValue) * geometry.size.height
                    
                    // 2
                    let deltaX = x - previousPoint.x
                    let curveXOffset = deltaX * self.lineRadius
                    
                    // 3
                    path.addCurve(to: .init(x: x, y: y),
                                  control1: .init(x: previousPoint.x + curveXOffset, y: previousPoint.y),   
                                  control2: .init(x: x - curveXOffset, y: y ))
                    
                    previousPoint = .init(x: x, y: y)
                }

Here’s what is happening. First of all, you have to store the previous Point which will be used to calculate the position of curve points.

Now you can calculate X delta between current and previous Point. To get an offset value for curve points you have to multiply the delta with a new property lineRadius. It tells how curved the chart should be. The lineRadius has to be a value within 0…1 range (where 0 means no curve at all). Finally, instead of addLine use the addCurve function. This lets you add two curves on the line between two points. We can achieve that by specifying two control points. The first one is moved to the right side by the calculated offset and the second one to the left side. This gives us a nice effect of a curved line ⎰.

SwiftUI chart 2
Curved line

Now it’s way better! I can’t wait to build the rest of the functionalities on top of it. It’s a great start but there is a lot of work ahead of you. In the next part of the iOS development SwiftUI experiment, you’ll try to add some gradients and transition animation.

I hope you enjoy the post. Thanks for reading and see you soon!