Quantcast
Channel: Envato Tuts+ Code
Viewing all 5166 articles
Browse latest View live

Kotlin From Scratch: Abstract Classes, Interfaces, Inheritance, and Type Alias

$
0
0

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.  

In the previous article, you learned more about Kotlin properties such as late-initialization, extension, and inline properties. Not only that, you also learned about advanced classes such as data, enum, nested, and sealed classes in Kotlin. 

In this post, you'll continue to learn about object-oriented programming in Kotlin by learning about abstract classes, interfaces, and inheritance. For a bonus, you'll also learn about type aliases. 

1. Abstract Classes

Kotlin supports abstract classes—just like Java, these are classes which you never intend to create objects from. An abstract class is incomplete or useless without some concrete (non-abstract) subclasses, from which you can instantiate objects. A concrete subclass of an abstract class implements all the methods and properties defined in the abstract class—otherwise that subclass is also an abstract class!

We create an abstract class with the abstract modifier (similar to Java). 

Note that not all members have to be abstract. In other words, we can have method default implementation in an abstract class. 

Here we created the non-abstract function fullName() in an abstract class Employee. Concrete classes (subclasses of the abstract class) can override an abstract method's default implementation—but only if the method has the open modifier specified (you will learn more about this shortly). 

We can also store state in abstract classes. 

Even if the abstract class doesn't define any methods, we need to create a subclass before we can instantiate it, as in the example below.

Our Programmer class extends the Employee abstract class. In Kotlin we use a single colon character (:) instead of the Java extends keyword to extend a class or implement an interface. 

We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).  

One thing that might surprise you is that we have the ability to override a val (immutable) property with var (mutable). 

Make sure you use this functionality wisely! Be aware that we can't do the reverse—override a var property with val

2. Interfaces

An interface is simply a collection of related methods that typically enable you to tell objects what to do and also how to do it by default. (Default methods in interfaces are a new feature added to Java 8.) In other words, an interface is a contract that implementing classes must abide by. 

An interface is defined using the interface keyword in Kotlin (similar to Java). 

In the code above, we've declared a StudentRepository interface. This interface contains two abstract methods: getById() and getResultsById(). Note that including the abstract keyword is redundant in an interface method because they are already abstract implicitly. 

An interface is useless without one or more implementers—so let's create a class that will implement this interface. 

Here we created a class StudentLocalDataSource that implements the StudentRepository interface.

We use the override modifier to label the methods and properties we want to redefine from the interface or superclass—this is similar to the @Override annotation in Java.

Note the following additional rules of interfaces in Kotlin:

  • A class can implement as many interfaces as you want, but it can only extend a single class (similar to Java).
  • The override modifier is compulsory in Kotlin—unlike in Java. 
  • Along with methods, we can also declare properties in a Kotlin interface. 
  • A Kotlin interface method can have a default implementation (similar to Java 8). 

Let's see an example of an interface method with a default implementation.

In the preceding code, we added a new method delete() with a default implementation (though I did not add the actual implementation code for demonstration purposes). 

We also have the freedom to override the default implementation if we want.

As stated, a Kotlin interface can have properties—but note that it can't maintain state. (However, remember abstract classes can maintain state.) So the following interface definition with a property declaration will work.

But if we try to add some state to the interface by assigning a value to the property, it will not work.

However, an interface property in Kotlin can have getter and setter methods (though only the latter if the property is mutable). Note also that property in an interface cannot have a backing field. 

We can also override an interface property if you want, so as to redefine it. 

Let's look at a case where we have a class implementing multiple interfaces with the same method signature. How does the class decide which interface method to call?

Here we have two interfaces that have a method with the same signature funD(). Let's create a class that implements these two interfaces and overrides the funD() method. 

The compiler is confused about calling the super.funD() method because the two interfaces that the class implements have the same method signature. 

To solve this problem, we wrap the interface name for which we want to call the method in angle brackets <InterfaceName>. (IntelliJ IDEA or Android Studio will give you a hint about solving this issue when it crops up.)

Here we are going to call the funD()  method of InterfaceA. Problem solved! 

3. Inheritance

A new class (subclass) is created by acquiring an existing class's (superclass) members and perhaps redefining their default implementation. This mechanism is known as inheritance in object-oriented programming (OOP). One of the things that make Kotlin so awesome is that it encompasses both the OOP and functional programming paradigms—all in one language.

The base class for all classes in Kotlin is Any

The Any type is equivalent to the Object type we have in Java. 

The Any type contains the following members: equals(), hashcode(), and also toString() methods (similar to Java). 

Our classes don't need to explicitly extend this type. If you don't explicitly specify which class a new class extends, the class extends Any implicitly. For this reason, you typically don't need to include : Any in your code—we do so in the code above for demonstration purposes. 

 Let's now look into creating classes in Kotlin with inheritance in mind. 

In the code above, the GraduateStudent class extends the superclass Student. But this code won't compile. Why? Because classes and methods are final by default in Kotlin. In other words, they cannot be extended by default—unlike in Java where classes and methods are open by default. 

Software engineering best practice recommends that you to begin making your classes and methods final by default—i.e. if they aren't specifically intended to be redefined or overridden in subclasses. The Kotlin team (JetBrains) applied this coding philosophy and many more development best practices in developing this modern language. 

For us to allow subclasses to be created from a superclass, we have to explicitly mark the superclass with the open modifier. This modifier also applies to any superclass property or method that should be overridden by subclasses.

We simply put the open modifier before the class keyword. We have now instructed the compiler to allow our Student class to be open for extension. 

As stated earlier, members of a Kotlin class are also final by default. 

In the preceding code, we marked the schoolFees function as open—so that subclasses can override it. 

Here, the open schoolFees function from the superclass Student is overridden by the GraduateStudent class—by adding the override modifier before the fun keyword. Note that if you override a member of a superclass or interface, the overriding member will also be open by default, as in the example below:

Even though we didn't mark the schoolFees() method in the GraduateStudent class with the open modifier, we can still override it—as we did in the ComputerScienceStudent class. For us to prevent this, we have to mark the overriding member as final

Remember that we can add new functionality to a class—even if it's final—by the use of extension functions in Kotlin. For a refresher on extension functions, check out my Advanced Functions in Kotlin post. Also, if you need a refresher on how to give even a final class new properties without inheriting from it, read the section on extension Properties in my Advanced Properties and Classes post. 

If our superclass has a primary constructor like this:

Then any subclass has to call the primary constructor of the superclass. 

We can simply create an object of the GraduateStudent class as usual:

If the subclass wants to call the superclass constructor from its secondary constructor, we use the super keyword (similar to how superclass constructors are invoked in Java). 

If you need a refresher on class constructors in Kotlin, kindly visit my Classes and Objects post. 

4. Bonus: Type Alias

Another awesome thing we can do in Kotlin is to give a type an alias. 

Let's see an example.

In the class above, we can assign the String and Int types for the Person properties aliases using the typealias modifier in Kotlin. This modifier is used to create an alias of any type in Kotlin—including the ones you have created. 

As you can see, we have created an alias Name and Age for both the String and Int types respectively. We have now replaced the firstName and lastName property type to our alias Name—and also Int type to Age alias. Note that we didn't create any new types—we instead created an alias for the types. 

These can be handy when you want to provide a better meaning or semantic to types in your Kotlin codebase. So use them wisely! 

Conclusion

In this tutorial, you learned more about object-oriented programming in Kotlin. We covered the following:

  • abstract classes
  • interfaces 
  • inheritance
  • type alias

If you have been learning Kotlin through our Kotlin From Scratch series, make sure you have been typing the code you see and running it on your IDE. One great tip to really grasp a new programming language (or any programming concept) you're learning is to make sure you don't just only read the learning resource or guide, but also type the actual code and run it!

In the next tutorial in the Kotlin From Scratch series, you'll be introduced to exception handling in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts!



How You Can Support LGBTQ Youth as a Mobile App Developer

$
0
0

October 19th is Spirit Day, a day for supporting LGBTQ youth and speaking out against the bullying and harassment they too often face. Here at Envato Tuts+, we're proud to stand against bullying and discrimination of any kind, so we're going purple to show we stand with lesbian, gay, bisexual, transsexual and queer youth.

In this post, we'll take a quick look at some of the ways we can support LGBTQ youth as app developers.

Avoid Coding Assumptions About Your Users' Identities

It's really important that we as developers avoid coding assumptions about gender and sexual identity into our apps. Anyone in a gender or sexual minority will understand this point immediately, but for others it can be easy to let gender assumptions creep into our code without even realizing it.

Gender Mutability

In my role as editor of mobile content for Envato Tuts+, I see assumptions like this crop up occasionally when reviewing code snippets and examples. For instance, in the Swift language, you might model a person as follows.

Pretty straightforward, but there's one problem: the gender property of Person is immutable and set in the class initializer. But real people can change the gender they are identified with! 

This is a somewhat artificial example, and of course there could be provisions in other parts of the codebase or system for users to change their gender, but it demonstrates how gender assumptions can cause problems. Imagine if the assumption that gender is unchangeable were coded into a university enrollment or driver's license database. It would lead to a system that was unable to accurately model the people it represents!

Remember, in real life, gender is a var (mutable).

Modeling Gender

Similarly, how should we model the Gender type? In the past, a lot of devs and database designers have represented gender as an enum. Again, in Swift, we might have:

I'm sure you see the problem: a binary choice between "male" and "female" doesn't encompass the range of gender identities held by app users today. If you make your users choose between one of these alternatives, you will be sure to alienate a lot of them. 

The online dating app OkCupid had this problem in its early years, causing many potential users to be excluded—to be unable or feel uncomfortable to use the service. In 2014 though, OkCupid (along with social media giant Facebook) overhauled their gender and sexual orientation model.

OkCupid gender selection

OkCupid's is an example of a well-thought-out system for modeling gender and sexual orientation, and it's worth referencing if you need to provide for gender in your app. 

In Swift, then, we might implement a very inclusive Gender type as follows:

This would let users select from a broad range of established gender identities, choose multiple simultaneous identities, and even supply their own if the supplied options were not enough.

Non-Traditional Families

For a final example, suppose that we had the following properties in the Person class:

This assumes that a person has one mother and one father. For many people, raised in non-traditional families, that is simply not the case. For instance, I have a friend who was raised in a house with five mothers. How lucky for her! 

A better way to model parent relations might be:

Inclusive Apps

As mobile apps and software in general become more and more central to people's lives, we have a responsibility as developers to make sure that our apps are as inclusive as possible. If we make assumptions about gender or sexual identity, we exclude some potential users of our apps or limit their opportunity to use the service our apps provide. 

The same goes for other assumptions about users. Check out this great list of Falsehoods Programmers Believe About Names.

Tell Stories and Explore LGBTQ Themes in Your Game

If you are a mobile game developer, you have a great opportunity to support the LGBTQ community by including diverse characters in your game, and by allowing users to use their preferred gender identity and sexual orientation in the game.

For an overview of ways that LGBTQ issues can be and have been addressed in games, check out Michael James Williams' Spirit Day 2015 post.

Write an App to Support LGBTQ Youth

Whatever issue you are passionate about, you have a real opportunity to make a difference by developing a custom app to support that cause. Even if you're just learning to code apps or only setting out in your career, this can be a great way to get started. Let's face it, your app has a much better chance of getting noticed if it is connected to a social issue that people care about. 

Here is a list of some apps that have been created to help LGBTQ youth and other victims of bullying. Be inspired!

Verena

The title of this app means "protector", and it is intended to help its users find protection in times of crisis: directing them to police stations, hospitals, shelters and other places of refuge, as well as notifying a designated list of contacts in case of emergency.

Verena app

Verena was created by 15-year-old Amanda Southworth to support her friends in the LGBTQ community. One clever feature is that the app has an incognito mode, disguised to look like a homework helper. That way, youth who might not be able to be open about their sexual identity are safe to have and use the app on their phone.

You're Accepted

Coming out is an extremely difficult and even dangerous time for many LGBTQ youth. Many teens have faced cruel bullying, abuse, or disownment and expulsion from their family home. The creators of the You're Accepted app are trying to make this transition easier by helping users build a network of safety and support before coming out.

You're Accepted is a message platform that allows LGBTI youth to tell their friends their sexuality or gender identity, anonymously. You can see their responses and then decide who to tell. — You're Accepted
Youre Accepted app

The creators of the app believe that no one should live in fear of being themselves and have written this app to help counter online discrimination against LGBTQ youth.

PRIDE Study

This app was created by doctors and scientists at the University of California in San Francisco to investigate connections between being a gender or sexual minority and long-term health outcomes.

The PRIDE Study deeply explores how the experience of being LGBTQ is related to all aspects of health and life. — PRIDE Study

This will help doctors, governments and community groups understand how to support LGBTQ health.

The PRIDE Study is built on Apple's ResearchKit framework, announced at Apple's Spring Forward event in 2015. This technology allows researchers to easily enroll and collect data from participants in large-scale, longitudinal studies—studies that collect health information over time.

Know Bullying

While it's not a problem unique to LGBTQ youth, all too many LGBTQ youth experience some sort of bullying. This experience can be deeply painful and has driven many young people to depression, self-harm, and even suicide. The app is a tool to help parents and teachers check in with children and detect the signs of bullying. Some of the features of the app include:

  • tips about the kinds of bullying experienced in specific age groups
  • warning signs that a child might be bullied or be engaged in bullying
  • conversation starters to help engage with children
Know Bullying conversation starters

Know Bullying was created by the US Substance Abuse and Mental Health Services Administration (SAMHSA), and it's packed with information for parents and educators to help them detect and prevent bullying.

Quist

Quist, short for "quistory" or "queer history", was created to celebrate and educate young people in the history of the struggle for LGBTQ rights. Every day, the app shows users a collection of events from that day in history so that users can see:

How far the LGBTQ community has come over time—how we have been treated, how we have reacted, how our allies have supported us, and how others have worked vehemently to stop the progress. — Quist 

With this youth-friendly app, the Quist team is trying to educate and inform the world about the deep history of LGBTQ communities, and to provide support to individuals by showing how others throughout history have shared their struggle.

Quist app

Circle of 6

Circle of 6 is an easy-to-use tool designed to help teenagers and college students prevent sexual violence and get out of bad situations.

Need help getting home? Need an interruption? Two taps lets your circle know where you are and how they can help. Circle of 6 app for iPhone and Android makes it quick and easy to reach the 6 people you choose. — Circle of 6

The Circle of 6 app was created for the 2011 Apps Against Abuse White House challenge. And won! With more than 150,000 students in 32 countries, the app has received press from around the world. 

The app creators say that they are inspired to make the world a better place with "technology that enhances friendship and trust". 

Conclusion

Bullying of LGBTQ youth is a huge problem, with 85% of LGBTQ youth reporting having been verbally harassed, 48% reporting experiencing cyberbullying, and 13% reporting having been physically assaulted—all because of their gender identity. 

Spirit Day gives us a chance to support the LGBTQ community and show that we are against bullying. You can help out by wearing purple today and talking to your friends or young people in your life. As a mobile app developer, though, you have a special opportunity to help—by ensuring your apps are inclusive and perhaps even by creating an app to help youth at risk of bullying!

Essential JavaScript Libraries and Frameworks You Should Know About

$
0
0

JavaScript has been around for 20+ years, and it's one of those languages that never stop evolving. The language has been experiencing a fast-paced growth recently that makes me wonder whether the modern front-end JavaScript technologies that are well known today will be relevant a couple of years later. 

Nevertheless, it's important to be ahead of the game by working with the latest tools and frameworks for a better development workflow. This article explores various JavaScript libraries, frameworks, and tools that you should consider learning right now.

Introduction

The JavaScript environment has grown huge. It has its own ecosystem of libraries, frameworks, tools, package managers and new languages that compile down to JavaScript. Interestingly, npm, which is the de facto package manager for JavaScript, is also the largest software registry in the world. Here is an excerpt from a post published on Linux.com back in January 2017.

At over 350,000 packages, the npm registry contains more than double the next most populated package registry (which is the Apache Maven repository). In fact, it is currently the largest package registry in the world.

Fast forward eight months, and there are currently about 500,000 packages in the npm registry. That's a massive growth compared to other package repositories. 

A comparison of different package registries based on number of modules
Source: ModuleCounts.com

As a front-end JavaScript developer, it's important to keep up with the modern JavaScript tools and libraries. When a technology becomes popular, demand for it is high, which in turn means more coding jobs that pay the highest salary in the industry. So I've assembled a list of the popular JavaScript technologies that I think you should be aware of. 

Libraries

A library is a reusable piece of code that offers certain functionality. It is a collection of functions, objects, and classes that you can use in your application. A library abstracts different layers so that you don't have to be concerned about their implementation details. 

You can call a library function and pass it some parameters, and the library executes it and returns the control back to you. However, it doesn't place any structural constraints that restrict how you use the library. Popular JavaScript libraries include:

React

React is a JavaScript library built by the developers of Facebook and Instagram. React was voted as the most-loved technology among developers, according to the Stack Overflow Survey 2017. React also holds the credit for being the most popular JavaScript project based on GitHub star count. 

So why is React getting all the attention? With React, it is possible to create an interactive UI using a declarative approach where you can control the state of the application by saying "the view should look like this". It uses a component-based model where the components are reusable UI elements and each component has its own state.

React a JavaScript library for building interactive views

React uses a Virtual DOM so that you don't have to be concerned about directly manipulating the DOM. Other notable features of React include one-way data flow, optional JSX syntax, and a command-line tool for creating a React project with zero build configuration. 

If you believe that React is the next best thing and would like to learn React, check out our React Crash Course for Beginners tutorial series.

jQuery

jQuery is a library that made JavaScript more approachable and DOM manipulation easier than before. jQuery's gentle learning curve and easy syntax gave rise to a generation of new client-side developers. A few years back, jQuery was considered a solid solution for building robust websites with cross-browser support. jQuery's core features such as DOM manipulation based on CSS selectors, event handling, and making AJAX calls fueled its popularity. 

jQuery library for DOM manipulation using JavaScript

However, things have changed, and the JavaScript environment has steadily evolved. Some of jQuery's features have been incorporated into the newer ECMAScript specification. Moreover, the new libraries and frameworks in use today have a native way of binding the DOM, and hence plain DOM manipulation techniques are not required anymore. jQuery's popularity is on the decline, but I don't see it disappearing anytime soon.

D3: Data-Driven Documents

D3 (or D3.js) is a powerful JavaScript library for producing interactive visualizations using web standards such as SVG, HTML, and CSS. Unlike other visualization libraries, D3 offers better control over the final visual result. 

D3 works by binding the data to the DOM and then making the transformation to the document. It also has an ecosystem of its own, which consists of plugins and libraries that extend its basic functionality. The library has been around since 2011, and it has tons of documentation and tutorials that can help you get started. 

D3 interactive visualization for the web

If you are looking to create simple visualizations without investing too much time in it, you should check out Chart.js. We have an introductory series on Chart.js that covers most of the visualizations that you can create with Chart.js

Frameworks

A framework has an architecture that dictates the flow of control in your application. The framework describes the skeleton and tells you how everything should be organized. The basic functionality required to get the application up and running is also provided to you. Moreover, you are bound to follow the framework's design principles and patterns. The difference between a framework and library is that you call a library, whereas the framework calls you. 

A framework often comprises of many libraries and has a higher level of abstraction. Functionality such as event handling, making AJAX calls, template and data binding, and testing are built into the framework.  

Angular

AngularJS was once the most popular JavaScript technology among front-end developers. It was backed by Google and a community of individuals and corporations. Despite the popularity, AngularJS had its own share of flaws. The Angular team spent two years working on a newer version of Angular, which was finally released in September 2016. 

Angular framework for mobile and desktop

The Angular 2 release was a ground-up rewrite of AngularJS. Some of the features of Angular 2 include:

  • TypeScript over JavaScript as the default language
  • component-based architecture
  • improved performance on both mobile and web platforms. 
  • better tooling and scaffolding options

However, upgrading from Angular 1.x to Angular 2 is expensive because Angular 2 is an entirely different beast. That's one of the reasons why Angular 2 hasn't experienced the same adoption rate as that of its predecessor. But Angular and AngularJS continue to be among the most commonly used technologies according to Stack Overflow (2017). The Angular project has about 28,000 stars on GitHub.

Vue.js

Vue.js is a lightweight JavaScript framework that has been trending this year. It is the most popular JavaScript framework on GitHub in terms of the GitHub star count. Vue claims to be a less opinionated framework and thus easy for developers to catch up with. Vue's HTML-based template syntax binds the rendered DOM to the instance data. 

Vuejs The progressive JavaScript framework

The framework offers a React-like experience with its Virtual DOM and reusable components that you can use to create both widgets and entire web applications. Moreover, you can also use the JSX syntax to write the render functions directly.  When the state changes, Vue.js uses a reactivity system to determine what has changed and rerenders the minimal number of components. Vue.js also supports the integration of other libraries into the framework without much hassle.

Ember.js

Ember.js is a front-end framework based on the  Model-View-ViewModel (MVVM) pattern. It follows the convention over configuration approach which is popular among server-side side frameworks like Ruby on Rails and Laravel. Ember.js incorporates common idioms and best practices into the framework so that you can get an application up and running without much effort. 

Emberjs a framwork for creating ambitious web apps

The Ember stack usually comprises:

  • Ember CLI: Provides basic scaffolding options and supports hundreds of add-ons.
  • Ember Data: A data persistence library that can be configured to work with any server back end.
  • Ember Inspector: An extension available for Chrome and Firefox.
  • Liquid Fire:  An add-on for transitions and animations.

Tools

A tool is a collection of routines that help you in the development process. Unlike a library, a tool usually executes a task on the client code. It takes your code as input, performs a task on it, and then returns an output. The commonly used tools include transpilers and build tools, asset minifiers, module bundlers, and scaffolding tools. 

Tools: General-Purpose Task Runners

General-purpose task runners are the tools used to automate certain repetitive tasks. The popular general-purpose task runners include:

Gulp 

Gulp is a JavaScript toolkit used as a task runner and as a build system in web development. Compilation, code minification, image optimization, unit testing, linting etc. are repetitive tasks that should be automated. Gulp makes the process of writing tasks easier, even for people who are less familiar with JavaScript. 

Gulp uses pipelines to stream the data from one plugin to another, and the final result is outputted to a destination folder. Gulp performs better compared to Grunt because it doesn't create temporary files for storing intermediate results, which results in fewer I/O calls.

Automate and enhance your workflow using Gulp

Grunt

Grunt is a task runner and an automation tool for JavaScript. Grunt has a command-line interface that lets you run custom tasks defined in a file called a Gruntfile. Grunt has thousands of plugins to choose from, which should cover most of the common repetitive tasks that you'd encounter. With Grunt, you can run all the tasks under a single command, making your life easier.

Grunt the JavaScript task runner

npm 

Gulp and Grunt require you to spend time learning and mastering a new tool, which takes time. Introducing additional dependencies into your project can be avoided by choosing an alternative that is already bundled with Node.js. Although npm is better known as a package manager, npm scripts can be used to perform the bulk of the abovementioned tasks. 

npm task runner

Tools: Testing

Testing is the process of validating and verifying that the application meets the expected business and technical requirements. The Test-Driven Development approach also aids in discovering bugs and therefore should be treated as an integral part of the modern front-end development stack.

Jest

Jest is a relatively new testing framework authored by Facebook and is well-received by the React community. There is a common misconception that Jest is specifically designed to work with React; however, according to the Jest Documentation:

Although Jest may be considered React-specific test runner, in fact it is a universal testing platform, with the ability to adapt to any JavaScript library or framework. You can use Jest to test any JavaScript code.

The biggest advantage of using Jest over other test suites is that you require zero or minimal configuration to start writing tests. The framework has a built-in assertion library and supports the use of mock functions or spies.

Delightful JavaScript testing using Jest

Jest has a feature called snapshot testing that lets you ensure that the UI of the application doesn't change unexpectedly. The developers at Facebook and other contributors have been pouring a lot of work into this project recently, so it wouldn't be a surprise if Jest turns out to be the most popular testing framework for JavaScript in the years to come.

Mocha 

Mocha is a JavaScript testing framework that features browser support, async support including promises, test coverage reports, and a JavaScript API for running tests. Mocha is often paired with an assertion library such as Chai, should.js, expect.js, or better-assert because it lacks an assertion library of its own. 

Mocha test runner and testing framework

Jasmine

Jasmine is a behavior-driven testing framework for JavaScript. Jasmine aims to be a browser, platform, and framework-independent test suite. Jasmine has its own assertion library called matchers that gives it a clean and easy-to-read syntax. Jasmine doesn't have a built-in test runner, and you might have to use a generic test runner like Karma instead. 

Jasmine test runner and testing framework

Summary

JavaScript, the language of the web, has stayed relevant since the days of its inception back in 1995. It will probably stay that way as long as browsers don't decide to ditch it for another language. Although there are a lot of other languages that compile down to JavaScript, there is no other scripting language that will replace JavaScript in the foreseeable future. Why? Because JavaScript has grown too popular to be replaced.

The language is not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato Market

The JavaScript environment is definitely evolving, which is evident from the current trends in web development. Older libraries and frameworks have been replaced with new technologies. jQuery, which was once the most favored JavaScript library, is experiencing a decline in terms of appeal, usage, and popularity. The new generation of front-end libraries, frameworks, and tools are gaining ground and getting universal acceptance. 

Adapting to the new trends in technology has benefits too. Coding jobs that require React have some of the highest salaries in the industry, with an average salary of $105,000 in the U.S. according to Stack Overflow (2016). So you need to continue learning and experimenting with the latest tools and frameworks to get the best out of JavaScript. 

If you think I've missed a JavaScript framework, library or tool that is worth mentioning, let me know through the comments. 

Further Reading

How to Create Your Own Local Premium URL Shortener Service

$
0
0

You will encounter some very long URLs (Uniform Resource Locators) on the internet. Many sites put information about your visit into the URL: items like language, location, identification, reference codes for specials, and many other items. This makes for very long URLs.

Premium URL Shortener on CodeCanyon
Premium URL Shortener on CodeCanyon

Premium URL Shortener on Code Canyon is a way to make long URLs shorter. In this tutorial, I will show you how to set up your own URL shortener on your system and how to use it.

What Is a URL Shortener?

You use a URL whenever you browse the internet. It identifies the particular web page and content. Since these can often contain parameters for a form or search engine, these URLs can get quite large.

This URL is for searching the Tuts+ website for the string “How to Draw Animals: Horses, Their Anatomy and Poses”. This string is 74 characters long. I’ve seen URLs that are over 200 characters long.

When you use a URL shortening service, like bit.ly, you get a much shorter URL. The same URL is now 15 characters long. When someone browses this link, the bit.ly server redirects the browser to the full URL. The extra lookup on a different URL does delay the site load time, but not much.

Installing Docker

The easiest way to create a local server is to use a virtualized environment. But running a full system virtualizer is very resource intensive. Docker is a minimal virtualizer for terminal-based systems. You can run a Docker container (a small unix server) using fewer system resources.

To run containers on your system, you will need to install Docker. Select the proper download for your operating system from the Docker website.

With Docker installed, you need to prepare your system to look for the web service you will be creating. To do this, you will need to change a system file. In the /etc/hosts file for Linux or macOS systems and in the c:\windows\System32\drivers\etc\lmhosts file for a Windows system, put this statement:

This change will make all references to http://s.dev go to the local system. This is done to give the service a proper hostname before trying to configure it.

To create your development area, create a directory and place the Premium URL Shortener zip file in it and expand it. You should then have this directory structure:

Directory Structure
Directory Structure

This is the documentation with the file main.zip. Expand this file also. Once you expand it, you should have this directory structure:

Directory Structure with Code
Directory Structure with Code

The main.zip file contains all the source code files and resources for the service. This will be the directory you will add to the Docker instance.

Now you need to get the Docker LAMP stack from fauria. With Docker running, type the following into a terminal:

This will download the Fauria LAMP (Linux, Apache, MySQL, and PHP) stack to your Docker installation. Once downloaded, you can create the container with:

Replace the {{service source directory}} with the complete path to the directory that contains all the source files and resources. This command creates a container named linkshort that works on port 80 and gives all the error and log messages to standard out.

Right now, every time you stop and relaunch the container, you will lose all your information. You need to move the database information to your source code directory to preserve it with each reboot. In a terminal window, perform these commands:

The first command opens a bash shell to the container. The second command creates the directory data in your source code directory. The container sees the source code directory as the /var/www/html directory. The third command copies the database information to that directory. The exit command gets you out of the container. 

Now stop the container using:

You will use this command each time you want to stop the container.

Now, to restart the container using the proper data directory, use this command:

This time you created the container with the MarianDB server using the database data now stored on your computer. This is the command you will use to launch the service. I use the keyboard expander Typinator to type this out for me.

Now, the database for the URL shortener needs to be created. You will need to open a shell in to the container as well. In a new terminal instance, type the following command:

This command creates the bash shell into the container. If you need to adjust something in the container, this is the command you will use. Next, open a command shell into the MarianDB program:

Now, you can create databases in MarianDB and grant permissions to the web server to access it:

The {{password}} needs to be set to the password you want to give to the user of the database. Remember this as you will use it to configure the service.

With the service running in the container, open your web browser to http://s.dev.

Requirement Check Page
Requirement Check Page

If you did the configuration, you should see this page. This page shows the requirements for the URL Shortener service and the status of your setup. By using the fauria container in Docker, you already have all the dependencies met. Click the blue button at the bottom of the page.

Database Configuration Page
Database Configuration Page

The next page shown is the configuration file creator for the service. This page allows you to give the program the name and password for the database you created earlier.

Database Configuration Page Details
Database Configuration Page Details

You need to fill in these fields as shown above. The Database Host is the localhost for the container. The Database Name is urlshort, which you created in the setup. The Database User is www-data, and the password is the one you assigned in the initial database setup. The Database Prefix is the beginning name for each database created for the service. I used short_. The installation program sets the Security Key. Keep a copy of the key given for future reference.

If you were to install this on a Virtual Private Server (VPS), these values would be according to that service. Some will be the same, and some will change.

With the proper information in place, press the blue button at the bottom of the page to go to step 3.

Basic Configuration Page
Basic Configuration Page

The Basic Configuration screen allows you to set the admin user name, email, and password. Set these to the values that pertain to you. The Site URL needs to be set to http://s.dev as you set up in your hosts file earlier. Once set, press the blue button at the bottom of the screen.

Installation Complete Page
Installation Complete Page

The next screen tells you that the service is now set up. Press the blue button that says Delete install.php. This is a security feature for using on a real web server, but isn’t needed for a local install. However, the installation will not finish until you have done it.

Premium URL Shortener Front Page
Premium URL Shortener Front Page

Congratulations—the service is functional! You should see the above screen. If you give a long URL into the input field named Paste a long url and then press the blue button Shorten, you will get a shortened URL to use. The URL will also be in the database for future reference. This feature makes a great bookmarker.

Using the API

Now that you have your URL shortener service running, you will want to make good use of it. But always opening a web page, even a local one, will slow you down. You need to make it faster. That’s where using the API (Application Programming Interface) is helpful. You can refer to the full documentation for the API.

With the service running, open the page http://s.dev/user/settings.

Account Settings Page
Account Settings Page

You have to log in to your account to see this page. At the bottom right in the sidebar, you will see Your API Key: with an alpha-numeric number. Copy that number and save it. This number gives access to the API.

To make use of the API, you can create a Ruby program to access it. On macOS and Linux, Ruby is usually pre-installed. On Windows, you will have to install it.

The minimal program in Ruby for creating a short link is:

Save the script to a file named shortener.rb, replace {YourAPIKey} with the API key you copied earlier, and run the following in the command line:

You should get a shortened link for that URL. This creates the shortened URLs, but is still not convenient.

Creating a PopClip Extension

On the Mac, PopClip is a great little program for processing highlighted text. To make creating the shortened links easier, you will create a PopClip extension. I’m not going to explain everything about making an extension, but you can read about the mechanics of doing it in my tutorial PopClip: Scripting Extensions.

Create a PopClip extension called PremiumURLShortener.popclipext. Use the following for the Config.plist file inside the extension directory:

Then create the script file for the extension called PremiumURLShortener.rb and place this code in it:

When you load the new extension, it will ask for the API key. Once you give it the API key and press Okay, it is usable in PopClip.

Shortening a URL with PopClip
Shortening a URL with PopClip

When you select a link, PopClip will open with a list of options. You then select the Shortener option. It will think for a while and then paste the proper shortened URL. The full extension is in the download for this tutorial. Now, you are ready to do many more!

Conclusion

Not only do you now have a private URL shortener, you also know how to make use of Docker for running local containers, an easy way to keep track of URLs that you use, and a way to create the shortened links. 

You can use the Ruby script with Alfred 3 or Keyboard Maestro as well. Enjoy using your new service and experimenting with its other features.

Package Management in Laravel

$
0
0

In this article, we'll go ahead and explore the package management feature in the Laravel framework. In the course of the article, we’ll go through a real-world example to demonstrate the purpose of the article.

Package management in Laravel is an important feature that allows you to bundle a piece of functionality so that it can be distributed easily. Moreover, you could always publish your package to repositories like Packagist and GitHub that allow other developers to benefit from your package.

To demonstrate the concept, we’ll build an example page in Laravel that uploads an image to the Amazon S3 cloud. Rather than going with the usual flow, we’ll develop it as a bundled package that can be distributed and maintained easily.

Before moving ahead, I assume that you are familiar with the Laravel framework already as I won't go into the details of basic Laravel concepts.

Also, you need to have a valid AWS account and the credentials to access the Amazon API in order to follow along with the example in this article. So, make sure that you set that up first.

With everything on hand, we are ready to dive into the actual development.

Setting Up the Package Files

Let's quickly look at the list of files that we'll implement throughout the course of this tutorial.

  • composer.json: We need to add the class mapping of our package in the existing composer.json file in the root of the package.
  • config/app.php: This is the existing file that we'll use to add an entry of our custom service provider so that we can load views and routes using that file.
  • composer.json: This is the package-specific composer.json file should you wish to distribute the package with others.
  • packages/envato/aws/src/Providers/AwsServiceProvider.php: The usual Laravel service provider file that will be used to load other components of the package.
  • packages/envato/aws/src/routes/web.php: It loads the custom routes of our package.
  • packages/envato/aws/src/Controllers/AwsController.php: This is the controller file that handles the application logic of our package.
  • packages/envato/aws/src/views/upload.blade.php: The view file that handles the rendering logic.

Don't worry if it doesn't make much sense yet as we'll discuss everything in detail as we go through it.

Setting Up the Prerequisites

As we discussed earlier, our package implements the use case of file upload to Amazon S3 cloud. In this section, we'll go through the prerequisites that need to be set up in order to run our package successfully.

As a Laravel developer, you must be familiar with Flysystem, which provides a nice abstraction layer to interact with the filesystem. It provides easy-to-use drivers so that you can interact with it easily no matter the type of filesystem you're dealing with—either it's the local file system or the AWS S3 cloud system.

In order to enable the support of Amazon S3 cloud filesystem with Flysystem, you need to install the corresponding adapter composer package.

Go ahead and run the following composer command from your project root to install the flysystem-aws-s3-v3 package.

Upon the successful execution of that command, now you're able to use Laravel Flysystem to interact with Amazon S3 cloud filesystem in the same way you would have used it for the local file system.

Now, let's quickly pull in the config/filesystems.php file to see the settings provided for the Amazon S3 filesystem.

As you can see, the configuration is already in place for the Amazon S3; it's just that we need to set appropriate ENV variables in the .env file.

Go ahead and add the following variables in your .env file.

Of course, you need to replace placeholders with their actual values. Now, you're ready to use the Flysystem AWS S3 adapter in your Laravel application.

Going Through the Package Files

To create your own Laravel package, the first thing is to create an appropriate directory structure that reflects the conventions of the Laravel system. I assume that you're already running a basic Laravel application; in fact, the default blog application will do as well.

Go ahead and create the packages directory in the root of your application. Considering that you're going to distribute your package with others, the preferred structure of your package should be {vendor_name}/{package_name}.

Following that convention, let's go ahead and create an envato/aws directory under the packages directory. As you may have guessed, envato is the vendor name, and aws stands for the package name itself. Finally, let's create a packages/envato/aws/src directory that holds the source files of our package.

Now, we need to inform Laravel about our new package. Go ahead and open the composer.json file in the root of your Laravel application and add the "Envato\\Aws\\": "packages/envato/aws/src" entry in the autoload section as shown below.

As you can see, the Envato\Aws\ namespace is mapped to the packages/envato/aws/src directory. Now, we just need to run the dump-autoload command to regenerate the composer mappings.

Now, you can use the Envato\Aws\ namespace in your application and it'll pick up the files from the correct location!

Composer File of the Package

Now, let's go ahead and add a package-specific composer.json file so that you can distribute your package to the packagist repository.

Go to the packages/envato/aws directory and run the following command to generate a composer.json file for your package.

You'll be prompted with the usual questions, so just go through it and it'll create a composer.json file.

At the very least, it should look something like this.

Route

In our package, we'll create a simple page that displays the status of the uploaded file. So we need to create a route associated with that page.

Let's create a route file at packages/envato/aws/src/routes/web.php.

Does it require any explanation at all? The obvious next step is to create the associated controller file.

Controller

Let's create a controller file at packages/envato/aws/src/Controllers/AwsController.php with the following contents.

Let's go through the file to understand what every piece of code is meant for.

We kick off the things by setting a namespace of our controller to namespace Envato\Aws\Controllers. Recall that we added the mapping of Envato\Aws to packages/envato/aws/src in the root composer.json file so that it could find our package files.

Next, we've defined the upload method that does the needful to sync local files to the Amazon S3 cloud. The important thing to note here is the first argument of the upload method that asks for the \Illuminate\Contracts\Filesystem\Factory dependency. During the execution, the appropriate Laravel contract will be injected.

Now, we could use the filesystem factory instance to create disk instances as needed. The disk instance in Laravel is the driver that allows you easy access to underlying filesystems such as the local disk, Amazon S3 cloud, and the like.

For simplicity, we'll transfer the static image file that's already available under the default local storage of Laravel, and the path is storage/app/test.jpg.

As a first step, let's grab the source file contents.

With everything set up as mentioned, you should be able to sync a file to Amazon S3 using the put method.

Make sure that you've set the AWS environment variables correctly, just in case something doesn't work as expected.

And the last thing is to call a view file that displays the synced image and an appropriate message.

Of course, we haven't created a view file yet, and that's exactly what the next section is all about.

View

Let's create a view file at packages/envato/aws/src/views/upload.blade.php with the following contents.

It's a pretty standard view file that displays the uploaded image upon the successful upload, or otherwise an appropriate error message.

Service Provider

We're almost done with our package as we've created the necessary files. The next step is to create a service provider so that we can register the routes and views of our package.

Let's create a service provider file at packages/envato/aws/src/Providers/AwsServiceProvider.php with the following contents.

Obviously, you could have created the service provider file by using the artisan command as well. But it would have required an extra step of moving the file from app/Providers to our package.

Anyway, let's go through the service provider file that was just created.

Firstly, we load the routes and views associated with our package.

Next, we provide the support of publishing the views of our packages so that the developers who want to override the views can do that. Next time they run the php artisan vendor:publish command, Laravel copies the views from packages/envato/aws/src/views/ to resources/views/vendor/aws.

Now, they can change the views under the resources/views/vendor/aws directory, and it'll be picked up automatically by Laravel instead of the views under packages/envato/aws/src/views/. In fact, it's the proper way to modify third-party package views, instead of directly modifying the package views.

That's it as far as the service provider is concerned. As you would have expected, we need to add the service provider entry in config/app.php. Add the following entry in the providers array.

And there you are—everything's in order now, so that we can go ahead and test our package.

Go ahead and run the http://your-laravel-application/aws/s3/upload URL in your browser. If everything goes fine, you should see the image on your page that's loaded from the Amazon S3 cloud. Please let me know if you face any problems, and I would be more than happy to answer those.

So we are on the closing note of this article, and I hope you've enjoyed it!

Conclusion

Today, we discussed one of the important features of the Laravel framework—package management. In the process of setting up our custom Laravel package, we went through a real-world example that demonstrated how you could upload an image to the Amazon S3 cloud.

It's a really nice feature should you wish to bundle and distribute a set of functionalities all together. In fact, you could look at this as an option to approach your custom module development in Laravel.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.

As always, you could leave your valuable comments and feedback in the feed below!

Speeding Up Python With Cython

$
0
0

Cython is a superset of Python that lets you significantly improve the speed of your code. You can add optional type declarations for even greater benefits. Cython translates your code to optimized C/C++ that gets compiled to a Python extension module. 

In this tutorial you'll learn how to install Cython, get an immediate performance boost of your Python code for free, and then how to really take advantage of Cython by adding types and profiling your code. Finally, you'll learn about more advanced topics like integration with C/C++ code and NumPy that you can explore further for even greater gains.

Counting Pythagorean Triples

Pythagoras was a Greek mathematician and philosopher. He is famous for his Pythagorean theorem, which states that in a right-angled triangle, the sum of squares of the legs of the triangles is equal to the square of the hypotenuse. Pythagorean triples are any three positive integers a, b and c that such that a² + b² = c². Here is a program that finds all the Pythagorean triples whose members are not greater than the provided limit.

Apparently there are 881 triples, and it took the program a little less than 14 seconds to find it out. That's not too long, but long enough to be annoying. If we want to find more triples up to a higher limit, we should find a way to make it go quicker. 

It turns out that there are substantially better algorithms, but today we're focusing on making Python faster with Cython, not on the best algorithm for finding Pythagorean triples. 

Easy Boosting With pyximport

The easiest way to use Cython is to use the special pyximport feature. This is a statement that compiles your Cython code on the fly and lets you enjoy the benefits of native optimization without too much trouble. 

You need to put the code to cythonize in its own module, write one line of setup in your main program, and then import it as usual. Let's see what it looks like. I moved the function to its own file called pythagorean_triples.pyx. The extension is important for Cython. The line that activates Cython is import pyximport; pyximport.install(). Then it just imports the module with the count() function and later invokes it in the main function.

The pure Python function ran 50% longer. We got this boost by adding a single line. Not bad at all.

Build Your Own Extension Module

While pyximport is really convenient during development, it works only on pure Python modules. Often when optimizing code you want to reference native C libraries or Python extension modules. 

To support those, and also to avoid dynamically compiling on every run, you can build your own Cython extension module. You need to add a little setup.py file and remember to build it before running your program whenever you modify the Cython code. Here is the setup.py file:

Then you need to build it:

As you can see from the output, Cython generated a C file called pythagorean_triples.c and compiles it a platform-specific .so file, which is the extension module that Python can now import like any other native extension module. 

If you're curious, take a peek at the generated C code. It is very long (2789 lines), obtuse, and contains a lot of extra stuff needed to work with the Python API. Let's drop the pyximport and run our program again:

The result is pretty much the same as with pyximport. However, note that I'm measuring only the runtime of the cythonized code. I'm not measuring how long it takes pyximport to compile the cythonized code on the fly. In big programs, this can be significant.

Adding Types to Your Code

Let's take it to the next level. Cython is more than Python and adds optional typing. Here, I just define all the variables as integers, and the performance skyrockets:

Yes. That's correct. By defining a couple of integers, the program runs in less than 57 milliseconds, compared to more than 13 seconds with pure Python. That's almost a 250X improvement.

Profiling Your Code

I used Python's time module, which measures wall time and is pretty good most of the time. If you want more precise timing of small code fragments, consider using the timeit module. Here is how to measure the performance of the code using timeit:

The timeit() function takes a statement to execute, a setup code that is not measured, and the number of times to execute the measured code.

Advanced Topics

I just scratched the surface here. You can do a lot more with Cython. Here are a few topics that can further improve the performance of your code or allow Cython to integrate with other environments:

  • calling C code
  • interacting with the Python C API and the GIL
  • using C++ in Python
  • porting Cython code to PyPY
  • using parallelism
  • Cython and NumPy
  • sharing declarations between Cython modules

Conclusion

Cython can produce two orders of magnitude of performance improvement for very little effort. If you develop non-trivial software in Python, Cython is a no-brainer. It has very little overhead, and you can introduce it gradually to your codebase.

Additionally, don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.

An Introduction to Elixir Applications

$
0
0

In my previous articles we have discussed various Elixir terms and written a hefty amount of code. What we have not discussed, however, is how to structure and organize your code so that it is easy to maintain and release. 

Applications are very common for Erlang and Elixir and are used to build reusable components that behave as stand-alone units. One application may have its own supervision tree and configuration, and it can rely on other applications that are available either locally or on some remote server. All in all, working with applications is not that complex, and people who have come, say, from the world of Ruby will find many familiar concepts.

In this article you will learn what applications are, how they can be created, how to specify and install dependencies, and how to provide environment values. At the end of the article we will do some practice and create a web-based calculator. 

I will be using Elixir 1.5 in this article (it was released a couple of months ago), but all the explained concepts should apply to version 1.4 as well.

Applications?

Some might argue that the term "application" is not very appropriate because in Erlang and Elixir it actually means a component, or some code that has a bunch of dependencies. The application itself can be used as a dependency as well—in Ruby world we would call it a "gem".

All in all, applications are very common in Elixir and allow you to craft reusable components while also providing easy dependency management. They consist of one or multiple modules with zero or more dependencies and are described by the application resource file. This file contains information about the application's name, version, its modules, dependencies, and some other stuff. You may create the resource file manually, but it is much easier to do so with the mix tool that will also prepare a correct folder structure for you. 

So let's see how we can create a new Elixir application!

New Application

To create a new application, all you need to do is run the following command:

We can also provide the --sup flag to create an empty supervisor for us. Let's create a new application called Sample this way:

This command will create a sample directory for you with a handful of files and folders inside. Let me quickly guide you through them:

  • config folder contains a sole file config.exs that, as you can guess, provides configuration for the application. Initially it has some useful comments, but no configuration. Note, by the way, that the configuration provided in this file is only restricted to the application itself. If you are loading the application as a dependency, its config.exs will be effectively ignored.
  • lib is the primary folder of the application that contains a sample.ex file and a sample folder with an application.ex file. application.ex defines a callback module with a start/2 function that creates an empty supervisor.
  • test is the folder containing automated tests for the application. We won't discuss automated tests in this article.
  • mix.exs is the file that contains all the necessary information about the application. There are multiple functions here. Inside the project function, you provide the app's name (as an atom), version, and environment. The application function contains information about the application module callback and runtime dependencies. In our case, Sample.Application is set as the application module callback (that can be treated as the main entry point), and it has to define a start/2 function. As already mentioned above, this function was already created for us by the mix tool. Lastly, the deps function lists build-time dependencies.

Dependencies

It is quite important to distinguish between runtime and build-time dependencies. Build-time dependencies are loaded by the mix tool during the compilation and are basically compiled into your application. 

They can be fetched from a service like GitHub, for example, or from the hex.pm website, an external package manager that stores thousands of components for Elixir and Erlang. Runtime dependencies are started before the application starts. They are already compiled and available for us.

There are a couple of ways to specify build-time dependencies in a mix.exs file. If you'd like to use an application from the hex.pm website, simply say:

The first argument is always an atom representing the application's name. The second one is the requirement, a version that you desire to use—it is parsed by the Version module. In this example, ~> means that we wish to download at least version 0.0.1 or higher but less than 0.1.0. If we say ~> 1.0, it means we'd like to use version greater than or equal to 1.0 but less than 2.0. There are also operators like ==, >, <, >=, and <= available.

It is also possible to directly specify a :git or a :path option:

There is also a :github shortcut that allows us to provide only the owner's and a repo's name:

To download and compile all dependencies, run:

This will install a Hex client if you don't have one and then check if any of the dependencies needs to be updated. For instance, you can specify Poison—a solution to parse JSON—as a dependency like this:

Then run:

You will see a similar output:

Poison is now compiled and available on your PC. What's more, a mix.lock file will be created automatically. This file provides the exact versions of the dependencies to use when the application is booted. 

To learn more about dependencies, run the following command:

Behaviour Again

Applications are behaviours, just like GenServer and supervisors, which we talked about in the previous articles. As I already mentioned above, we provide a callback module inside the mix.exs file in the following way:

Sample.Application is the module's name, whereas [] may contain a list of arguments to pass to the start/2 function. The start/2 function must be implemented in order for the application to boot properly.

The application.ex contains the callback module that looks like this:

The start/2 function must either return {:ok, pid} (with an optional state as the third item) or {:error, reason}.

Another thing worth mentioning is that applications do not really require the callback module at all. It means that the application function inside the mix.exs file may become really minimalistic:

Such applications are called library applications. They do not have any supervision tree but can still be used as dependencies by other applications. One example of a library application would be Poison, which we specified as a dependency in the previous section.

Starting an Application

The easiest way to start your application is to run the following command:

You will see an output similar to this one:

A _build directory will be created inside the sample folder. It will contain .beam files as well as some other files and folders.

If you don't want to start an Elixir shell, another option is to run:

The problem, though, is that the application will stop as soon as the start function finishes its job. Therefore, you may provide the --no-halt key to keep the application running for as long as needed:

The same can be achieved using the elixir command:

Note, however, that the application will stop as soon as you close the terminal where this command was executed. This can be avoided by starting your application in a detached mode: 

Application Environment

Sometimes you may want the user of an application to set some parameter before the app is actually booted. This is useful when, for example, the user should be able to control which port a web server should listen to. Such parameters can be specified in the application environment that is a simple in-memory key-value storage. 

In order to read some parameter, use the fetch_env/2 function that accepts an app and a key:

If the key cannot be found, an :error atom is returned. There are also a fetch_env!/2 function that raises an error instead and get_env/3 that may provide a default value.

To store a parameter, use put_env/4:

The fourth value contains options and is not required to be set.

Lastly, to delete a key, employ the delete_env/3 function:

How do we provide a value for the environment when starting an app? Well, such parameters are set using the --erl key in the following way:

You can then easily fetch the value:

What if a user forgets to specify a parameter when starting the application? Well, most likely we need to provide a default value for such cases. There are two possible places where you can do this: inside the config.exs or inside the mix.exs file.

The first option is the preferred one because config.exs is the file that is actually meant to store various configuration options. If your application has lots of environment parameters, you should definitely stick with config.exs:

For a smaller application, however, it is quite okay to provide environment values right inside mix.exs by tweaking the application function:

Example: Creating a Web-Based CalcServer

Okay, in order to see applications in action, let's modify the example that was already discussed in my GenServer and Supervisors articles. This is a simple calculator that allows users to perform various mathematical operations and fetch the result quite easily. 

What I want to do is make this calculator web-based, so that we can send POST requests to perform calculations and a GET request to grab the result.

Create a new lib/calc_server.ex file with the following contents:

We will only add support for the add operation. All other mathematical operations can be introduced in the same way, so I won't list them here to make the code more compact.

The CalcServer utilizes GenServer, so we get child_spec automatically and can start it from the callback function like this:

0 here is the initial result. It must be a number, otherwise CalcServer will immediately terminate.

Now the question is how do we add web support? To do that, we'll need two third-party dependencies: Plug, which will act as an abstraction library, and Cowboy, which will act as an actual web server. Of course, we need to specify these dependencies inside the mix.exs file:

Now we can start the Plug application under our own supervision tree. Tweak the start function like this:

Here we are providing child_spec and setting Sample.Router to respond to requests. This module will be created in a moment. What I don't like about this setup, however, is that the port number is hard-coded, which is not really convenient. I might want to tweak it when starting the application, so let's instead store it in the environment:

Now provide the default port value inside the config.exs file:

Great! 

What about the router? Create a new lib/router.ex file with the following contents:

Now we need to define a couple of routes to perform addition and fetch the result:

We are using get and post macros to define the /result and /add routes. Those macros will set the conn object for us. 

ok and fetch_number are private functions defined in the following way:

fetch_query_params/2 returns an object with all the query parameters. We are only interested in the number that the user sends to us. All parameters initially are strings, so we need to convert it to integer.

send_resp/3 sends a response to the client with the provided status code and a body. We won't perform any error-checking here, so the code will always be 200, meaning everything is okay.

And, this is it! Now you may start the application in any of the ways listed above (for example, by typing iex -S mix) and use the curl tool to perform the requests:

Conclusion

In this article we have discussed Elixir applications and their purpose. You have learned how to create applications, provide various types of information, and list dependencies inside the mix.exs file. You've also seen how to store the configuration inside the app's environment and learned a couple of ways to start your application. Lastly, we have seen applications in action and created a simple web-based calculator.

Don't forget that the hex.pm website lists many hundreds of third-party applications ready for use in your projects, so be sure to browse the catalog and pick the solution that suits you! 

Hopefully, you found this article useful and interesting. I thank you for staying with me and until the next time.

Code Your First Augmented Reality App With ARKit

$
0
0

Until recently, Augmented Reality was one of those "futuristic" ideas that were portrayed in science-fiction utopias. But the time has come when building an AR app has become a reality, and you can have one in your pocket. 

In this tutorial, you'll learn how to bring Mars, the nearest planet to Earth, into your own room.

Getting Started

Xcode Version

Before we begin, make sure you have the latest version of Xcode installed on your Mac. This is very important because ARKit will only be available on Xcode 9 or newer. You can check your version by opening Xcode and going to Xcode> About Xcode in the upper toolbar. 

If your version of Xcode is older than Xcode 9, you can go to the Mac App Store and update it for free. If you don't already have Xcode, you can also download and install it for free.

Sample Project

New Project

After you have made sure you have the right version of Xcode, you'll need to make a new Xcode project. 

Go ahead and open Xcode and click Create a new Xcode project.

Figure 1 Create an Xcode Project

You may be used to making a Single View Application, but for this tutorial, you will need to choose an Augmented Reality App and then click Next.
Figure 2 Choose an Augmented Reality App

Gaming Frameworks

You can name your project anything you like, but I will be naming mine ARPlanets. You will also notice that there is an option at the bottom where you can select from SceneKit, SpriteKit, and Metal. 

These are all Apple's gaming frameworks, and for the purpose of the tutorial, we will be using SceneKit because we'll be using 3D objects. 

Go ahead and select SceneKit if it isn't already selected. Your screen should look something like this:

Figure 3 Create your Project

Preparing to Test

Connecting an iPhone

Since the Xcode Simulator doesn't have a camera, you'll need to plug in your iPhone. Unfortunately, if you don't have an iPhone, you'll need to borrow one to be able to follow along with this tutorial (and for any other camera-related apps). If you already have an iPhone connected to Xcode, you can skip ahead to the next step.

A nifty new feature in Xcode 9 is that you can wirelessly debug your app on a device, so let's take the time to set that up now:

In the top menu bar, choose Window > Devices and Simulators. In the window that appears, make sure that Devices is selected at the top.

Now, plug in your device using a lightning cable. This should make your device appear in the left pane of the Devices and Simulators window. Simply click your device, and check the Connect via Network box.

Figure 4 Devices and Simulators

You will now be able to wirelessly debug on this iPhone for all future apps.

Complete Setup

Now your setup is complete. You should have a working ARKit app, and you can test it on the iPhone that you just connected. In the upper left of Xcode, next to the Run and Stop buttons, select your device from the simulator dropdown.

Figure 5 Select a Simulator

I've selected Vardhan's iPhone, but you need to select your specific device. 

Now you're done creating your starter project, and you should see a virtual spaceship appear in your world once you click Run. Here's what it should look like:

An Augemented Reality spaceship

Diving Deeper

Okay, we're finally ready to delve deeper and actually write some code. You already have a working ARKit app, so let's build on that and make something cool. 

Exploring the Sample Project

Nodes and Textures

If you look at the folder called art.scnassets, you will notice that it contains two things already: the spaceship node and its texture. In this example, Apple has created a blank spaceship object and basically used an image overlay to form its colors and shapes.

Similarly, we will be creating our own sphere and overlaying an image of the surface of Mars to create an accurate representation of Mars.

Exploring the Sample Code

The ARKit template in Xcode comes with a bunch of pre-written code to make the spaceship appear, so let's take some time to explore what everything means and why it works.

At the top of the file, you'll see the following:

At the top, UIKit is being imported, and we need it because the main view will be a UIViewController. Remember when you selected SceneKit in the project setup? It's being imported right along with ARKit down below. These are all of the libraries that this file uses.

Below this, you will see a class declaration and the following line of code:

We don't need to go too much in depth here, but this is an Augmented Reality SceneKit view which is linked via an @IBOutlet to the storyboard. This is the main view for everything we'll be placing in this tutorial.

Going down a bit further, the viewDidLoad() method should look like this:

Here's what this code does:

  1. Remember the sceneView that was linked to the storyboard? We're assigning its delegate to our ViewController because it conforms to the ARSCNViewDelegate protocol.
  2. The next line of code is optional, and it needs to be disabled (set to false) when you actually publish on the App Store. This shows you data such as the FPS and other performance data.
  3. Previously, we saw the ship.scn file (the 3D rendering) in the folder called art.scnassets. In this line, an SCNScene, which is a hierarchy of nodes (in this case, the spaceship and its camera) is being created.
  4. Lastly, the scene is added to the sceneView, which is connected to the storyboard with an @IBOutlet.

We didn't cover each and every line in the ViewController.swift file, but what we did cover is important for you to know in order to follow along with the tutorial and build your own ARKit apps in the future.

Creating Planet Mars

Removing the Spaceship

Since we'll be making a planet instead of a spaceship in our ARKit app, you'll need to remove it.

First, remove the following two files from the art.scnassets folder: ship.scn and texture.png. We won't be needing these anymore. 

Next, go back to your ViewController.swift file and locate the following line of code:

Since we no longer have the ship.scn file, this line of code will cause our app to crash, especially because the exclamation mark at the end of this line is forcing it. Since we won't be using a .scn file for our ship, there's no need initialize the SCNScene with a string.

Simply replace this line of code with the following:

If you now run your app, you will see reality, but it won't be augmented. In other words, the spaceship will be gone.

Function Declaration

Right below viewDidLoad(), create a function declaration as follows:

Doesn't it seem a bit pointless to create something and not return it? In the function, we will need to return an SCNNode. While we're at it, let's also take in a parameter for the position of the planet. 

After you've made these modifications, your method should appear like this:

Coding the Sphere

Since Mars is spherical, let's create a sphere to be the basic shape of Mars. You may choose to do this directly in the viewDidLoad() method, but we'll be using the function we declared above.

Inside your function, insert the following code:

Here's what this code does:

  1. This line creates a sphere of type SCNSphere with a radius of 0.4
  2. Here, we simply turn the sphere into an SCNNode which can be returned to the function call site.
  3. When we take in the position as an argument to the createMars() function, we are using the parameter here to set the position of the SCNNode which we created on the previous line.
  4. This simply returns the SCNNode to the function.

Adding the Sphere

So far, we have created a sphere, but to make it appear at all, we need to add it to our current scene. To do this, add these three lines of code to your viewDidLoad() method:

This is what the code does:

  1. This line creates a position of type SCNVector3 (which is a three-dimensional representation of a point in space) to be passed into the createMars() function which we created earlier.
  2. Here, we're calling createMars() and passing in the position from the previous variable. Next, we are assigning the node which this function returns to a variable called mars.
  3. After doing that, we're adding mars to the scene that was provided in the sample project from Apple.

Wow! We've made quite a bit of progress already. If you run your app now, you should be able to see that there is a white sphere somewhere in your world. If you try to look at it from other angles, it will just look like a circle, but that's because we don't have any textures or shadows yet. This is how it should look:

Untextured AR sphere

Adding the Texture

Now that we have a sphere in place, we need to add a texture so that it looks like the actual planet, Mars. I just searched for a photo of Mars's surface, and I will be using it, but you can use any photo you'd like (if you want to mix things up, you can even use textures of other planets).

To use the image you just got, you'll need to place it in two folders: art.xcassets and art.scnassets. Another thing to note: if you want to be able to copy and paste this code into your project, you will need to name your image mars_texture.png, and it needs to be a PNG file.

Add the following code before the return line in the function createMars():

First, we create an SCNMaterial that SceneKit can use later on to wrap around the sphere, and we assign it to a constant named material. Then we particulate the selected image and reassign it to the contents of the default SCNMaterial. In other words, the material constant now contains this image to be used as an SCNMaterial. Finally, we wrap the sphere with the SCNMaterial which we made previously.

You are now done, and if you run your app, you'll be able to see Mars in your room! You can even walk around it and see it from different angles. Here's how it should look:

Mars in your backyard

Conclusion

Now, you can see just how easy it is to implement Augmented Reality in your app. You can make your imagination go wild with it and even make full games. If you have more technical three-dimensional rendering skills, you can also integrate this with your skills.

I hope this tutorial was informative and you enjoyed it!


Best Unique Bootstrap JavaScript Plugins

$
0
0

Though Bootstrap contains a great selection of useful plugins, there’ll always be those times when you need some extra functionality. Luckily, Bootstrap is pretty extendible and there are loads of JavaScript plugins available that will instantly add a desired behaviour and save you a whole lot of time and effort. Here are ten of the best unique Bootstrap JavaScript plugins to be found at CodeCanyon.

1. Dropdown Sidebar Menu Responsive Bootstrap Navigation

If you’re looking for a sidebar menu with a healthy dose of sophistication, the Dropdown Sidebar Menu Responsive Bootstrap Navigation plugin could be just the thing you need. The plugin supports multiple navigation styles, and users can set the default or change any navigation affecting window load and sidebar toggle features.

Dropdown Sidebar Menu Responsive Bootstrap Navigation

Main features:

  • designed and developed for any device
  • customisable menu trigger on each menu level 
  • dropdown menu with toggle effect
  • multiple submenu levels
  • and more

User Masino_Sinaga says of Dropdown Sidebar Menu Responsive Bootstrap Navigation:

“Easy to implement, and many options available to customize the look and feel that suits my needs.”

2. TinyMCE Bootstrap Plugin

The TinyMCE Bootstrap Plugin is a Bootstrap toolbar for TinyMCE that allows you to extend TinyMCE functionality using any Bootstrap element, like buttons, icons, labels, pagination, etc.

TinyMCE Bootstrap Plugin

Main features:

  • 13 plugins in one
  • 13 visual editors
  • easy to install
  • multi-language
  • and more

User Enigmatic says of TinyMCE Bootstrap Plugin:

 “I immediately translated it to German and will most probably purchase additional licenses for some of my customers' projects. I think it will be a great help for content editors who aren't tech-savvy.”

3. Responsive Bootstrap Modal and Popup

Looking for a plugin to display your images beautifully? If so the Responsive Bootstrap Modal and Popup plugin will probably do the trick. The plugin features modals and popups with a pleasing variety of elements like an image gallery, sign-in, and subscribe and contact forms, as well as 20 stunning ready-to-use examples of various modals.

Responsive Bootstrap Modal and Popup

Main features:

  • built with Bootstrap 3.x
  • five colour schemes
  • 26 animation effects
  • YouTube, Vimeo and self-hosted video support
  • and more

User WaddoBrian says of Responsive Bootstrap Modal And Popup:

“Great product and well written. Fantastic, quick and detailed support. Just what you need.”

4. Flat - Responsive Bootstrap Menu

Flexible and highly customisable, the Flat - Responsive Bootstrap Menu plugin is a great choice for building your custom Bootstrap responsive menus. The plugin offers horizontal and sticky menu versions and five different colour schemes.

Flat - Responsive Bootstrap Menu

Main features:

  • 100% responsive layout
  • 12 column bootstrap grid system
  • dropdown with three style types
  • flat and gradient colour effects
  • and more

Flat - Responsive Bootstrap Menu is highly versatile and suitable for any type of website, template, or landing page.

5. Paradise Slider

The Paradise Slider plugin features a selection of beautiful sliders in a variety of styles like sliders with thumbnail navigation, multiple image sliders, full-screen slider, carousel video background and parallax slider, etc.

Paradise Slider

Main features:

  • 130 ready-to-use examples of different sliders
  • touch swipe enabled
  • controlled slide timing and duration functions
  • different types of sliding transition effects
  • and more

User Ravi Rajcoomar says of the Paradise Slider plugin:

“The last slider pack you will ever need. Easy to use, well documented and very high quality. Support is by far the best, very quick response.”

6. Flip Box

The Flip Box plugin is a super cool plugin that will surely add a little pizazz to your web pages. The plugin offers a simple and easy-to-customise flip animation for all sorts of content like features, blogs, profiles, images, question and answer, etc., without the need to customise any JavaScript code.

 Flip Box

Main features:

  • unlimited flip boxes
  • 12 flip box layouts
  • vertical and horizontal flip
  • uses Font Awesome icons
  • and much more!

With 12 layouts and effects and tons of customisable options, Flip Box is easy to integrate into any website.

7. Zlogin - Simple Login System with Bootstrap

The Zlogin - Simple Login System with Bootstrap plugin provides users with a simple, secured and easy-to-customise login and user management system that will integrate with your own website beautifully.

Zlogin

Main features:

  • advanced admin panel
  • high security script with advanced login system with tokens
  • Captcha integration from reCAPTCHA
  • welcome email and activation email
  • and more

Zlogin - Simple Login System with Bootstrap can also be used as a start point to build your own CMS with a private user area where visitors to your website have to be logged in to view page content.

8. Responsive Bootstrap Sidebar Navigation

Responsive Bootstrap Sidebar Navigation is ideal for those looking to add a bit more functionality to their sidebar. The plugin adds both horizontal and vertical navigation menus with four levels of submenus to your sidebar.

Responsive Bootstrap Sidebar Navigation

Main features:

  • Bootstrap 3+ based
  • sticky sidebar
  • modern application style navigation
  • drop down, push, shrink, and overlay menu effects
  • Font Awesome version 4.3
  • and more

User Reactiveflorence says of Responsive Bootstrap Sidebar Navigation:

“Great job, works perfect, clear code, ultra speedy support.”

9. DMSS - Bootstrap jQuery Style Switcher

Need to test different styles on your website? Try DMSS - Bootstrap jQuery Style Switcher for an easy way to see Drupal or WordPress Themes and HTML5 website or Joomla templates in as many styles as you want.

DMSS - Bootstrap jQuery Style Switcher

Main features:

  • Bootstrap 3.0
  • custom colour picker
  • custom cookie script
  • make unlimited styles
  • and more

DMSS - Bootstrap jQuery Style Switcher is easy to set up and use and a great way to create unlimited styles.

10. Responsive Bootstrap Portfolio and Lightbox

The Responsive Bootstrap Portfolio and Lightbox plugin allows you to show off your images to their best effect. The package contains different types of lightboxes and portfolios such as image and video galleries, carousels and sliders of different types, etc. and allows users to create two, three, four, five, or six column galleries easily.

Responsive Bootstrap Portfolio and Lightbox

Main features:

  • 18 lightboxes
  • 18 simple portfolios
  • 6 sliders and carousels
  • 3 background colour schemes
  • and more

User Mmeneguzzo says of Responsive Bootstrap Portfolio and Lightbox:

“Installing the lightbox was very easy and the documentation very easy to follow. This product is well worth the money and saves a lot of time in having to code something yourself.”

Conclusion

These plugins just scratch the surface of products available at Envato Market. So if none of them catch your fancy, there are plenty of other great options there to hold your interest.

And if you want to improve your JavaScript skills, check out the ever so useful free JavaScript tutorials we have on offer.

Tools for React Native Development

$
0
0

Tools, libraries, and services are an important part of every developer’s life, no matter which environment you’re developing for. And React Native is no exception. In this article, I’ll walk you through some of the best UI frameworks, libraries, components, development tools, and web services which will make you a happier and more productive React Native developer. 

Text Editors and IDEs

Visual Studio Code is a text editor which has built-in IntelliSense, debugging, and Git integration capabilities. What makes it really good for React Native development is its React Native tools extension. This allows you to execute React Native commands from the command palette, add IntelliSense for React Native APIs, and debug code within the editor itself. 

For more information regarding how to set up Visual Studio Code for React Native, check out this blog post: VSCode for React Native.

If you’re using Atom, you can install the Nuclide plugin. This plugin was specifically created for working with React Native, Flow, and Hack projects. It has a built-in debugger and element inspector with all the features you’re used to in Chrome Developer Tools. Flow support means that you get autocomplete, type-hinting, and code diagnostics out of the box. 

If you want to explore more IDE and editor options, check out this blog post on the Top 10 Editors for React Native.

Development Tools

Development tools have a wide scope, so I’ll be grouping each tool based on its focus:

  • SDK
  • code quality
  • testing
  • debugging

SDK

When it comes to SDKs for React Native, nothing beats Expo. Expo allows you to easily prototype an app without the need for Android Studio or Xcode. It includes a set of components and libraries to help you speed up your development. 

The Expo workflow consists of the following:

  1. Create a new project using create-react-native-app.
  2. Write the code in your favorite text editor.
  3. Run the app using the Expo client app. 

There’s no need to connect your phone to your computer. Simply scan the QR code on your terminal using the Expo client app, and it will automatically run your app. If you’re using Genymotion, Expo supports that too

The only disadvantage when using Expo is that you cannot include any custom package which uses the device’s native functionality. Expo already includes a number of commonly used native packages such as the Camera, Facebook, and Map. But if you need to use a package that they don’t already support, then you’ll have to "eject" your app. At that point your app will be as if it was created with react-native init, and you’ll also lose the ability to run it using the Expo client app.

Code Quality

Checking the quality of your code is important, and that is why tools like ESLint exist. In a nutshell, a linting tool allows you to be more consistent with your code by checking it against a style guide. An example of such a style guide is Airbnb’s JavaScript Style Guide which specifies rules on how JavaScript code should be written. The linting tool then checks your code against those rules to ensure that they've been followed. There’s also a style guide for React projects.

If you’re using Sublime Text, here’s a good tutorial on how you can configure it so that you can have real-time feedback on the quality of your code while you’re coding: Sublime Linting for React and ES6. If you’re using another editor or IDE, be sure to look for a corresponding plugin which uses ESLint.

If you want to add static typing to your project, you can use Flow. Flow adds static-typing on top of JavaScript without you having to make any changes to your existing codebase. This is because Flow tries to infer the type whenever possible. For new projects, though, it's recommended that you explicitly specify the type to reap the full benefits of using Flow.

To get started using Flow, here’s a tutorial on how you can set up Flow for your React Native projects.

Testing

Enzyme is a testing utility for React which allows you to assert, manipulate, and traverse your component’s output. It provides methods such as shallow() to "shallowly" render your components, find() to traverse the rendered component, and expect() to assert the props or the content rendered within the component.

You can follow this guide to Using enzyme to Test Components in React Native to make your React Native app testable with enzyme. If you’re new to enzyme, you can read this tutorial on Testing React Components with Enzyme and Mocha.

Debugging

Reactotron is a desktop app that allows you to debug React and React Native apps. Some of its key features include inspecting, modifying, and subscribing to the app state, tracking HTTP requests made through the app, benchmarking the app performance, and tracking errors. If you’re using Redux, you can even dispatch actions and track sagas from within Reactotron.

Boilerplates and UI Frameworks

Snowflake is a boilerplate for full-stack React Native development. It includes everything from the front-end to the back-end of the app. So if you just want a tool that can help you quickly get started then you might find Snowflake useful. You can read the notes for more information on what packages and tools are used to put it up.

Alternatively, you can use Ignite. It's a command-line tool which also includes a boilerplate, generators, style guide for UI components, API Testing Tool, and more. 

React Native already comes with UI components which you can use for user interaction. The problem is that they only have the most basic styling in order for each component to be distinguished for what it is (e.g. button, checkbox). If you want to add custom styles, you have to write your own CSS code. 

This is where NativeBase comes in. It allows your app to have a truly native look and feel by implementing the same design used in native Android (Material Design) and iOS (Human Interface Guidelines) apps. Out of the box, you get custom components such as Floating Action Buttons, Spinners, and best of all, form components.

Libraries and Components

React Native has a huge community behind it, so there are lots of libraries and components that you can use. We could spend all day talking about these, so to keep things brief, I’ll focus on the following areas:

  • navigation
  • state management
  • animations
  • commonly used components and libraries

Navigation

React Navigation allows you to easily implement navigation in your React Native apps through the use of its built-in navigators such as the Stack Navigator, Tab Navigator, and Drawer Navigator. That's not all, though: in addition to in-app navigation, it also includes deep linking, Redux integration, and web integration. This makes it a really robust library for implementing navigation.

State Management

MobX provides the functionality to update and manage the app state used by React. What makes it a good candidate for state management in React is its simplicity and testability. It also has a short learning curve, so things like async functions and computed values are already handled behind the scenes. 

For bigger and more complex applications, Redux is still recommended. This is because MobX is very liberal, not unlike Redux, which provides strict guidelines on how the state should be managed. So it's a wiser choice for bigger projects with more people working on them.

Animations

React Native already has an animation API built into it. In fact, there’s not just one, but two APIs for working with animation: Animated API and LayoutAnimation. Those two are very powerful but can be cumbersome, especially if all you want to do is apply basic animations such as moving an object up and down or making it bounce. In such cases, components like Animatable come in handy.

Commonly Used Components and Libraries

Here’s a list of components and libraries that are commonly used in React Native projects. These are compatible with both Android and iOS devices:

Web Services

You can build serverless apps and ease the deployment of your React Native apps by using web services. There are a plethora of web services out there, but I’ll focus on the following areas:

  • database
  • analytics
  • push notifications
  • code updates
  • continuous integration

Database

Realm is a real-time database with a focus on mobile apps. It includes features such as two-way data sync, offline-first capabilities, and data push. The Realm Mobile Database is open-source and cross-platform, which means that you can host the Realm Object Server on your own server and then use the Realm JavaScript library for free. 

Not all features are available in the developer edition, but in most use cases you should be fine with just the developer edition because it includes the core features such as the Object Database, Realtime Synchronization, and Authentication. Here's a comparison of what you get for each edition: Realm Products and Pricing.

If Realm is too much for your needs, you can always stick with the AsyncStorage API that comes with React Native.

Analytics

Fabric is an all-in-one service that allows you, among other things, to add analytics in your app. There’s Answers, which gives you real-time statistics on how your app is being used. This includes the number of active users, the session length, and retention rate. There’s also Crashlytics, which gives you powerful crash reporting capabilities. All of it happens in real time, and you can view it in Fabric’s real-time dashboard. You can use the Fabric library to easily set up Fabric for your React Native app.

If you’d rather stick with a tried and tested solution like Google Analytics, there’s also a library that allows you to do that.

Push Notifications

There’s really no competition when it comes to implementing push notifications in apps. Firebase Cloud Messaging (previously known as Google Cloud Messaging) allows you to send push notifications to both Android and iOS apps. You can use the react-native-fcm package to communicate with FCM from your app.

Code Updates

CodePush allows you to deploy code updates to mobile apps directly to the users’ devices. CodePush acts as a central repository where you can deploy changes to HTML, CSS, JavaScript, and assets such as images. The corresponding CodePush code in the app would then pull these changes. This is great for pushing bug fixes to the app without the need for uploading it in the app store and waiting for users to update the app. You can use this package to pull updates from CodePush within your React Native app.

Continuous Integration

Bitrise is a Continuous Delivery Service for mobile app development. It allows you to run your tests, build the app, and automatically push it to your users’ devices every time you deploy your code. 

Bitrise integrates with a bunch of services in every step of your development workflow. For example, when you push to your release branches on GitHub, Bitrise is notified of that push through webhooks. It will then begin running the tests. Once the tests pass, the build process begins. If it’s just a "soft release" (e.g. changes to the JavaScript code) then the changes can be deployed to the users through CodePush. But if there are changes to the native code (e.g. you added a Camera plugin), then Bitrise can also build an APK or IPA file and deploy it to Google Play or iTunes Connect.

Fastlane is a collection of tools that automate the build and release process for Android and iOS apps. For iOS, it handles tasks such as running your tests, generating screenshots, code signing, and releasing the app to the app store. It also includes beta testing tools such as Pilot and Boarding. Pilot allows you to upload your app to iTunes Connect and manage your TestFlight beta testers right from the command line. Boarding creates a signup page for TestFlight beta testers.

The tools are more geared towards iOS deployment, but you can also benefit if you’re deploying Android apps. Currently, there are only two tools available for Android deployment: Supply and Screengrab. 

Supply allows you to automate the uploading of assets such as the app icon, promo graphics, and screenshots of your app. It also allows you to update your existing apps on the Google Play Store. 

Screengrab, on the other hand, automates the generation of screenshots for multiple devices. Each screenshot can also be localized if your app supports multiple languages.

Conclusion

That’s it! In this article, you’ve learned about some of the tools, libraries, and services that you can use when developing React Native apps. What about you? What are your go-to tools when it comes to developing apps in React Native?

And while you're here, check out some of our other posts on React Native app development!

TypeScript for Beginners, Part 1: Getting Started

$
0
0

Let's start this tutorial with the question: "What is TypeScript?" 

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. As an analogy, if JavaScript were CSS then TypeScript would be SCSS. 

All the valid JavaScript code that you write is also valid TypeScript code. However, with TypeScript, you get to use static typing and the latest features that get compiled to plain JavaScript, which is supported by all browsers. TypeScript is aimed at solving the problem of making JavaScript scaleable, and it does a pretty good job. 

In this tutorial, you will begin by reading about different features of TypeScript and why learning it is a good idea. The rest of the sections in the article will cover the installation and compilation of TypeScript along with some popular text editors that offer you support for the TypeScript syntax and other important features.

Why Learn TypeScript?

If you have never used TypeScript before, you might be wondering why you should bother about learning it at all when it compiles to JavaScript in the end. 

Let me assure you that you won't have to spend a lot of time in learning TypeScript. Both TypeScript and JavaScript have very similar syntax, and you can just rename your .js files to .ts and start writing TypeScript code. Here are a few features that should convince you to start learning TypeScript:

  1. Unlike JavaScript, which is dynamically typed, TypeScript allows you to use static typing. This feature itself makes the code more maintainable and greatly reduces the chances of bugs that might have been caused due to incorrect assumptions about the type of certain variables. As an added bonus, TypeScript can determine the type of a variable based on its usage without you explicitly specifying a type. However, you should always specify the types for a variable explicitly for clarity.
  2. To be honest, JavaScript was not designed to serve as a large-scale development language. TypeScript adds all these missing features to JavaScript that make it truly scaleable. With static typing, the IDE that you are using will now be able to understand that code that you are writing in a better way. This gives the IDE the ability to provide features like code completion and safe refactoring. All this results in a better development experience.
  3. TypeScript also allows you to use all the latest JavaScript features in your code without worrying about browser support. Once you have written the code, you can compile it to plain old JavaScript supported by all browsers with ease.
  4. A lot of popular frameworks like Angular and Ionic are now using TypeScript. This means that if you ever decide to use any of the frameworks in future, learning TypeScript now is a good idea.

Installation

Before you start writing some awesome TypeScript code, you need to install TypeScript first. This can be done with the help of npm. If don't have npm installed, you will have to install npm first before installing TypeScript. To install TypeScript, you need to start the terminal and run the following command:

Once the installation is complete, you can check the TypeScript version that was installed by running the command tsc -v in your terminal. If everything was installed properly, you will see the installed TypeScript version number in the terminal.

IDEs and Text Editors With TypeScript Support

TypeScript was created by Microsoft. So the fact that Visual Studio was the first IDE to support TypeScript should not come as a surprise. Once TypeScript started gaining popularity, more and more editors and IDEs added support for this language either out of the box or through plugins. Another lightweight and open-source editor called Visual Studio Code, created by Microsoft, has built-in support for TypeScript. Similarly, WebStorm also has out-of-the-box support for TypeScript.

Microsoft has also created a free Sublime TypeScript Plugin. NetBeans has a TypeScript plugin that provides variety of features for ease of development. Syntax highlighting is available in Vim and Notepad++ with the help of the typescript-vim and notepadplus-typescript plugins respectively. 

You can see a full list of all the text editors and IDEs that support TypeScript on GitHub. For the examples in this series, I will be using Visual Studio Code to write all the code.

Compiling TypeScript to JavaScript

Let's say you have written some TypeScript code in a .ts file. Browsers won't be able to run this code by themselves. You will have to compile the TypeScript into plain JavaScript that can be understood by browsers. 

If are using an IDE, the code can be compiled to JavaScript in the IDE itself. For example, Visual Studio allows you to directly compile the TypeScript code to JavaScript. You will have to create a tsconfig.json file where you specify all the configuration options for compiling your TypeScript file to JavaScript. 

The most beginner-friendly approach when you are not working on a large project is to use the terminal itself. First, you have to move to the location of the TypeScript file in the terminal and then run the following command.

This will create a new file named first.js in the same location. Keep in mind that if you already had a file named first.js, it would be overwritten.

If you want to compile all the files inside the current directory, you can do so with the help of wildcards. Remember that this will not work recursively.

Finally, you can only compile some specific files by explicitly providing their names in a single line. In such cases, JavaScript files will be created with corresponding file names.

Let's take a look at the following program, which multiplies two numbers in TypeScript.

The TypeScript code above compiles to the following JavaScript code when the targeted version is set to ES6. Note how all the type information that you provided in TypeScript is now gone after the compilation. In other words, the code gets compiled to JavaScript that can be understood by the browser, but you get to do the development in a much better environment which can help you in catching a lot of bugs.

In the above code, we have specified the type of variables a and b as numbers. This means that if later you try to set the value of b to a string like "apple", TypeScript will show you an error that "apple" is not assignable to the type number. Your code will still compile to JavaScript, but this error message will let you know that you made a mistake and help you avoid a problem during runtime. 

Here is a screenshot that shows the error message in Visual Studio Code:

type error in TypeScript

The above example shows how TypeScript keeps giving you hints about possible errors in code. This was a very basic example, but when you are creating very large programs, messages like these go a long way in helping you write robust code with less chance of error.

Final Thoughts

This getting started tutorial in the series was meant to give you a very brief overview of different TypeScript features and help you install the language along with some suggestions for IDEs and text editors that you can use for development. The next section covered different ways of compiling your TypeScript code to JavaScript and showed you how TypeScript can help you avoid some common errors.

I hope you liked this tutorial. If you have any questions, please let me know in the comments. The next tutorial of the series will discuss different variable types available in TypeScript.

Testing a Node.js API

$
0
0

Introduction

Tests are important; they provide a safeguard for your applications or APIs. As beginners, it is possible to be oblivious of the need to write tests that cover the important parts of what you are building. Yet you will meet with it as you make progress as a developer.

In a previous tutorial, you learned how to build an API with Node.js. If you have not gone through it, I suggest you do so before continuing with this. In this tutorial, you will be writing tests for an API built using Node.js and Express. At the end of this tutorial, you will know how testing works in Node.js, and you will be able to build functional and tested APIs.

Testing Tools

You will be making use of Mocha, Expect, and Supertest.

Mocha is a JavaScript test framework which makes asynchronous testing simple and fun. Mocha comes with tons of great features which can be found on the website. You will be making use of a handful of them.

Expect is an assertion library that makes it easy for you to make better assertions. You will see how that works. Supertest provides a high-level abstraction for testing HTTP. This is needful as you will be testing an API.

Enough talk, time to write some code.

Project Setup

I have a to-do list project already set up for you. The model, config file, and part of the app.js are already done for you. Go over to GitHub and clone the repository. Or you can simply do:

Your package.json should look like this.

Now run the command to install the dependencies.

POST Request Test

For your test, create a new folder called test; this folder should be in your server directory. Now create a new file where you will write your test. Name the file server.test.js.

In this file, start by requiring the modules you installed. You also need to require your server file and your model.

You need to have a few to-dos that will be used during tests. But these to-dos will be deleted from the test database each time you run your test suite. To handle that, create two tests like so.

The before block cleans your Todo database, then inserts the to-dos set above. This ensures that you have a stable amount of entries in your database so your tests do not run into issues.

With that done, you can write the test for the POST request. For your POST request, you will write two tests. The first will make a request for a valid to-do and be successful. The second will make a request with an invalid body, and this should not create a new to-do.

Here is what the test should look like.

Run the test using the command:

It should fail. Here is what is happening:

  1. Describes the test.
  2. Creates a new to-do and saves it as a value to text.
  3. You make a POST request to the /todos path of your API, sending the to-do you created as the body of the request. You expect the status code for the request to be 200 and the body of the to-do to equal the value of text.
  4. An error is returned if there is any, and this will cause the request to end. Thus the next block of code will not run. If no error is encountered, the flow continues.
  5. A request is made to the database to find the created to-do. You expect the length of the to-dos in the database to be 1, and the text of the to-do to be equal to the value of text.
  6. This is the test made with invalid body data.
  7. A POST request is made to the /todos path. This time, you are sending a request with no body. You expect to get a 400 request. No need to check the body as you are not sending any. If an error is encountered, it gets returned and the code stops running.
  8. If no error is encountered, a request is made to the database to check the length of the to-dos. We expect that the database will contain only 2, which are the to-dos created at the beginning.

To get this test passing, go to your server.js file and drop in the code needed for the POST request.

GET Request Test

This is simple—the test should return the length of to-dos available in the database. As you already know, the length of the todos should be 2. Why? You guessed right. At the beginning of the test suite, you created a beforeEach block that cleans your database and inserts new to-dos each time the test suite is run.

To test that the request to get all to-dos works, here is the code for that.

In the above, you are making a GET request to the /todos path. This time, you are not passing anything as the body of the request because it is a GET request. You expect to get a response with the status code of 200. Then you expect that the length of the to-dos will be 2.

When you run the test, you should get an error. Try getting the error to pass on your own.

I bet you got that to work. Here is the code to get the test to pass; compare it with your solution.

When a GET request is made to the /todos path, you want to find every to-do in the Todo collection and return them as to-dos. Adding this to server.js causes the test to pass.

Next, you'll write three tests for the GET request made to retrieve individual to-dos. The first should retrieve and return the to-do. The second and third should return 404 error in cases where the to-do is not found.

Open up your server.test.js and create a new describe block with the first test case.

This test makes a GET request to retrieve the first to-do available in your database. You expect to get a 200 status code, and then check that the text value of the to-do is the same as the one created.

The next test looks like this.

Here you are looking for a to-do using an ID that does not correspond to the ID of any to-do saved in your database. The test expects this request to return a 404 error.

The last test is like the first but a little different; here is how it looks.

Here, you create an invalid ObjectId and try to query the database to get a to-do matching the ObjectId created. The test expects the request to return a 404 error. 

When you run the test, they should all fail. To get them to pass, add the code below to your server.js file.

  1. Get the ID of the to-do requested from the params.
  2. Check to see if the ID is valid. If the ID is not valid, an error stating this is sent.
  3. If the ID is valid, try to find a to-do that matches that ID using the findById method. If no to-do is found with that ID, a 404 error is sent.
  4. If a to-do is found, the to-do is sent. Then you catch any error that occurs and sends it.

Run the test command once more, and it should pass.

DELETE Request Test

The test for your DELETE request will be a little like what you have for your GET request.

First, you want to test that a to-do is deleted.

Here is what is happening above:

  1. You set the id of the to-do to a variable called hexId. Next, a DELETE request is made to the path of the to-do, using the ID. You expect to get a 200 response, and the to-do obtained to match the value of hexId.
  2. If any error is encountered, it is returned.
  3. If no error, the test goes further to query your database using the ID saved as the value of hexId. Since a DELETE request has been previously sent, the test expects that the to-do matching that ID does not exist.

Next, you want to test that when a request is made to delete a to-do that does not exist, the response contains a 404 error. It is important to have this, as it is not possible to delete a to-do twice. Here is how the test for this should look.

This creates an ID for a to-do that does not exist in the database. Then a DELETE request is made to delete the to-do. The test is expected to return a 404 error as the to-do does not exist.

You want to test that a DELETE using an invalid ID returns a 404 error, like so.

To get the test to pass, open your server.js and drop this.

Run the command to test:

And your tests should be passing.

Conclusion

At this point, you now know how to set up a test suite when building an API using Node.js. You have used Mocha, Expect, and Supertest to test an API. One advantage of doing this is that you do not need to always fire up Postman when building your API. With your test, you can get to know what is broken.

Before we wrap up, note that JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available on Envato Market.

Using what you now know, you are good to explore the world of testing.

New Course: PHP Fundamentals

$
0
0

Do you want a comprehensive introduction to PHP? Like seven-hour, 34-video comprehensive? Then try our new course, PHP Fundamentals.

What You’ll Learn

In this course, Envato Tuts+ instructor Jeremy McPeak will teach you the fundamentals of PHP. You'll start with the very basics, using variables and writing simple loops and functions, before building up to coding classes for simple object-oriented programming (OOP). 

Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Here are some free lessons from this course, as a preview of what you can expect:

PHP Syntax and Variables

Every language has its own syntax. In this video, you'll learn about the basics of PHP, and you'll see how to store data in memory by using variables.

 

Error Reporting in PHP

Error messages are important to developers—they tell us why and where something went wrong. By default, you won't see any PHP errors in the browser, so in this video you'll learn how to modify your PHP configuration to display error information.

 

Conditions and Decisions in PHP

Almost every application you write will need to make decisions and respond to certain conditions. You'll learn about conditions and decisions in this video.

 

Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 300,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Mobile Development Tools

$
0
0

Traditional desktop app development is dominated by large-scale software companies with huge workforces, sometimes scattered around the globe. However, the mobile app development industry is quite different. Its ecosystem has created a new breed of small-scale and highly efficient developers. Its dominant players are powered by innovation and efficiency, rather than by the number of heads on the payroll. Even an individual developer can produce a killer app that has millions of downloads in the app stores.

So how do these individuals or small teams of developers achieve such great results, without a large human workforce? It's because the mobile app ecosystem has a broad range of software tools that simplify the workflow and improve efficiency. There are tools that even guarantee certain types of functionality, up to certain standards.

In this post, you'll be exposed to various mobile development tools that enable you to make your app unique and stand out from the rest. With these tools, you can achieve success even without a large team of programmers.

1. General-Purpose Tools

These include Software Development Kits (SDKs) that make it possible to develop for a specific platform such as Android, iOS, and Windows. In addition, Integrated Development Environments (IDEs) that help streamline the workflow also fall into this category.

1.1 Native Platform SDKs

An SDK usually consists of compiled core sources, supporting software libraries and various other components such as documentation, sample apps, etc., that are designed to facilitate app development. Platform SDKs can be defined as the immediately usable form of the platform's source code.

Android SDK & NDK

You can download Android SDK from the Android Developer website's Downloads section, free of charge. You just need to download the SDK command-line tools package that matches your OS and use the SDK Manager included there to download the other packages. Then, you can use this SDK to develop apps with or without the help of an Integrated Development Environment (IDE).

Unlike the SDK, which facilitates Java-based development, Android Native Development Kit (NDK) enables developers to implement their apps in the C or C++ languages. This comes in handy, especially when external libraries written in C or C++ are used within your app. Also, this ensures the fastest performance and maximum utilization of the device's hardware features. Therefore, if performance is the main criterion, you'd be better off using Android NDK.

You can find a large collection of Android tutorials on Envato Tuts+ that can help you get up and running in a flash.

iOS SDK

Similar to the Android SDK, you can download the iOS SDK, free of charge, once you register for an Apple Developer Center Account. However, you can't run the apps developed using that on an Apple device, unless you join the paid iOS Developer Program. However, you can still run your app on an emulator and test if it works correctly. 

When you are ready to run your app on a real device, you can join the Developer Program and eventually publish the app on the App Store. If you need more help on iOS development, check out our iOS From Scratch series.

Windows 10 SDK

Microsoft has unified the app development process for different devices including PC, Mobile, Xbox One, and HoloLens, with its Universal Windows Platform (UWP). You can download the Windows 10 SDK (also supports UWP) from Microsoft Windows Dev Center and use it for developing mobile apps with other tools, such as mobile emulators, to test your app. 

When used together with UWP, the Windows 10 SDK allows you to port your existing Android, iOS and older Windows apps to the latest Windows 10 platform. This is really great because it enables developers to expand their reach and target the broadest possible range of devices. Windows Phone SDK tutorials on Envato Tuts+ could be a great place to look for expert help.

1.2 Complete IDEs

IDEs help streamline your workflow and get the maximum out of the SDKs. They also save developers a great deal of time with clever features such as code completion, interactive debugging, and automated building.

Android Studio

Android Studio is the IDE officially supported by Google for building Android apps. It's an all-in-one IDE featuring intelligent code completion, fast and realistic device emulation, and robust build systems. You can share the same code base across many devices, ranging from wearables, through phones, to smart TVs. 

The latest Android SDK is also bundled with Android Studio so that developers can start coding from day one. The older versions of the SDK can be downloaded via the SDK Manager included in the IDE. It's also full of sample apps, code templates, and project wizards that make life really easy for developers.

Xcode

If you are an iOS developer, you must get yourself familiar with Xcode, which includes the iOS SDK and a number of other useful tools. Similar to Android Studio, it's a productive environment for building apps for Mac, iPhone, iPad, and Apple Watch. Xcode's features include a powerful source-code editor, built-in interface builder, advanced device emulator, and complete, up-to-date documentation. 

Anyway, you don't have much choice, because it's mandatory to use the Xcode IDE if you plan to publish your iOS apps to Apple's App Store. Xcode handles all the app signing and developer-key management, plus the verification process for app submission, so that developers can focus more on their core business rather than worrying about their apps' administrative overheads.

Visual Studio

Visual Studio is the IDE of choice for Windows developers. It's from Microsoft, and therefore, you'll get the full support that you'd expect from the official vendor. With Visual Studio, you can use the same code base for desktop apps, mobile apps, and other Microsoft device-based apps. 

Naturally, the Windows 10 SDK is bundled with the IDE, as in the case of Android Studio and Xcode. Visual Studio makes it easy for developers to find their way around a large code base with features such as Peek To Definition, improved GoTo, and more. Depending on your capacity and budget, you can select from three versions, namely Community, Professional, and Enterprise. Also, Visual Studio comes with two OS flavors, Windows and Mac. So it doesn't matter whether you own a PC or a Mac; you can use Visual Studio to code your next mobile app.

Not only that, but Visual Studio Code is a great IDE for coding cross-platform apps in JavaScript—for React Native, for example. Visual Studio Code is especially good for React Native development with the React Native tools extension. With that, you can run React Native commands from the GUI, view smart code completion prompts for React Native APIs, and even debug your apps from within the editor.

2. Special-Purpose Tools

These are the tools that enable your app to have a competitive advantage. That's really what it takes to build a killer app or a niche market. Here, you'll read about the most popular ones.

2.1 Game Engines

Mobile games are the most popular app category, in terms of download volume, on almost all the app stores. So, if you're planning to develop a mobile game, why not try one of these game engines?

Unity

Unity is a popular game development tool that can be used for creating a compelling user experience. Its features include an all-in-one editor, 2D and 3D workflow support, realistic physics engine, built-in UI creation components, and a lot more. Based on the size of your game development studio, you can choose a suitable version from Personal, Plus, or Pro. 

Unity allows you to maintain a single code base and publish to multiple platforms such as Android, iOS, and Windows Phone. Unity is essentially packed with tons of features such as 360 panoramic video support, cinematic VR, and photo- or video-based asset creation. It even has its own mobile app monetization platform with Unity Ads.

Godot

Released under the MIT license, Godot is a free and open-source game creation tool that enables you to publish 2D and 3D games to all the popular mobile platforms. You can write your programs either with its default scripting language called GDScript or in the C++ language. It also has a nice visual editor with an uncluttered UI. What's really interesting is that it supports live editing on mobile devices too.

libGDX

libGDX is a game engine with multiple publishing targets including Android and iOS. It's released under the Apache 2.0 license and maintained by an active community of talented developers. It also comes with a large collection of books and tutorials, so that it's really easy for you to get started and continue.

2.2 Computer Vision SDKs

Computer vision has made remarkable progress since its early days of conception. Now it's become such a commodity that there are thousands of apps that use some form of computer vision. The availability of the built-in camera has made computer vision-based mobile apps a widespread type of software.

IBM Watson

IBM Watson is a cloud-based suite of machine-learning tools. With its Visual Recognition service, detecting and analyzing images from a smartphone app is actually quite easy. Check out some of our Watson tutorials here on Envato Tuts+. You can even use it to guess a person's age and gender from a photograph.

Google Cloud Vision

Google Cloud Vision is another cloud-based machine learning platform that makes computer vision easier. Through the Cloud Vision REST API, Google shares its deep learning AI technology with app developers everywhere. With this API, you can easily add features such as face detection, emotion detection, and optical character recognition to your Android apps. In this tutorial, you'll learn how.

OpenCV

OpenCV was one of the early adopters of computer vision technology, and today it's one of the leaders in the field. There are several other projects, some open source, and other commercial ones, based on OpenCV. It's available for Android, iOS, and Windows platforms. In Android, you'll need Android NDK to use it. 

OpenCV itself is written in C++, and you'll need to brush up your C++ skills if you intend to write programs using the SDK. You'll be able to add a wide range of computer vision based features to your app using OpenCV. They include face recognition, eye tracking and gaze estimation, object recognition, and a lot more related to both still images and videos. OpenCV is released under the BSD license and is completely free to use.

Qualcomm FastCV

Released by Qualcomm Technologies Inc., FastCV is another popular computer vision based SDK. It supports features like gesture recognition, face detection, tracking, and text recognition. Although FastCV can perform reasonably well on most ARM-based processors, it's specifically designed for Qualcomm Snapdragon processors. A high-end processor is needed to fully utilize FastCV's capabilities.

2.3 Augmented Reality (AR) SDKs

AR is slowly gaining traction and becoming more of a day-to-day mobile experience, thanks to some state-of-the-art SDKs and enthusiastic developer communities. Here are some of the leaders and trendsetters in the industry.

Vuforia

Vuforia is a widely used mobile AR platform that can support a broad range of Android, iOS, and Windows smartphones and tablets. It helps you create memorable AR experiences in mobile apps, so that those apps can stand out from the rest. 

Vuforia can cater to a variety of AR use cases such as print media and magazines, toys and consumer products, boxes and product packaging, and even bottles and cans. It also supports object recognition and object tracking and enables developers to create AR and VR apps by using its Mixed Reality API. You can choose from four available pricing plans depending on your requirements.

Wikitude

Another serious player in the field, Wikitude combines mobile geo-location with other standard AR features. So it must be another essential tool for any aspiring developer who wants to produce really cool mobile AR apps. The SDK comes with different options for licensing, such as a one-time fee and yearly subscription-based models. 

Wikitude can currently deploy to Android and iOS mobile targets. Its community is also full of seasoned developers who are ready to share their knowledge, and hence you could take a shortcut to accelerate your development efforts to full speed.

Tango

Tango is an AR SDK developed by Google. It currently supports only two specific device models, namely Asus ZenFone AR and Lenovo Phab 2 Pro. So, if you are interested in specifically developing for any of those devices, Tango is worth considering.

ARKit

ARKit is the AR platform of Apple. You'll need to get Xcode 9, in which ARKit is included as part of the iOS 11 SDK. So, if you don't want to mess up with third-party tools and prefer to focus only on official Apple tools, ARKit is ideal for you.

Stay tuned to Envato Tuts+ for courses and tutorials about ARKit!

3. Hybrid Development Tools

Some novice developers are intimidated by the steep learning curve normally associated with native mobile development platforms. They might have to learn new programming languages and acquire platform-specific development skills, such as mastering the testing tools. 

Hybrid development tools address this issue in a clever manner. They enable developers with web development skills to develop mobile apps—without needing platform-specific knowledge. There are many such platforms available, but we'll focus only on a few popular ones.

React Native

React Native is a mobile development platform released by Facebook. It allows developers to publish native mobile apps using HTML, CSS, and JavaScript. You can maintain a single code base and publish your app on the Android or iOS platforms. 

It's wonderful since you don't have to install Android Studio or Xcode on your development machine. And the real fun begins when you switch to native code within the React Native code editor itself. You can mix code snippets from several native platforms in the same code editor, and that makes you really powerful and versatile.

Ionic

Ionic is another framework that lets you build mobile apps with HTML, CSS, and JavaScript. It comes out of the gate with a library of UI components and lots of handy utilities that let you code beautiful mobile apps. Ionic is built on top of the very popular Angular framework, so if you have experience with Angular, you'll find Ionic a snap.

NativeScript

NativeScript is another framework for building cross-platform mobile apps. Like Ionic and React Native, it allows you to use CSS and JavaScript to build mobile apps, but instead of HTML you code your app layouts in XML. 

NativeScript can target Android, iOS, and even the Windows Universal Platform. Unlike Ionic, which uses Cordova's WebView for rendering the UI of the app, NativeScript uses the native platform's rendering engine, which means that it provides a truly native user experience. 

Adobe PhoneGap

PhoneGap was one of the pioneers of HTML-based hybrid mobile development frameworks. Since being acquired by Adobe in 2011, it's just gotten better and better. 

The quickest way to get started is to download the PhoneGap desktop app and dive into coding. You can emulate apps in your browser, and you can also perform live testing on connected devices, using the PhoneGap Developer Mobile App. It can serve all the three popular platforms: Android, iOS, and Windows Phone. 

If you encounter a problem while writing your app, there are thousands of posts and articles on the web that will help you fix the issues. PhoneGap has a thriving community of developers who are really knowledgeable and helpful.

Xamarin

Xamarin is another hybrid mobile development tool, but it's based on C#, instead of HTML. So, if you are coming from a Microsoft development background and want to develop cross-platform mobile apps, it's an ideal choice. You'll also need Visual Studio IDE when you develop mobile apps with Xamarin.

Conclusion

The availability of the right tools and the ability to use them correctly are the key success factors of mobile app development. So, when you plan to develop your next app, give these tools a try. 

TypeScript for Beginners, Part 2: Basic Data Types

$
0
0

After reading the introductory TypeScript tutorial, you should now be able to write your own TypeScript code in an IDE that supports it and then compile it to JavaScript. In this tutorial, you will learn about different kinds of data types available in TypeScript.

JavaScript has seven different data types: Null, Undefined, Boolean, Number, String, Symbol (introduced in ES6), and Object. TypeScript defines a few more types, and all of them will be covered in detail in this tutorial.

The Null Data Type

Just as in JavaScript, the null data type in TypeScript can have only one valid value: null. A null variable cannot contain other data types like number and string. Setting a variable to null will erase its content if it had any. 

Remember that when the strictNullChecks flag is set to true in tsconfig.json, only the value null is assignable to variables with null type. This flag is turned off by default, which means that you can also assign the null value to variables with other types like number or void.

The Undefined Data Type

Any variable whose value you have not specified is set to undefined. However, you can also explicitly set the type of a variable to undefined, as in the following example. 

Keep in mind that a variable with type set to undefined can only have undefined as its value. If the strictNullChecks option is set to false, you will also be able to assign undefined to variables with number and string types, etc.

The Void Data Type

The void data type is used to signify the lack of a type for a variable. Setting variables to have a void type may not be very useful, but you can set the return type of functions that don't return anything to void. When used with variables, the type void can only have two valid values: null and undefined.

The Boolean Data Type

Unlike the number and string data types, boolean only has two valid values. You can only set its value to either true or false. These values are used a lot in control structures where one piece of code is executed if a condition is true and another piece of code is executed if a condition is false

Here is a very basic example of declaring Boolean variables:

The Number Data Type

The number data type is used to represent both integers and floating-point values in JavaScript as well as TypeScript. However, you should remember that all numbers are internally represented as floating-point values. Numbers can also be specified as Hexadecimal, Octal or Binary literals. Keep in mind that Octal and Binary representations were introduced in ES6, and this can result in different JavaScript code output based on the version you are targeting. 

There are also three additional special symbolic values that fall under the number type:  +Infinity-Infinity, and NaN. Here are a few examples of using the number type.

When the target version is set to ES6, the above code will compile to the following JavaScript:

You should note that the JavaScript variables are still declared using let, which was introduced in ES6. You also don't see any error messages related to the type of different variables because the JavaScript code has no knowledge of the types we used in the TypeScript code.

If the target version is set to ES5, the TypeScript code we wrote earlier will compile to following JavaScript:

As you can see, this time all the occurrences of the let keyword have been changed to var. Also note that the octal and binary numbers have been changed to their decimal forms.

The String Data Type

The string data type is used to store textual information. Both JavaScript and TypeScript use double quotes (") as well as single quotes (') to surround your textual information as a string. A string can contain zero or more characters enclosed within quotes.

TypeScript also supports template strings or template literals. These template literals allow you to embed expressions in a string. Template literals are enclosed by the back-tick character (`) instead of double quotes and single quotes that enclose regular strings. They were introduced in ES6. This means that you will get different JavaScript output based on the version that you are targeting. Here is an example of using template literals in TypeScript:

Upon compilation, you will get the following JavaScript:

As you can see, the template literal was changed to a regular string in ES5. This example shows how TypeScript makes it possible for you to use all the latest JavaScript features without worrying about compatibility.

The Array and Tuple Data Types

You can define array types in two different ways in JavaScript. In the first method, you specify the type of array elements followed by [] which denotes an array of that type. Another method is to use the generic array type Array<elemType>. The following example shows how to create arrays with both these methods. Specifying null or undefined as one of the elements will produce errors when the strictNullChecks flag is true.

The tuple data type allows you to create an array where the type of a fixed number of elements is known in advance. The type of the rest of the elements can only be one of the types that you have already specified for the tuple. Here is an example that will make it clearer:

For all the tuples in our example, we have set the type of the first element to a number and the type of the second element to a string. Since we have only specified a type for the first two elements, the rest of them can be either a string or a number. Creating tuples b and c results in an error because we tried to use a string as a value for the first element when we had mentioned that the first element would be a number.

Similarly, we can't set the value of a tuple element to false after specifying that it will only contain strings and numbers. That's why the last line results in an error.

The Enum Data Type

The enum data type is present in many programming languages like C and Java. It has been missing from JavaScript, but TypeScript allows you to create and work with enums. If you don't know what enums are, they allow you to create a collection of related values using memorable names.

By default, the numbering of enums starts at 0, but you can also set a different value for the first or any other members manually. This will change the value of all the members following them by increasing their value by 1. You can also set all the values manually in an enum.

Unlike the previous example, the value of Animals[3] is undefined this time. This is because the value 3 would have been assigned to dog, but we explicitly set its value to 11. The value for cow stays at 12 and not 3 because the value is supposed to be one greater than the value of the last member.

The Any and Never Types

Let's say you are writing a program where the value of a variable is determined by the users or the code written in a third-party library. In this case, you won't be able to set the type of that variable correctly. The variable could be of any type like a string, number, or boolean. This problem can be solved by using the any type. This is also useful when you are creating arrays with elements of mixed types.

In the above code, we were able to assign a number to b and then change its value to a string without getting any error because the type any can accept all types of values.

The never type is used to represent values that are never supposed to occur. For example, you can assign never as the return type of a function that never returns. This can happen when a function always throws an error or when it is stuck in an infinite loop.

Final Thoughts

This tutorial introduced you to all the types that are available in TypeScript. We learned how assigning a different type of value to a variable will show errors in TypeScript. This checking can help you avoid a lot of errors when writing large programs. We also learned how to target different versions of JavaScript.

If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

In the next tutorial, you will learn about interfaces in TypeScript. If you have any questions related to this tutorial, let me know in the comments.


Building With Vue.js 2 and Firebase

$
0
0

Introduction

Firebase is Google's mobile platform that helps you develop high-quality apps and grow your business. In this tutorial, you will make good use of one of Firebase's awesome features: the Realtime Database. 

You will build a single page application to create books. This book will be saved to your Firebase database, and you will be able to retrieve and delete books you have created.

Let's get started.

Set Up Firebase

Go to Google's Firebase page to create a new account. When done with that, log in to your console. Click on the option to add a project. Enter your project details and click on the button CREATE PROJECT.

This will lead you to your console. The Firebase console helps you manage your Firebase configuration settings.

For this tutorial, you'll need to make access to your database public. From the panel on the left, select Database. Select Realtime Database from the options that show next by clicking GET STARTED. Making your database public involves editing the rules. So click RULES on the page that loads next.

Make your rules look like this.

Click the option to PUBLISH when done.

With this rule, authentication is not required to perform read and write actions on your database. This is needful for the application you will be building in this tutorial.

Set Up a Project Using Vue CLI

Vue CLI allows you to scaffold Vue.js projects. If you do not have it on your machine, you can get it by running:

This will install it globally on your machine. Here is how Vue-CLI is used.

To learn more about Vue-CLI, check the GitHub page.

For this project you will use webpack templates, so run the command below from your terminal.

These are the installation options I used.

Navigate to your project folder. The files and folders generated by Vue-CLI have a tree like this.

Now run the command to install your dependencies.

When done, you can start your dev server by running:

Add Firebase to the Project

To bind Firebase data to Vue.js data properties, we will make use of the VueFire library. You can check more about it on GitHub.

Run the command below:

Open up main.js to add VueFire. Make your main.js file look like what I have below.

Set Up the Firebase Connection

Go to your Firebase console, and click on the Overview link on the left panel. Select the option to add Firebase to your web app. Copy the snippet that pops up in the window to a text file. The snippet contains your apiKey, authDomain, databaseURL, projectId, storageBucket, and messagingSenderId. You need these details to be able to access your Firebase database.

You start by importing Firebase from the core Firebase library. A Firebase instance is created using the initializeApp method. The snippet you copied has to be passed to this method as an object. This has to be done in the script section of your App.vue, like this.

After creating the Firebase instance, the database reference is obtained by using app.database().

Book Listing

Since VueFire makes it easy to bind Vue.js data properties to Firebase, implementing the books listing feature requires you to add this.

You add that below:

Now you have access to the book items from your database. The template will look like this.

The v-for directive is used to iterate through the available books. Each book will be outputted in a new table row.

Adding a New Book

To put in place the addition of new books, you need to first define the data model that will be used.

Next, set up the template to look like this.

The v-model directive is used to bind the newBook properties to the corresponding input.

The v-on directive will lead us to create an event handler method that gets called whenever a new book is to be created. Here is what the event handler should look like.

The addBook method helps insert new book objects into the Firebase database. The data is also synced across all clients. 

Deleting Books

Let's add the ability to delete books. Add another column to the book listing.

Let's put in place a method that gets called each time the button is clicked. The method is passed the book you intend to delete, which is actually the key to the book, as you will see soon. The remove() is called on the returned book to delete it from the database.

Here is what the method looks like.

With that, you are done with App.vue. Putting everything together, here is how your App.vue file should look.

In the template, I added some Bootstrap classes. For these to work, open your index.html file and make it look like this.

Conclusion

JavaScript has become extremely popular and is now capable of building mature applications (as we've seen above). If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato Market.

In this tutorial, you learned about Firebase. You were able to connect Vue.js and Firebase using VueFire. Your application can make read and write requests to your Firebase database.

You can go further by adding more features like categories and description.

TypeScript for Beginners, Part 3: Interfaces

$
0
0

We began this series with an introductory tutorial that introduced you to different TypeScript features. It also taught you how to install TypeScript and suggested some IDEs that you can use to write and compile your own TypeScript code. 

In the second tutorial, we covered different data types available in TypeScript and how using them can help you avoid a lot of errors. Assigning a data type like a string to a particular variable tells TypeScript that you only want to assign a string to it. Relying on this information, TypeScript can point it out to you later when you try to perform an operation that is not supposed to be done on strings.

In this tutorial, you will learn about interfaces in TypeScript. With interfaces, you can go one step further and define the structure or type of more complex objects in your code. Just like simple variable types, these objects will also have to follow a set of rules created by you. This can help you write code more confidently, with less chance of error.

Creating Our First Interface

Let's say you have a lake object in your code, and you use it to store information about some of the largest lakes by area around the world. This lake object will have properties like the name of the lake, its area, length, depth, and the countries in which that lake exists.

The names of the lakes will be stored as a string. The lengths of these lakes will be in kilometers, and the areas will be in square kilometers, but both of these properties will be stored as numbers. The depths of the lakes will be in meters, and this could also be a float. 

Since all these lakes are very large, their shorelines are generally not limited to a single country. We will be using an array of strings to store the names of all the countries on the shoreline of a particular lake. A Boolean can be used to specify if the lake is salt water or fresh water. The following code snippet creates an interface for our lake object.

The Lakes interface contains the type of each property that we are going to use while creating our lake objects. If you now try to assign different types of values to any of these properties, you will get an error. Here is an example that stores information about our first lake.

As you can see, the order in which you assign a value to these properties does not matter. However, you cannot omit a value. You will have to assign a value to every property in order to avoid errors while compiling the code. 

This way, TypeScript makes sure that you did not miss any of the required values by mistake. Here is an example where we forgot to assign the value of the depth property for a lake.

The screenshot below shows the error message in Visual Studio Code after we forgot to specify the depth. As you can see, the error clearly points out that we are missing the depth property for our lake object.

Missing Property Values in TypeScript Interface

Making Interface Properties Optional

Sometimes, you might need a property only for some specific objects. For example, let's say you want to add a property to specify the months in which a lake is frozen. If you add the property directly to the interface, as we have done until now, you will get an error for other lakes that do not freeze and therefore have no frozen property. Similarly, if you add that property to lakes that are frozen but not in the interface declaration, you will still get an error.

In such cases, you can add a question mark (?) after the name of a property to set it as optional in the interface declaration. This way, you will not get an error for either missing properties or unknown properties. The following example should make it clear.

Using Index Signatures

Optional properties are useful when quite a few of your objects are going to use them. However, what if each lake also had its own unique set of properties like economic activities, the population of different kinds of flora and fauna flourishing in that lake, or the settlements around the lake? Adding so many different properties inside the declaration of the interface itself and making them optional is not ideal.

As a solution, TypeScript allows you to add extra properties to specific objects with the help of index signatures. Adding an index signature to the interface declaration allows you to specify any number of properties for different objects that you are creating. You need to make the following changes to the interface. 

In this example, I have used an index signature to add information about different settlements around the lakes. Since each lake will have its own settlements, using optional properties would not have been a good idea.

As another example, let's say you are creating a game with different kinds of enemies. All these enemies will have some common properties like their size and health. These properties can be included in the interface declaration directly. If each category of these enemies has a unique set of weapons, those weapons can be included with the help of an index signature.

Read-Only Properties

When working with different objects, you may need to work with properties that should only be modified when we first create the object. You can mark these properties as readonly in the interface declaration. This is similar to using the const keyword, but const is supposed to be used with variables, while readonly is meant for properties.

TypeScript also allows you to make arrays read-only by using ReadonlyArray<T>. Creating a read-only array will result in the removal of all the mutating methods from it. This is done to make sure that you cannot change the value of individual elements later. Here is an example of using read-only properties and arrays in interface declarations.

Functions and Interfaces

You can also use interfaces to describe a function type. This requires you to give the function a call signature with its parameter list and return type. You also need to provide both a name and a type for each of the parameters. Here is an example:

In the above code, we have declared a function interface and used it to define a function that subtracts the damage dealt to a tank from its health. As you can see, you don't have to use the same name for parameters in the interface declaration and the definition for the code to work.

Final Thoughts

This tutorial introduced you to interfaces and how you can use them to make sure you are writing more robust code. You should now be able to create your own interfaces with optional and read-only properties. 

You also learned how to use index signatures to add a variety of other properties to an object that are not included in the interface declaration. This tutorial was meant to get you started with interfaces in TypeScript, and you can read more on this topic in the official documentation.

In the next tutorial, you will learn about classes in TypeScript. If you have any questions related to interfaces, let me know in the comments.

Updating Your App for iOS 11

$
0
0
Final product image
What You'll Be Creating

In addition to feature development and bug fixes, iOS developers have to keep tabs on what’s announced yearly at WWDC. Amidst the notable new SDKs announced, there are some changes that iOS devs will need to roll out to keep their apps platform-compliant.

With Swift having evolved to version 4, along with improvements and changes coming to the iOS SDK itself, developers need to sift through the changes and devise a strategy for updating their code bases. All without breaking any of their existing features and functionalities! It all comes down to prioritization for your project: what is the minimum you need to do in order to make your app iOS 11 compliant? What is the easiest case you can make to your project stakeholder or project manager?

Vital features come first, and next come the nice-to-have but not required improvements that iOS 11 brings, from optimizing your application to the visual aesthetics that will further enrich the interaction and functionality of your app. With that in mind, this tutorial will guide you through the steps to take to upgrade your app, taking a pragmatic approach to required and optional improvements. 

Objectives of This Tutorial

This article will provide you with an overview of the changes that will be required in order to update your app for iOS 11, from architectural to visual changes as well as App Store publishing changes. Moreover, this tutorial will organize the sections starting from the required changes needed and the scope and effort required, to the nice but not necessary features that will enhance your app as a result of iOS 11. 

In this tutorial we will be covering the following:

  • preparing your app (and yourself) for iOS 11
  • architectural changes
  • App Store publishing changes
  • UI changes

Assumed Knowledge

This tutorial assumes an intermediate knowledge of Swift or Objective-C and Xcode, as well as familiarity with core iOS SDKs (e.g. UIKit and Core Foundation).

Architectural Changes

As with every iteration of iOS, the most important changes usually are the architectural ones. With iOS 11, this involves migrating to Swift 4, so updating the build settings for Xcode 9 will be the first task we'll look at. 

Incremental Migrating to Swift 4 

Important | Required

For those who had to migrate from Swift 2 to 3 last year, that process was extremely painful, and a lot of the changes broke the existing codebase. Thankfully, this isn’t the case moving from Swift 3.2 to 4, as most of the chances are considered additive, rather than deprecating, and as a result the Xcode 9 migration tool performs an admirable job of transitioning your code to the latest Swift.

Moreover, unlike in previous versions, you are not going to be forced to do the upgrade to 4 in one go. That is, Xcode projects simultaneously support both Swift 4 and Swift 3.2, which means that you can have one target in your project compile under Swift 3.2 and another compile in Swift 4. The migration tool will let you know which classes and functions it successfully migrated, and which ones will require your manual intervention to resolve, in the form of errors or warnings. 

The errors mean you will need to fix something that isn’t backward-compatible, whereas many of the warnings will indicate that there is a new way in Swift 4 of doing something, such as new API changes. Fix the errors, and prioritize the aforementioned warnings as a separate task. 

To access the migration tool, go to Edit > Convert > To Current Swift Syntax in Xcode, and follow the prompts, selecting the target(s) you wish to migrate at this stage. 

The Xcode Migration Tool modal prompt screen

The migration tool will let you know the minimum work that you will need to do in order to recompile your app, and therefore it should come as no surprise that the recommended best practice is to work on migrating your app from 3 to 4 incrementally, especially in large projects, testing and converting target by target. You won’t have to migrate everything at once, and you can plan your migration path in stages, where and when needed. 

We will next take a quick look at what the changes are in Swift 4 that are not mandatory to implement, but good to know. 

32-Bit Architectural Deprecation

Important | Required

Another major change in iOS 11 is that all apps in the App Store now have to be 64-bit, as 32-bit apps are no longer supported, and as a matter of fact don’t even work on devices running iOS 11. This shouldn’t come as a surprise as Apple have been warning developers for quite a while, but in case your app has still not made its transition, you can follow Apple’s guidelines on Converting Your App to a 64-bit Binary.

What’s New in Swift 4

Not Important | Optional

Beyond the mandatory work needed in order to get your target to become Swift 4 compliant, you have the option of refactoring your existing code to leverage the new Swift API changes, which are broken down according to the following API-level improvements:

Strings

String has received a lot of attention in Swift 4, with the most notable change being a reversion back to Swift 1.0 where Strings are once again defined as collections, so you can iterate over a String object character by character (SE-0163) using a for loop. Other notable changes to the Strings class include: 

Collections

Dictionaries and sets, as part of collections, have also been revamped in Swift 4, starting with the filtering of dictionaries, which until now returned an array of tuples consisting of key/value pairs. To access a specific element, you would use the following subscript, as in an array:

In Swift 4, you get back a dictionary instead, providing a more consistent syntax, and subsequently, you access the returned dictionary as you would a normal dictionary. The same now occurs for the map() function, where you also get back a dictionary. New to dictionary-access subscripts, you can provide a default value in case the key doesn’t exist, making your code safer.

The rest of the changes for collections include:

Other Notable Changes

Finally, there are some miscellaneous changes worth noting as part of this release pertaining to the language: 

You can find the exhaustive list of changes and original proposals at Swift.org.

App Store Publishing Changes

iOS 11 users of the App Store would have already noticed that it is sporting a completely new design with whole new sections, providing developers with new ways in which they can promote their apps and communicate with their users.

The new App Store Today Screen source Apple

We will start off by taking a look at the new marketing icon that you will now be required to upload with your app updates.

Marketing Icon

Mandatory | Higher Priority

As of iOS 11, for any new submissions, whether your app is new or an existing one, you will need to include an icon-1024.png—a 1024x1024 sized marketing icon. Conveniently enough, you won’t need to submit the icon via iTunes Connect, but through Xcode, bygoing to Images.xcassets and adding the appropriately sized image, the same way you manage your other icons:

You add the Marketing Icon in Xcode

The marketing icon is used as part of the new App Store design process, to show a larger image icon representing your app in the Today section, or other sections where the app graphic is enlarged. 

Promoting In-App Purchases

Optional | Lower Priority

Apple has made the process of in-app purchases more prominent and transparent, allowing users to view all the in-app purchasing options directly via the same level as the app product display, and in fact, even initiate an in-app purchase for the app whilst downloading the actual app. Think of a subscription app where users who download your app may already want to purchase their subscription. iOS 11 makes this quicker and more convenient. 

As of iOS 11, developers are able to promote up to 20 in-app purchases such as subscriptions on their app’s product page. These purchase options will also appear in search results. 

Promoting in-app purchases can also encourage downloads of your app. When a user doesn’t have your app installed but wants to buy a promoted in-app purchase, they'll receive a prompt to download the app first. Once the app is downloaded, the transaction will continue in the app. (Apple)

Marketing in-app purchases more visibly in the App Store source Apple

To enable greater in-app purchase promotion visibility, in iTunes Connect you will need to include the following metadata: 

  • Image: This is the unique promotional image representing your in-app purchase, appearing on your App Store product page, Today, Games, and Apps tabs, as well as other prominent areas. This should not consist of a screenshot or represent your app’s icon, but rather represent what the in-app purchase does. The image should also be in PNG format, and high quality with dimensions of 1024 x 1024.
  • Name: The display name of the in-app purchase, consisting of a maximum of 30 characters. This should be specific, befitting the function of that specific in-app purchase. If it is a subscription, say so, and ensure the duration of the subscription is included in the title, such as “One Month All-Access Subscription”.
  • Description: 45 characters long, descriptions provide context for the users to understand and appreciate the benefits of your specific in-app offering. 

For more information on promoting your in-app purchase, refer to Apple’s official guidelines as well as Apple’s Product Page guidelines.

Communicating With Your Customers

Optional | Lower Priority

Something that is definitely long overdue, and Android developers have enjoyed for quite some time, is the ability to respond directly to user comments. As of iOS 11, developers can now also directly respond to their users’ reviews and comments. While this doesn’t require any technical changes and participation is optional, developers through iTunes Connect (App > Activity > Ratings) can respond to praise as well as criticism.

Developers can now respond to comments and reviews in the App Store source Apple

Individualized developer responses can be leveraged in order to build stronger and more intimate relationships, fostering deeper engagement, by showing that their feedback is being reviewed and responded to, and issues they raised are actively being listened to. To respond to comments, simply go to iTunes Connect where you can view the feedback and respond individually. 

Besides the new developer comments feature, Apple have also provided a new formalized SDK to prompt users to rate and review apps. The new SKStoreReviewController should be used instead of any third party or manual prompting of users for reviews, because Apple wants the operating system to be able to control the frequency of the prompts as well as their visual appearance. Apple will thus constrain prompts to no more than three times in a 365-day period. 

To implement SKStoreReviewController, simply import StoreKit and call requestReview() as shown below:

While Apple hasn’t outright banned the other methods of prompting users for feedback, expect this to change in the near future, so it's best that you start thinking of implementing Apple’s prompt-to-review engine over the next year.

Refer to Apple’s Ratings, Reviews and Responses guidelines for more information. 

Incremental Rollouts

Optional | Lower Priority

Another very useful feature iOS 11 brings to developers is the ability to release their apps to users incrementally. Apple calls this phased releasing, and it's intended to reduce the risk of overloading the production environment all at once, instead rolling out the release updates over a seven-day period. 

Developers can now roll-out an app in phases over a 7-day period

Under Version Release in iTunes Connect, there is a new section called Phased Release for Automatic Updates, which gives you the option of either releasing immediately or over the seven-day period. Developers are also able to halt the phased roll-out for up to 30 days, which would normally happen if a major issue is discovered and reported.

A chart demonstrating the percentage of users receiving the app split over a 7-day period

The phased roll-out doesn’t prevent users from getting the update manually from the App Store, but rather is targeted at users who use the iOS automatic download setting in the App Store. 

Next, let’s take a look at the visual changes that were introduced as part of iOS 11, as we go through the important as well as the less important topics. 

UI Changes

After looking at the architectural as well as the app store publishing changes for iOS 11, we are now ready to dissect the visual changes and help you prioritize what UI changes should be tackled first. 

Importantly, while we certainly could build our iOS apps without implementing any of the changes in this section, addressing only the architectural and App Store changes, you may first want to ensure that your app visually supports the new iPhone X. This means changes to the navigation bars to address the new physical ‘notch’ at the top. 

With that in mind, we will look at updating your UI for the iPhone X first up, followed by some other quick changes that will ensure your app appears modern and up-to-date.

Updating Your UI for iPhone X

Mandatory | Higher Priority

One of the most important tasks in updating your iOS app is ensuring is ensuring your app looks good and works nicely on the newer devices, whilst not breaking your previous device support. That's why Apple has worked very hard to provide developers with tools such as Auto Layout to design for screen-agnostic layouts, be it the iPhone 4, 5C, or the 6 and 6 Plus. As of this year, we now have a phone that not only has new dimensions, but also has a physical notch at the top. 

The top notch of the iPhone X

Notice that we don’t have a rectangle viewport anymore, and with the new notch at the top for the physical sensors, how does Apple recommend you deal with that? For one thing, Apple don’t want you to place black bars at the top to hide the notch! Instead, they are advocating for developers to embrace it.

Don't mask or call special attention to key display features. Don't attempt to hide the device's rounded corners, sensor housing, or indicator for accessing the Home screen by placing black bars at the top and bottom of the screen. Don't use visual adornments like brackets, bezels, shapes, or instructional text to call special attention to these areas either. (iOS Human Interface Guidelines)

You will need to design for the full-screen experience, leveraging the new device’s bezel-less design while not obscuring parts of your UI with either the device’s rounded corners or sensor housing (notch). 

The layout of the iPhone X along with the safe areas Auto-Layout source iOS Human Interface Guidelines

The good news is, Apple’s system-provided UI elements from UIKit such as the UINavigationBar already conform and adapt to the new design requirements out of the box. However for any custom UI elements, you will need to do the conformance work yourself. 

Comparing the UI elements on the iPhone 47 versus the iPhone X source iOS Human Interface Guidelines

Looking at the images of the iPhone 4.7 compared to the new iPhone X above, you will notice how the status bar is now implemented differently, starting with its height, which has grown from the historical 20 pt to 44 pt on the iPhone X. 

Apple suggests that app developers who have been hiding their status bars should reconsider that decision in light of the iPhone X and only hide it in landscape mode, not portrait mode. 

Finally, make use of the Safe Area Layout Guides by leveraging Auto Layouts as your primary measure to ensure your app fits within its appropriate margins, guaranteeing no visual obstructions, such as underlapping the status bar or navigation bar.

iPhone X Safe Areas source iOS Human Interface Guidelines

Two excellent resources to help get you started with designing for the iPhone X are the following WWDC videos:

Implementing Drag & Drop

Optional | Lower Priority

One of the most talked about new SDKs at this year’s WWDC is drag & drop. This is something desktop users have been accustomed to for a very long time, but its absence in the iOS platform meant the iPad and iPhone have never truly embraced multi-tasking. In iOS 11, this has changed, as the new iOS will support UI elements being dragged not only within the same screen, but from one application to another. 

Drag  Drop on the iPad source Apple - Drag  Drop

Leveraging iOS’s multi-touch engine, users can effortlessly move content in a natural way between apps on the iPad (or just within the same screen on the iPhone) by tapping and holding on an image, file, text, or specific UI element to drag it. This is already integrated system-wide in iOS, allowing users for instance to drag text from Safari into the dock’s Reminders app to create a new reminder item. 

This hasn’t been flagged as mandatory for implementation, but because it will rapidly become an expected behavior due to its prevalence system-wide, it is suggested that you try and prioritize this sooner rather than later, so that you can make your app’s UX conform to the new standard system UX behavior. 

UIKit comes with some level of drag & drop support built-in, for components such as UITables and UICollectionViews, but you will need to bridge and adapt the elements with code so that other components can receive the dragged component. This can be somewhat involved, and it's outside the scope of this article, but I'll cover drag & drop support more fully in a follow-up post next week. 

For now, briefly, you would add and support drag & drop in your ViewController’s viewDidLoad() method, by implementing the two delegates shown below:

Stay tuned for our upcoming article on how to add Drag and Drop support to your iOS 11 app. 

Other UIKit & Auto Layout Changes

Optional | Lower Priority

Finally, let's take a look at the remaining UIKit changes new to iOS 11, starting with the UINavigationBar, which has some notable improvements, including the integration of SearchViewController and large titles. We then take a look at the improvements to UITableView, from the new and improved swipe actions to table view cells automatically self-sizing. 

Navigation 

We already touched on navigation bars earlier on when discussing the iPhone X and how it aligns with the new status bar dimensions. Besides that, the new contemporary design style advocated for in iOS includes new larger titles in navigation bars, first seen in the Apple Music App in iOS 10 and since then an established design pattern across all of the other system apps in iOS. 

Large title bars on the iPhone X Navigation Bar source iOS Human Interface Guidelines

The larger title text provides greater emphasis on the context of the screen in a navigation bar, and helps orient users as to the active tab while navigating through the various tabs. The size of the title text is not static but rather shrinks as the user scrolls down, reverting to the pre-iOS 11 style. Inversely, when you pull down in a scroll view, the title text will increase slightly. 

Use a large title when you need to provide extra emphasis on context. In some apps, the big, bold text of a large title can help orient people as they browse and search. In a tabbed layout, for example, large titles can help clarify the active tab and inform the user when they've scrolled to the top. Phone uses this approach, while Music uses large titles to differentiate content areas like albums, artists, playlists, and radio. A large title transitions to a standard title as the user begins scrolling content. Large titles don't make sense in all apps and should never compete with content. Although the Clock app has a tabbed layout, large titles are unnecessary because each tab has a distinct, recognizable layout. (iOS Human Interface Guidelines))

As a developer, it's up to you to decide if and when to implement the large text style, based on Apple’s Human Interface Guidelines, and Apple recommends you specifically use the large text titles only for top-level navigation screens rather than across all levels. To enable large text, simply add the following property to your UINavigationController:

Hierarchically, both the master and detail view controllers under the navigation bar will have the large text mode enabled by default due to parent inheritance, and as just mentioned, it is advisable to only have the top-level navigation screens implement the large text mode. To suppress the large text inheritance in your detail screen, go to your view controller and add the following to its initializer (it has to be set at initialization time):

The largeTitleDisplayMode above is being set to .never. Without that line, the default is .automatic, which is where the detail view controller inherits the properties of its parent view controller.

Search View Controllers

Search can now be integrated directly into navigation bars without needing to associate the UISearchViewController instance with the subject view controller (and its table header view) separately. As of iOS 11, you can elegantly embed the search bar in the navigation bar:

You will also need to conform to UISearchResultsUpdating to react to search terms, of course. While iOS automatically hides the search bar based on the number of rows in your table view, you can force the search bar to be visible at all times by toggling:

UITableViews

Finally, we take a look at two new and distinguished features introduced to UITableViews as of iOS 11: self-sizing and improved swipe actions. Self-sizing was introduced way back in iOS 8 to alleviate the burden of developers having to manually size table view cells, with the ability to dynamically size the cells to fit the contents of the row using Auto Layout. Until now, you had to explicitly request auto-sizing using:

As of iOS 11, it is on and set by default with no extra code, but you still have the ability to specify your own row height explicitly, as needed. iOS 11 has also brought about new leading and trailing swipe actions, prevalent in many system apps such as Apple’s very own Mail app. 

New Action swipes in iOS 11s UITableView source Cult of Mac

In addition to being able to being able to swipe either left or right, you can also attach images to associate with these actions. You implement two delegate methods as part of the UIContextualAction, for leading and trailing swipe actions:

Using the code above, you can create more than one contextual action and add it to the UISwipeActionsConfiguration grouping instance, for more than one action. This is a simple yet engaging improvement to bring greater elasticity to your table views, with minimal code changes, and while not mandatory, it's worth allocating a few hours to it in your sprint planning board. 

Conclusion

In this post, I've given you an overview of the changes across the architecture, App Store, and visual components of iOS 11, providing you with an idea of what you will need to action immediately, and what can be deferred until a later time. Migration to iOS 11 and Swift 4 will be a lot easier than it was in the previous years' updates.

Beyond the imminent changes that need to be made, we've also gone through the Swift 4 changes that improve strings and collections, as well as the visual improvements to UITableView and Search Controller. This should make it easier for you to plan your work to make updates to your app!

Stay tuned for my upcoming post on implementing drag & drop for your iOS 11 apps, and in the meantime, check out some of our other posts on new changes to iOS and Swift!

TypeScript for Beginners, Part 4: Classes

$
0
0

We have come a long way in learning TypeScript since starting this series. The first tutorial gave you a brief introduction of TypeScript and suggested some IDEs that you can use for writing TypeScript. The second tutorial focused on data types, and the third tutorial discussed the basics of interfaces in TypeScript.

As you might already know, JavaScript has only recently added native support for classes and object-oriented programming. However, TypeScript has allowed developers to use classes in their code for a long time. This code is then compiled to JavaScript that will work across all major browsers. In this tutorial, you will learn about classes in TypeScript. They are similar to their ES6 counterparts but are stricter.

Creating Your First Class

Let's start with the basics. Classes are a fundamental part of object-oriented programming. You use classes to represent any entity which has some properties and functions that may act on given properties. TypeScript gives you full control over the properties and functions that are accessible inside and outside their own containing class. Here is a very basic example of creating a Person class.

The above code creates a very simple class called Person. This class has a property called name and a function called introduceSelf. The class also has a constructor, which is also basically a function. However, constructors are special because they are called every time we create a new instance of our class. 

You can also pass parameters to constructors in order to initialize different properties. In our case, we are using the constructor to initialize the name of the person that we are creating using the Person class. The introduceSelf function is a method of the Person class, and we are using it here to print the name of the person to the console. All these properties, methods, and the constructor of a class are collectively called class members.

You should keep in mind that the Person class does not automatically create a person by itself. It acts more like a blueprint with all the information about the attributes a person should have once created. With that in mind, we created a new person and named her Sally. Calling the method introduceSelf on this person will print the line "Hi, I am Sally!" to the console.

Private and Public Modifiers

In the previous section, we created a person named Sally. Right now, it is possible to change the name of the person from Sally to Mindy anywhere in our code, as shown in the following example.

You might have noticed that we were able to use both the name property and the introduceSelf method outside the containing class. This is because all the members of a class in TypeScript are public by default. You can also explicitly specify that a property or method is public by adding the keyword public before it.

Sometimes, you don't want a property or method to be accessible outside its containing class. This can be achieved by making those members private using the private keyword. In the above code, we could make the name property private and prevent it from being changed outside the containing class. After this change, TypeScript will show you an error saying that the name property is private and you can only access it inside the Person class. The screenshot below shows the error in Visual Studio Code.

A private property not accessible outside its class

Inheritance in TypeScript

Inheritance allows you to create more complex classes starting from a base class. For example, we can use the Person class from the previous section as a base to create a Friend class that will have all the members of the Person and add some members of its own. Similarly, you could also add a Family or Teacher class. 

They will all inherit the methods and properties of the Person while adding some methods and properties of their own to set them apart. The following example should make it clearer. I have also added the code for the Person class here so that you can easily compare the code of both the base class and the derived class.

As you can see, you have to use the extend keyword for the Friend class to inherit all the members of the Person class. It is important to remember that the constructor of a derived class must always invoke the constructor of the base class with a call to super().

You might have noticed that the constructor of Friend did not need to have the same number of parameters as the base class. However, the first name parameter was passed to super() in order to invoke the constructor of the parent, which also accepted one parameter. We did not have to redefine the introduceSelf function inside the Friend class because it was inherited from the Person class.

Using the Protected Modifier

Up to this point, we have only made the members of a class either private or public. While making them public allows us to access them from anywhere, making the members private limits them to their own containing class. Sometimes you might want the members of a base class to be accessible inside all the derived classes. 

You can use the protected modifier in such cases to limit the access of a member only to derived classes. You can also use the protected keyword with the constructor of a base class. This will prevent anyone from creating an instance of that class. However, you will still be able to extend classes based on this base class.

In the above code, you can see that we made the age property protected. This prevents the use of age outside any classes derived from Person. We have also used the protected keyword for the constructor of the Person class. Declaring the constructor as protected means that we will no longer be able to directly instantiate the Person class. The following screenshot shows an error that pops up while trying to instantiate a class with the protected constructor.

TypeScript protected constructor

Final Thoughts

In this tutorial, I have tried to cover the basics of classes in TypeScript. We began the tutorial by creating a very basic Person class that printed the name of the person to the console. After that, you learned about the private keyword, which can be used to prevent the members of a class from being accessed at any arbitrary point in the program. 

Finally, you learned how to extend different classes in your code using a base class with inheritance. There is a lot more that you can learn about classes in the official documentation.

If you have any questions related to this tutorial, let me know in the comments.

How to Deploy With Deployer

$
0
0

Automated workflow for deployment is a great tool that every software development team must have. The release process, when it is fast, secure and fault tolerant, can save time for developing more great things. And the good news that there are many great tools for creating an automated release cycle.

In this article, I'm going to introduce you a deployment tool called Deployer. I like to use it because it is written in PHP, is easy to set up, and has many handy features to integrate the deployment process into your team's workflow.

The Deployment Process With Deployer

First of all, let's see the structure of the deployment process with Deployer. It consists of three main parts: a deploy server to init deployment, a production or staging server to host your application, and a git repository to store the code of your application.

When you init a deploy process, you run a deployment script on the deploy server. After this, the deploy server connects to the production server with SSH and does the maintenance things from the production server like cloning the code from a git repository, updating Composer's dependencies, and other stuff you need in order to have a successful release. 

Deployer Deployment Process

For everyone to be trusted in this chain, we will create and install SSH certificates to the servers and repository.

Install SSH Certificates

We need to create an SSH authentication key on a production server and share it to a git repository. If you don't have any SSH authentication keys on your deploy server, run ssh-keygen and follow the instructions. Keygen will create a public key in a file ~/.ssh/id_rsa.pub.

Now you can install it to the account of your repository. If you don't know how to do it, look at the example of GitHub from the related links at the bottom of the article, or ask your repository hosting service for help.

Also, it is better to create an SSH key on your deploy server to get trusted on the production machine. Use these commands to make a passwordless SSH connection between the deploy and production servers.

With all certificates installed, we are ready to install Deployer.

Install Deployer

The installation of Deployer is as easy as the installation of Composer. You need to download PHP Archive and make it a global command:

Let's check the version of Deployer to see if everything is installed correctly:

Everything looks great, and we are ready to create our first deployment script.

Make the First Deployment Script

To initialize Deployer for your project, run dep init. This will execute a utility to generate a deployment script, which will ask you for a project type and repository link and will create the deploy.php file in the current directory. Let's have a look at this file and the main functions that are used in a recipe. 

The functions set and get work with the configuration values, and a shortcut of a getter can be used with a run command:

Each configuration value can be overridden for each host. We can set up a deploy path and SSH user for our application in our deploy script:

To define your own tasks, use the task function and run to run a command on the production server:

And then run it with dep and the function name as a param:

Now you can look through the deploy file and change all the needed params to the configuration of your application.

Deploy to Production

We have already installed Deployer, installed SSL certificates to the deploy and production servers, and made the deployment script, so finally it is time to pull it all together and make the first deployment to production.

To deploy your application, just call dep deploy:

Deploy to Production

If something has gone wrong, you can roll back to the previously deployed version in just one step:

Looks easy, doesn't it?

Now let's check what was created on our production server. Thanks to Deployer, we can do this easily with shortcut commands. Try dep ssh to connect to a server directly using the configuration from the deployment script, or remotely execute a command via SSH tunnel with dep run. Also, this command supports variables that we have set in the script.

So let's have a look at the deploy path:

The main thing is the releases directory, where Deployer stores the last versions of our application. After each successful deploy or rollback, it links current to the enabled release. Finally, we have a shared directory, which stores files and folders from the shared_dirs and shared_files that we have set in the script file.

On the first deployment, Deployer will copy those files to a shared dir and create a link from the releases dir to the shared dir. The next time, it will just add a link from the release files to the files and folders in the shared directory. Also, you can change any file in a shared directory and Deployer will keep it without changes on each deploy—for example, this is useful for configuration files.

In addition, if you have a composer.json file in the root of your repository, Deployer will call Composer to create a vendor directory and update all needed dependencies. If you don't store the Composer file in the root directory, you can create a custom task to update it.

And now it is time to integrate the application deploy to our processes.

Add a Custom Task

Every team has its own deploy configurations and process to automate, so Deployer has easy tools to extend the standard configuration and add custom tasks. For example, your hosting may have the rule to store applications and webroot in different places, with no rights to change the configuration of Apache or Nginx. 

But there is a way to get over this rule—use symbolic links. So we will add a task for this:

And then add it to the main deploy task as part of a release cycle:

Now run the deploy script again and check if everything is correct with dep ssh.

Third-Party Recipes

Deployer has many recipes to integrate with third parties that can extend the basic functionality. We can use Composer to install them:

I like to use the Slack notification recipe. To enable it, we should go to the Slack recipe page, click the Add to Slack button, and select the channel to send notifications. Then we will get the Slack webhook and add this code to deployment.

After these changes, Deployer will send a message like this to the deploy channel:

Viewing Deployer in Slack

Now you can add your team to the channel so everyone who's involved can be notified.

Conclusion

In this tutorial we have installed Deployer and created a deploy script that can be used to deploy our application from a git repository to a production or staging server in just one click.

Also, it can be integrated into team processes—for example, an application can be deployed automatically after changes in the master branch and notification can be made on a Slack channel about successful deployment.

If you have any questions, don't hesitate to ask questions in the comments to the article. 

Further Reading and Related Links

Viewing all 5166 articles
Browse latest View live