Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

July 14 2017

13:00

Android O: Phone Number Verification With SMS Tokens

In this tutorial, you'll learn about the cool new SMS token feature in Android O. You'll learn how to generate an app-specific token that will fire up a pending intent when the device first receives a message containing that token so as to verify the phone number. 

Kindly note that as of this writing, the Android O APIs are still in their third developer preview, though they are final. (We still don't know what O stands for yet!)

What Is an SMS Token?

An SMS token or one-time password is a security mechanism used to authenticate or verify a user. The user enters their phone number, and a limited lifespan token is generated specifically for that user. The user then receives the token as an SMS to their phone. In the case of Android O as of this writing, this app-specific token does not expire, but instead becomes invalid when another is generated. 

Why Use Android O's SMS Token?

One of the major reasons you might consider using Android O's SMS token mechanism is that it improves the user experience of the app. The user does not need to copy and paste the token from the SMS client to be verified. Instead, the Android device automatically detects the token sent to the user's device and then triggers the app component in the intent associated with your app (we'll get to that shortly). 

Even better, this functionality doesn't require the READ_SMS permission or any other. This mechanism also improves the security of your app user, because no other app can read the message containing the token on the device. 

In this tutorial, you'll learn how to use this new feature in Android O's SMS API. You'll learn how to generate an SMS token specifically for your app and send it to a device. We'll use the Android Studio emulator to simulate this process. 

Prerequisites

To follow along with this tutorial, make sure you have downloaded the Android 8.0 (O) SDK platform on your computer and have an emulator already set up that targets this version. 

1. Generate the App-Specific Token

To start off, I'll show you how to generate an app-specific token which is unique to your app on the user's device.

Create a New Android Studio Project

Fire up Android Studio and create a new project with an empty activity called MainActivity.

Create a new Android Studio project

Modify the build.gradle File

Make the following changes to your app module's build.gradle file. 

Modify the MainActivity Class

In the code snippet below, we get the SMSManager class and then call the method createAppSpecificSmsToken(). This does just what it says—it creates the app-specific SMS token. This method requires a PendingIntent which contains the Activity to be fired up when an SMS containing this token (a string 11 characters long) is received by the device. 

Be aware that, as stated earlier, the generated token is unique to your app on the user's device. If you create another SMS token, the second one will be a valid token while the first one will be ignored. 

Lay Out the Screen

Here's a MainActivity layout file set up to display the SMS token that was generated:

Running the app at this point will show the SMS token generated. 

Running the app at this point

2. Receive the SMS Token

Next, we'll create the activity to be fired up when our device receives a message containing the SMS token. Nothing specific to SMS tokens happens here. 

Lay Out the Screen

Here we create the layout for the activity we created above that contains just one TextView

Next, we'll test this functionality using the Android Studio emulator.

3. Test the SMS Token

Set Up the Emulator to Send SMS Messages

You can use your emulator to simulate receiving an SMS message, but you'll need to do a little setup. Open your emulator, click the last button on the right-side navigation bar to open the extended control dialog, and then select the phone control button. 

Showing how to use the Emulator to simulate sending an SMS message

From this interface, you can simulate your device receiving a phone call or SMS from another phone.

Send the Token

Make sure you have set up your emulator that targets Android 8.0 (O). Generate a token and enter a text message that contains it. Then click the Send Message button.  

Sending a message with emulator

Finally, the activity we specified in the pending intent gets fired up immediately! Try sending the message again and see that this time, it will show up in the device SMS client instead, because it is no longer a valid token. 

Token result activity

Using a Server

For a production app, the SMS token will typically be sent by a back-end server. So when using a server, the client (your app) should make a request to the server, including the app generated token and the phone number. Your server will then receive this request and send the unmodified token back as a text message to the user's phone. Your app will then receive this token and fire up the component registered in the pending intent. That component can then let the server know that the phone number verification or user authentication succeeded.

Conclusion

In this tutorial, you learned about the awesome SMS token feature introduced in Android O: what is it, its benefits, and how to use it in an Android app. 

To learn more about Android SMS and phone APIs, including how to make calls from your app, check out my related tutorial here on Envato Tuts+.

  • Android SDK
    How to Make Calls and Use SMS in Android Apps
    Chike Mgbemena

And check out some of our other courses and tutorials on Android app development!

  • Android SDK
    Android O: How to Use Notification Channels
    Chike Mgbemena
  • Android
    How to Solve Android’s 13 Most Common Error Messages
    Jessica Thornsby
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal

12:00

Introducing NumPy

Numeric is a package that was originally developed by Jim Hugunin. It is considered the ancestor of NumPy, a Python library and an open-source project created by Travis Oliphant which stands for Numerical Python. Travis created NumPy by incorporating features of the Numarray package into Numeric. 

The fundamental idea of NumPy is support for multidimensional arrays. So NumPy can be considered as the base for numerical computing in Python, and has been created to enable Python to be used in solving mathematical and scientific problems. The NumPy module provides us with hundreds of useful mathematical functions in addition to constants such as the base of natural logarithms (e) and pi (π).

This tutorial shows how we can use NumPy to work with multidimensional arrays, and describes the ndarray object, a fundamental object of the library.

Installing NumPy

Since Python doesn't come bundled with NumPy, the first step to use this library is to go ahead and install it. This can be simply done by running the following command in your command prompt:

To make sure that NumPy was installed successfully, run the following commands in Python's IDLE:

Python-IDLE-Numpy

If the import statement at least runs successfully, then you are all set!

The ndarry Object

The ndarray is a fundamental object of NumPy. This object is an N-dimensional array, meaning that it contains a collection of elements of the same type indexed using N (dimensions of the array) integers.

The main attributes of ndarray are data type (dtype), shape, size, itemsize, data, and ndim. Let's learn what each attribute means through an example. 

In this example we are going to use NumPy to create an array. I will not give the dimensions of the array and other information, as we will see that using the above attributes.

create_array_numpy

Notice that we used the array function to create an array. The output of the above script is as follows:

array_numpy_output

Let's now return to our attributes.

dtype

The dtype attribute can be run as shown in the following statement:

The above statement will return int32 as the data type. This means that the elements of the array are of type int32. I'm getting 32 as I'm using a 32-bit Python. If you are using a 64-bit Python, you will get int64, but we are dealing with integers at the end.

Since NumPy is used in scientific computing, it has many data types, as shown in the documentation. Notice that the majority of the NumPy data types end with a number, which indicates the number of bits associated with that type (this was mentioned briefly in the above paragraph).

The following examples show how we can convert from one type to another:

The above statements return the following:

Although we can convert from one type to another, it is important to note that we cannot convert a complex number into an integer or a float.

shape

The shape attribute returns a tuple of the array dimensions. So the following statement:

will return (4,4), meaning that our array is composed of 4 rows and 4 columns.

size

The size attribute returns the number of elements in the array. Thus, if we type:

we will get 16 as the result, meaning that we have 16 elements in our array.

itemsize

The itemsize attribute returns the size of one array element in bytes. The following statement:

will return 4. This means that each array element is of size 4-bytes.

data

The data attribute is a Python buffer object that points to the start of the array's data. If we type the following:

we will get the following: <memory at 0x0000021E7E8D7EA0>.

ndim

The attribute ndim will return the number of the array dimensions. So typing the following statement:

will return 2, that is the array consists of two dimensions.

After understanding what the different ndarray attributes mean, let's take a look at some more examples of using ndarray.

Example 1

Say we want to create a new array with one row and five columns. We would do that as follows:

The output of the above statement is: [1 2 3 4 5].

Example 2

In this example, I'm going to rewrite the first example in this tutorial, but using [ ] instead of ( ), as follows:

numpy_array_square_brackets

Example 3

This example shows how we use a structured data type, where we declare the field name and the corresponding data type:

If we print(data_type), we will get the following:

We can apply the height_type to an ndarray object, as follows:

Selecting Items

In this section I'm going to show you how to select specific items in the array. For our array shown above under the "ndarry Object" section, let's say we want to select the item located on the third row and the fourth column. We will do that as follows:

Remember that indexing here starts at 0, and that's why we wrote [2,3] instead of [3,4].

More on NumPy Arrays

In this section, we are going to delve deeper into NumPy arrays.

Empty (Uninitialized) Arrays

We can create an empty array using numpy.empty with the following syntax:

The meanings of the parameters in the above constructor are as follows

  • Shape: the shape (dimensions) of the empty array.
  • dtype: the desired output type, which is optional.
  • Order: if you want a C-style (row-major) array, you would type C; if you want a FORTRAN-style (column-major) array, you would type F.

So let's create an empty [2,2] array of type int. We can do that as follows:

The above script will return the following random values as the array wasn't initialized:

Array Filled With Zeros

In order to create an array where the elements are all zeros, we use numpy.zeros. The constructor here has the same syntax and parameters as in numpy.empty. So, if we want to create a [2,2] zeros array of type int, we can do that as follows:

The above script will return the following:

An array with all elements having the value 1 can be simply created in the same way as above, but with numpy.ones.

Arrays With Evenly Spaced Values Within a Given Range

We can use numpy.arange to create an array with evenly spaced values within a specified range. The constructor has the following format:

Below is the meaning of each parameter:

  • Start: this is where the interval begins. The default value is 0.
  • Stop: the end of the interval, provided that this number is not included.
  • Step: the spacing between values. The default value is 1.
  • dtype: the data type of the output. If not specified, the data type will be the same as that of the input.

Let's take an example of numpy.arange.

The result of the above script is:

Reshaping an Array

In order to reshape an array, we use the numpy.reshape function. This function gives a new shape to an array without changing its data. As shown in the documentation, the function has the following attributes: numpy.reshape(a, newshape, order='C'), where a is the array we would like to reshape, newshape is the new desired shape provided that the new shape should be compatible with the origin shape, and order is an optional argument which refers to the index order we would like to use to both read the array a and how we would like to place the elements in the reshaped array.

C means reading/writing the elements using C-like index order; F means reading/writing the elements using Fortran-like index order, and A means reading/writing the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.

I know I've covered a lot in the above paragraph, but the concept is very simple. Let's take our original array my_array and try to reshape it. Remember that the new array (reshaped array) has to be compatible with the original array. For instance, my_array has the shape (4,4), that is we have 16 elements in the array, and the new array has to have that number of elements.

We can reshape my_array by setting it to have eight rows and two columns, as follows:

In which case we would have the following output, where we also have 16 elements.

What if we write the reshape statement as follows?

In this case, you would get the following error:

Concatenating Arrays

If we want to join two or more arrays of the same shape along a specific axis, we can use the numpy.concatenate function. The syntax of this function is: numnumpy.concatenate((a1, a2, ...), axis=0)y.concatenate. a1 and a2 are arrays having the same shape, and axis is the axis along which the arrays will be joined, provided that the default is 0.

Again, let's take an example to simplify the concept. In this example, we will be joining (concatenating) three arrays.

The output of the above code is as follows:

Splitting Arrays

Contrary to joining arrays as shown in the above section, let's see how we can split (divide) an array into multiple sub-arrays. This can be done using the following function:

ary is the array to be divided into sub-arrays. Regarding indices_or_sections, if it is an integer N, the array will be divided into N equal arrays along the axis. If it is a 1-D array of sorted integers, the entries indicate where along the axis the array is split. axis is the axis along which to split.

The following example will reverse what we have done in the previous example, that is to return the concatenated array into its three array constituents:

The output of the above script is:

Conclusion

As we saw in this tutorial, NumPy makes it very flexible to work with arrays. The tutorial was just a scratch on the surface of this interesting Python library. NumPy still has many more features to look at to get the most out of this library. A comprehensive book on the topic by the NumPy creator himself is Guide to NumPy.

Furthermore, 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.

July 13 2017

14:13

SpriteKit Basics: Putting It All Together

Final product image What You'll Be Creating

In this post we'll build a simple game from scratch. Along the way, we'll touch on some of the most important aspects of the SpriteKit library.

This post builds on what we've learned earlier in the SpriteKit Basics series. If you want to refresh your SpriteKit knowledge, take a look at some of my other posts.

  • SpriteKit
    Introducing SpriteKit
    James Tyner
  • SpriteKit
    SpriteKit Basics: Nodes
    James Tyner
  • iOS SDK
    SpriteKit Basics: Sprites
    James Tyner
  • SpriteKit
    SpriteKit Basics: Actions and Physics
    James Tyner

New Project

Open Xcode and start a new project from the menu File > New Project. Make sure iOS is selected and choose Game as your template.

new project

Give your project a name, and make sure that Language is set to Swift, Game Technology is set to SpriteKit, and Devices is set to iPad.

project options

Planning the Game Scenes

One of the first things I like to do when creating a project is to determine how many scenes I will need for the project. I will usually have at least three scenes: an intro scene, a main game scene, and a scene to show high scores, etc.

For this example, we just need an intro and main gameplay scene since we won't be keeping track of lives, scores, etc. SpriteKit already comes with one scene when you create a new project, so we just need an intro scene.

From Xcode's menu, choose File > New > File. Make sure iOS is selected, and choose Cocoa Touch Class.

new cocoa touch class

Name the class StartGameScene, and make sure that Subclass of is set to SKScene and Language is set to Swift.

startgamescene class

Setting Up GameViewController

Open GameViewController.swift. Delete everything in that file and replace it with the following.

When you create a new project, GameViewController.swift is set up to load GameScene.sks from disk. GameScene.sks is used along with SpriteKit's built-in scene editor, which allows you to visually lay out your projects. We will not be using GameScene.sks, and will instead create everything from code, so here we initiate a new instance of StartGameScene and present it.

Create the Intro Scene

Add the following to the newly created StartGameScene.swift.

This scene is pretty simple. In the didMove method, we add a logo and a button. Then, in touchesBegan, we detect touches on the new game button and respond by loading the main scene GameScene.

Planning Game Classes

The next thing I like to do when creating a new game is decide which classes I will need. I can tell right away that I will need a Player class and an Enemy class. Both of these classes will extend SKSpriteNode. I think for this project we will just create the player and enemy bullets right from within their respective classes. You could make separate player bullet and enemy bullet classes if you prefer, and I suggest you try to do that as an exercise on your own. 

Lastly, there are the islands. These do not have any specific functionality but to move down the screen. In this case, since they're just decorations, I think it's also okay not to create a class, and instead just create them in the main GameScene.

Creating the Player Class

From Xcode's menu, choose File > New > File.  Make sure iOS is selected and choose Cocoa Touch Class.

new cocoa touch class

Make sure that Class is set to Player, Subclass of: is set to SKSpriteNode, and Language is set to Swift.

player class

Now add the following to Player.swift.

Within the init() method, we set up the physicsBody and invoke generateBullets(). The generateBullets method repeatedly calls fireBullet(), which creates a bullet, sets its physicsBody, and moves it down the screen.

When the player loses a life, the respawn() method is invoked. Within the respawn method, we fade the plane in and out five times, during which time the player will be invincible. One the player has exhausted all the lives, the kill() method is invoked. The kill method simply loads the StartGameScene.

Creating the Enemy Class

Choose File > New > File from Xcode's menu. Make sure iOS is selected and choose Cocoa Touch Class.

new cocoa touch class

Make sure that Class is set to EnemySubclass of: is set to SKSpriteNode, and Language is set to Swift.

Add the following to Enemy.swift.

This class is pretty similar to the Player class. We set its physicsBody and invoke generateBullets(). The move() simply moves the enemy down the screen.

Creating the Main Game Scene

Delete everything within GameScene.swift and add the following.

We create an instance of Player and an instance of CMMotionManager. We are using the accelerometer to move the player in this game.

Within the didMove(to:) method we turn off the gravity, set up the contactDelegate, add an edge loop, and set the player's position before adding it to the scene. We then invoke setupAccelerometer(), which sets up the accelerometer, and invoke the addEnemies() and generateIslands() methods.

The addEnemies() method repeatedly calls the generateEnemy() method, which will create an instance of Enemy and add it to the scene.

The generateIslands() method works similarly to the addEnemies() method in that it repeatedly calls createIsland() which creates an SKSpriteNode and adds it to the scene. Within createIsland(), we also create an SKAction that moves the island down the scene.

Within the didBegin(_:) method, we check to see which nodes are making contact and respond by removing the appropriate node from the scene and invoking player.die() if necessary. The createExplosion() method creates an explosion animation and adds it to the scene. Once the explosion is finished, it is removed from the scene.

Conclusion

During this series, we learned some of the most important concepts used in almost all SpriteKit games. We ended the series by showing how simple it is to get a basic game up and running. There are still some improvements that could be made, like a HUB, high scores, and sounds (I included a couple of MP3s you can use for this in the repo). I hope you learned something useful throughout this series, and thanks for reading!

If you want to learn more about game programming with SpriteKit, check out one of our comprehensive video courses! You'll learn how to build a SpriteKit game from A to Z.

  • Swift
    Code a Side-Scrolling Game With Swift 3 and SpriteKit
    Derek Jensen
  • Game Development
    Game Development With Swift and SpriteKit
    Derek Jensen

08:00

Grab 16 Free Stock Photos and Design Assets From Envato Elements

Last month, we made a big announcement: unlimited stock photos on Envato Elements. Now, to celebrate the launch, we're giving away 16 free images and design assets, to give a small taste of what Elements has to offer. They all come with a simple license allowing you to use them in any single project you want.

The Freebies You Can Download

So what exactly can you download? You'll find a selection of beautiful photos, such as this stunning underwater shot:

Turtle swimming underwater

You'll also find striking portraits, creative close-up shots, landscape images, and work photos suitable for illustrating a report or proposal:

Colleagues working

And it's not just images you can download. There's also an amazing Photoshop action that allows you simply to brush onto areas of a photo and play the action to turn those areas into a powerful sandstorm effect.

Sandstorm Photoshop action

And on top of all this, you can download an elegant script font, a flyer template, and a PowerPoint presentation template. 

How to Unlock Your Free Photos

To access the free photos and design assets, all you have to do is go to the launch page and enter your email address. Then you can download as many of the free files as you want. 

If you like what you see, you can also explore the full range of more than 200,000 stock photos now available on Envato Elements, or browse the thousands of web templates, 3D renders, graphics and more that come with a monthly subscription. But if it's not right for you, no worries—you can just enjoy your freebies, with no obligation to buy anything. 

July 12 2017

17:46

Unit Testing in React: Shallow vs. Static Testing

 

In my course on Unit Testing React Components, I showed you how to use Enzyme, the Airbnb unit-testing library, to unit test React components.

Enzyme gives us a couple of different types of ways to render React components. In this video from the course, we’ll look at the difference between shallow rendering and static rendering, and talk about when you might use them.

Related Links

Unit testing in React

Watch the Full Course

The full course, Unit Testing React Components, goes into much more detail on unit testing React components, which is actually easy to do thanks to React's functional programming model. We'll go from the basic setup and writing a test all the way through to full DOM rendering tests.

If you want to see what else you can do with JavaScript, check out the wide range of JavaScript plugins on Envato Market.

12:00

Working With the File System in Elixir

Working with the file system in Elixir does not really differ from doing so using other popular programming languages. There are three modules to solve this task: IO, File, and Path. They provide functions to open, create, modify, read and destroy files, expand paths, etc. There are, however, some interesting gotchas that you should be aware of.

In this article we will talk about working with the file system in Elixir while taking a look at some code examples.

The Path Module

The Path module, as the name suggests, is used to work with file system paths. The functions of this module always return UTF-8 encoded strings.

For instance, you can expand a path and then generate an absolute path easily:

Note, by the way, that in Windows, backslashes are replaced with forward slashes automatically. The resulting path can be passed to the functions of the File module, for example:

Here we are constructing a full path to the file and then writing some contents to it.

All in all, working with the Path module is simple, and most of its functions do not interact with the file system. We will see some use cases for this module later in the article.

IO and File Modules

IO, as the name implies, is the module to work with input and output. For example, it provides such functions as puts and inspect. IO has a concept of devices, which can be either process identifiers (PID) or atoms. For instance, there are :stdio and :stderr generic devices (which are actually shortcuts). Devices in Elixir maintain their position, so subsequent read or write operations start from the place where the device was previously accessed.

The File module, in turn, allows us to access files as IO devices. Files are opened in binary mode by default; however, you might pass :utf8 as an option. Also when a filename is specified as a character list ('some_name.txt'), it is always treated as UTF-8.

Now let's see some examples of using the modules mentioned above.

Opening and Reading Files With IO

The most common task is, of course, opening and reading files. To open a file, a function called open/2 can be used. It accepts a path to the file and an optional list of modes. For example, let's try to open a file for reading and writing:

You may then read this file using the read/2 function from the IO module as well:

Here we are reading the file line by line. Note the :eof atom that means "end of file".

You can also pass :all instead of :line to read the whole file at once:

In this case, :eof won't be returned—instead, we get an empty string. Why? Well, because, as we said earlier, devices maintain their position, and we start reading from the previously accessed place.

There is also an open/3 function, which accepts a function as the third argument. After the passed function has finished its work, the file is closed automatically:

Reading Files With File Module

In the previous section I've shown how to use IO.read in order to read files, but it appears that the File module actually has a function with the same name:

This function returns a tuple containing the result of the operation and a binary data object. In this example it contains "test", which is the contents of the file.

If the operation was unsuccessful, then the tuple will contain an :error atom and the error's reason:

Here, :enoent means that the file does not exist. There are some other reasons like :eacces (has no permissions).

The returned tuple can be used in pattern matching to handle different outcomes:

In this example, we either print out the file's contents or display an error reason.

Another function to read files is called read!/1. If you have come from the Ruby world, you've probably guessed what it does. Basically, this function opens a file and returns its contents in the form of a string (not tuple!):

However, if something goes wrong and the file cannot be read, an error is raised instead:

So, to be on the safe side, you can, for example, employ the exists?/1 function to check whether a file actually exists: 

Great, now we know how to read files. However, there is much more we can do, so let's proceed to the next section!

Writing to Files

To write something to a file, use the write/3 function. It accepts a path to a file, the contents, and an optional list of modes. If the file does not exist, it will be created automatically. If, however, it does exist, all its contents will be overwritten by default. To prevent this from happening, set the :append mode:

In this case, the contents will be appended to the file and :ok will be returned as a result. If something goes wrong, you'll get a tuple {:error, reason}, just like with the read function.

Also, there is a write! function that does pretty much the same, but raises an exception if the contents cannot be written. For example, we can write an Elixir program that creates a Ruby program that, in turn, prints "hello!":

Streaming Files

The files can indeed be pretty large, and when using the read function you load all the contents into the memory. The good news is that files can be streamed quite easily:

In this example, we open a file, stream it line by line, and inspect each line. The result will look like this:

Note that the new line symbols are not removed automatically, so you may want to get rid of them using the String.replace/4 function.

It is a bit tedious to stream a file line by line as shown in the previous example. Instead, you can rely on the stream!/3 function, which accepts a path to the file and two optional arguments: a list of modes and a value explaining how a file should be read (the default value is :line):

In this piece of code we are streaming a file while removing newline characters and then printing out each line. File.stream! is slower than File.read, but we don't need to wait until all lines are available—we can start processing the contents right away. This is especially useful when you need to read a file from a remote location.

Let's take a look at a slightly more complex example. I'd like to stream a file with my Elixir script, remove newline characters, and display each line with a line number next to it:

Stream.with_index/2 accepts an enumerable and returns a collection of tuples, where each tuple contains a value and its index. Next, we just iterate over this collection and print out the line number and the line itself. As a result, you'll see the same code with line numbers:

Moving and Removing Files

Now let's also briefly cover how to manipulate files—specifically, move and remove them. The functions we're interested in are rename/2 and rm/1. I won't bore you by describing all the arguments they accept as you can read the documentation yourself, and there is absolutely nothing complex about them. Instead, let's take a look at some examples.

First, I'd like to code a function that takes all files from the current directory based on a condition and then moves them to another directory. The function should be called like this:

So, here I want to grab all .txt files and move them to the texts directory. How can we solve this task? Well, firstly, let's define a module and a private function to prepare a destination directory:

mkdir!, as you've already guessed, tries to create a directory and returns an error if this operation fails.

Next, we need to grab all the files from the current directory. This can be done using the ls! function, which returns a list of file names:

Lastly, we need to filter the resulting list based on the provided function and rename each file, which effectively means moving it to another directory. Here is the final version of the program:

Now let's see the rm in action by coding a similar function that is going to remove all files based on a condition. The function will be called in the following way:

Here is the corresponding solution:

rm!/1 will raise an error if the file cannot be removed. As always, it has an rm/1 counterpart that will return a tuple with the error's reason if something goes wrong.

You may note that the remove_if and transfer_to functions are very similar. So why don't we remove code duplication as an exercise? I'll add yet another private function that takes all the files, filters them based on the provided condition, and then applies an operation to them:

Now simply utilize this function:

Third-Party Solutions

Elixir's community is growing, and fancy new libraries solving various tasks are emerging. The Awesome Elixir GitHub repo lists some popular solutions, and of course there is a section with libraries for working with files and directories. There are implementations for file uploading, monitoring, filename sanitization, and more.

For example, there is an interesting solution called Librex for converting your documents with the help of LibreOffice. To see it in action, you can create a new project:

Then add a new dependency to the mix.exs file:

After that, run:

Next, you can include the library and perform conversions:

In order for this to work, the LibreOffice executable (soffice.exe) must be present in the PATH. Otherwise, you'll need to provide a path to this file as a third argument:

Conclusion

That's all for today! In this article, we've seen the IO, File and Path modules in action and discussed some useful functions like open, read, write, and others. 

There are lots of other functions available for use, so be sure to browse Elixir's documentation. Also, there is an introductory tutorial on the official website of the language that can come in handy as well.

I hope you enjoyed this article and now feel a bit more confident about working with the file system in Elixir. Thank you for staying with me, and until next time!

12:00

How to Add CAPTCHAs to Android Apps

If you are developing an Android application that needs to interact with your back-end server, it is important that you take steps to defend it against bots—automated scripts that try to pass for human. Otherwise, your server stands a very real chance of being overrun by them.

CAPTCHAs, short for Completely Automated Public Turing tests for telling Computers and Humans Apart, are currently the most effective defense against bots. As you might already know, they are usually image, voice, or common sense-based tests that are easy for humans, but extremely hard for computers.

In this tutorial, I'll show you how to use the newly released SafetyNet reCAPTCHA API to add CAPTCHAs to your Android apps.

Prerequisites

To be able to follow this tutorial, you'll need the following:

1. Project Setup

Launch Android Studio and create a new project with an empty activity. In the Configure your new project form, make sure you type in a meaningful package name—you'll be using it while registering your app with the reCAPTCHA service.

Additionally, check the Include Kotlin Support field. Because Kotlin is now an official Android language, we'll be using it instead of Java in this tutorial.

Configure your new project form

SafetyNet APIs are a part of Google Play services. To be able to use them in your project, add the following implementation dependency to the build.gradle file of the app module:

Additionally, to perform network-related operations, we'll be using the Fuel library, which has a very concise Kotlin-based API. Therefore, add it as another implementation dependency.

You can't perform network-related operations without the INTERNET permission, so add the following line to your project's manifest file:

Finally, press the Sync Now button to complete the project configuration.

2. Acquiring reCAPTCHA Keys

You'll need two keys before you can use the reCAPTCHA service:

  • a site key, which must be passed to the service from your Android app
  • and a secret key, which must be passed to the service from your back-end server

To get the keys, use your Google account and log in to the reCAPTCHA admin console. If you're opening the console for the first time, you'll automatically be presented with a short registration form where you can type in your app's package name.

reCAPTCHA registration form

After you accept the reCAPTCHA terms of service, go ahead and press the Register button to generate both the keys.

Site key and secret key screen

You can now add the site key to your Android Studio project by simply mentioning it inside the res/values/strings.xml file:

We'll be working with the secret key only towards the end of this tutorial, so note it down somewhere safe for now.

3. Generating CAPTCHAs

When we hear the word CAPTCHA, we usually think of messy images containing hard-to-read letters and numbers. Such CAPTCHAs, however, thanks to advances in computer vision technologies, are no longer good enough to stop all bots.

CAPTCHAs generated by the reCAPTCHA service are highly advanced, and very interactive too. In fact, solving them is akin to playing simple games. Consequently, you can't directly embed them in your activity's layout. Instead, you must add a button to the layout, which, when pressed, should lead the user to a new screen or dialog containing the CAPTCHAs.

The following code shows you how to add a Button widget to your activity's layout XML file:

Before you start generating CAPTCHAs, you'll have to initialize a client for the SafetyNet API. You can do so by calling the getClient() method of the SafetyNet class. Accordingly, add the following code inside the onCreate() method of your Activity class:

The CAPTCHAs must be displayed when the user presses the button, so add an on-click event handler to it using the setOnClickListener() method. Inside the handler, all you need to do is call the verifyWithRecaptcha() method and pass your site key as an argument to it in order to open a dialog containing a CAPTCHA.

The return value of the verifyWithRecaptcha() method is a Task object. By attaching an on-success event handler to it, you'll be able to acquire a RecaptchaTokenResponse object containing a token you can use to tell if the user passed or failed the CAPTCHA. Here's how:

4. Validating CAPTCHA Tokens

The token you got in the previous step must again be passed to the reCAPTCHA service to check if the user passed or failed the test. However, this time, the call to the reCAPTCHA service must be made from your back-end server.

The server, of course, won't have the token unless your Android app sends it to it. Therefore, we must now write code to send tokens from the Android app to the server.

For now, let's assume that our server has an endpoint called validate, which can accept the token as a query string parameter. I'll be using 10.0.2.2 as the server's IP address and 8000 as its port. If you intend to run the server on your own computer and the app on an emulator running on the same computer, you too can use the same IP address.

You can now call the httpGet() method offered by the Fuel library to send the token to the server. The method expects a list of query string parameters as its only argument, so I suggest you use the listOf() utility method to create a list containing a single item: the token assigned to a query parameter named user_token.

Because the httpGet() method runs asynchronously, you must call the responseString() method in order to handle its return value. The following code shows you how:

You can see that we now have access to a result object. In case of no errors, it will contain our server's response as a string.

Let's assume that our server returns the string "PASS" if the user passes the test, and "FAIL" otherwise. What you actually do when the user passes or fails the test is, of course, up to you. For now, I suggest you simply display appropriate Toast messages. The following code shows you how to do so concisely:

At this point, the app is ready. You can go ahead and deploy it to your emulator or device.

CAPTCHA dialog shown when user presses the button

5. Creating the Server

We made a lot of assumptions about our web server in earlier steps. It's now time to create it, making sure that it doesn't deviate from those assumptions.

A quick and easy way to create a fully functional web server is to use the Node.js platform and the Express.js framework. To create a new Node.js project, make a new directory on your computer and run the npm init command inside it.

To add the Express framework to the project, you can use the npm install command.

Additionally, we'll be needing the Request package to communicate with the reCAPTCHA service. Therefore, install it as another dependency.

You can now use your favorite code editor to create a new file called index.js and start writing all the required server-side code.

Start by loading both the express and request modules using the require() function and creating a new Express application by calling the express() function.

Our Express application must have an endpoint called validate, which can be accessed using the HTTP GET method. Therefore, create a new route for it using the get() method:

To validate the token generated by the Android app, you must now make a POST request to the reCAPTCHA service. The request must contain your secret key and the token itself. The following code shows you how to build the POST request's body by extracting the token from the query string:

To actually make the POST request, you can call the post() method of the request module. Its response is a short JSON document containing a key called success. As you might expect, its value is true only if the user has passed the test.

The following code shows you how to parse the JSON document, extract the success key, and generate the "PASS" and "FAIL" responses our Android app needs:

Lastly, you must call the listen() method of the Express application object to allow it to listen for connections.

At this point our web server is ready. To start it, return to the terminal and run the following command:

If you run your Android app now, press the button, and successfully solve a CAPTCHA, you should see a Toast message telling you that you are human.

Toast message shown when user passes the CAPTCHA

Conclusion

You now know how to use the SafetyNet reCAPTCHA API to secure your Android app and back-end infrastructure against bots. You don't have to worry about automated signups, screen scrapers, or bot-generated spam any more.

To learn more about the reCAPTCHA API, you can refer to the official documentation.

In the meantime, check out some of our other great posts on Android app development!

  • Android SDK
    How to Create an Android Chat App Using Firebase
    Ashraff Hathibelagal
  • Android Lollipop
    Getting Started With RecyclerView and CardView on Android
    Ashraff Hathibelagal
  • Android
    How to Get Started With Push Notifications On Android
    Ashraff Hathibelagal

July 11 2017

14:15

Get Started With the WPCOM.js WordPress API

The new WPCOM.js library lets you harness the power of WordPress to build a free and easy-to-update back-end for your web or mobile apps. In our new short course, Get Started With the WPCOM.js WordPress API, you will learn how to use WPCOM with a WordPress.com site. 

What You’ll Learn

In this quick half-hour course, Envato Tuts+ instructor Reggie Dawson will show you how to retrieve public content from your site, how to set up authentication tokens, and how to create and edit posts with the easy-to-use WPCOM JavaScript API.

WPCOM JavaScript API

By the end of the course, you'll have the information you need to start using WPCOM.js for your web or mobile apps.

Watch the Introduction

 

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 200,000+ photos and 26,000+ design assets and templates. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

And to speed up your WordPress development work even more, why not check out the range of useful WordPress plugins we have available on Envato Market.

13:37

15 Best iOS App Templates of 2017

Building an app used to be the domain of hardcore developers only, but with over 1,400 app templates for sale at CodeCanyon, even complete beginners to coding can build an app.

But what is an app template, you might ask. Well, essentially, it’s an app with core functions already implemented for you so that you can customise it easily and add the elements you most prefer to the app's code to create the product you want. 

Many beginners use app templates as a learning tool to improve their coding skills, while others choose to upload their new app creations to iTunes for approval and inclusion in the app store.

Whatever your needs, get started by taking a look at the 15 best iOS app templates available at CodeCanyon. You may just find exactly what you’re looking for.

1. Universal for iOS

The magic of the Universal for iOS app template is that it lets users create just about any app they want by pulling in unlimited content from blogs, timelines, feeds, channels, playlists, webpages, etc., and easily combining them in one customisable app.

Universal for iOS

One of the best-selling iOS app templates at CodeCanyon, Universal for iOS supports most popular web resources, like WordPress, YouTube, Facebook, RSS, etc. It also supports AdMob and gives your users the option of removing banners and interstitial ads with an easy in-app purchase.

The app is completely based on Objective-C and designed for the latest version of iOS. It comes with step-by-step instructions and video tutorials on how to configure your template from scratch and is suitable for both professionals and beginners as no code knowledge is required.

Customers say Universal for iOS is a “very good app” with “no crashes”.

2. BeoNews

There are a large number of users out there with a content-rich website that they want to convert into a gorgeous app, allowing their visitors to access the key features of the site easily and seamlessly. That’s what the BeoNews app template does. 

BeoNews

One of the best-rated templates in this category, BeoNews will allow users to convert any of the content of their WordPress site, including video, photos and blog, into a mobile app. How cool is that?

The app stores user data on Firebase and synchronises across devices.

Customers have praised the app’s design quality and the support offered.

3. WebViewGold 

Another app that allows you to convert your website content into an app, WebViewGold app template’s key difference from BeoNews is that it enables users to turn their entire site into an app. It does so by using a Swift Xcode package to wrap the URL or local HTML into an iOS app. The real genius of this app template, though, is that it does its work in just a few clicks. So no coding knowledge is required!

WebViewGold

One customer, zyn, said: 

“The script is awesome + the team is incredible …. They helped me integrate exactly what I need.”

4. MStore Pro

With so many businesses selling products and services online these days, the MStore Pro app template is an easy favourite among developers. The e-commerce app allows users to convert their existing online shop to a mobile store app so that they can more easily target busy shoppers who’re trying to make the most of their time by doing their shopping while commuting or waiting in a queue.

MStore Pro

The template requires no coding skills and is very easy to customise. It is fully integrated with WordPress and WooCommerce, supports PayPal, Stripe and COD, and allows users to log in with their Facebook account. What more could you ask for?

5. Mokets

Mokets, which stands for mobile markets, is another e-commerce app template targeting today’s busy shoppers. The app template distinguishes itself with a gorgeous Pinterest-type grid that displays items for sale with all relevant information. It features user registration and login, shopping cart with checkout, transaction history, Apple push notification, user feedback, analytics which track customer interests, and so much more.

Mokets

Customer, Simorq, said:

“Apple approved my app just 5 mins ago. The app is really great and works well.”

6. woopy

As sustainable living becomes more and more critical, apps that allow users to buy and sell used items and handcrafted items have grown in popularity. woopy is an app template that allows developers to create listing apps that facilitate such buying and selling online. Users can browse by keyword or category. They can also chat with sellers or potential buyers and give feedback on each transaction.

woopy

One of the app’s outstanding features for sellers is the ability to add a 10-second video to their listings. Another is the app’s optional email verification system that gives buyers and sellers extra assurance by posting a verification symbol next to the user’s name.

Customer Kaya09 said: 

“Great support, well designed and code is perfect and no issue with iTunes, approve in a few hours.”

7. Store Finder v1.9

Though we all know that online shopping is becoming more and more popular, most seasoned shoppers will admit that shopping in person gives a certain sensory pleasure that online shopping cannot emulate.

 Store Finder v19

When you need to find a specific item or store, however, and don’t want to spend all day driving from one end of town to the other or doing laps around the mall, a store finder app is a lifesaver. Enter the Store Finder v1.9 app template, a developer’s dream, with a long list of must-have features like call, email and SMS integration, Google directions, social media logins, pinch and zoom function, and so much more.

Customer reviewer larrybird1 said about the app:

“This is a fine code, from a fine developer … oh, and the support is pretty good.”

8. Restaurant Finder v1.5

Restaurant finder apps are always popular because they solve a common problem: how to find a good place to eat when you’re in a neighbourhood you don’t know. The Restaurant Finder v1.5 app template allows you to create your own app to help users looking for restaurants in a specific area. 

Restaurant Finder v15

The template uses an XML/JSON file for restaurant data, so you have full control over the restaurants you want to include as well as the amount of information you want to include about each restaurant.

This Objective-C-based app template supports AdMob.

9. PhotoGram

If you’re passionate about photography (and really, who isn’t these days?), you’re always on the lookout for photo editing apps that make your photos look even better than they already do when you post them to Instagram, Facebook, or your preferred social media site. 

 PhotoGram

The PhotoGram app template requires no configuration and is easy to customise. Some of its selling features that will keep users happy are its filters, tonal adjustments, resizing, and cropping. Users can also add text to their images and share them directly from the app on Facebook, Instagram, Twitter, etc. The app supports both iAd and AdMob.

Customers confirm that PhotoGram is indeed “easy to customise” with “clean code.”

10. PikLab

Owing to the popularity of photo editing apps, we’re featuring not just one but two photo app templates in our best of 2017 roundup. The PikLab app template has fewer bells and whistles than the previous PhotoGram app template, and that is its main selling point. It will appeal to users who prize simplicity and ease of use and are looking for a photo editing app that allows for a bit more creative play by using features such as collage frames, stickers, borders, textures, and custom fonts. Users can also share their pictures directly to Facebook, Twitter, Instagram, WhatsApp, etc.

PikLab

The app is AdMob ready, and includes PSD graphics and a PDF user guide.

One happy customer, tunebaco, said: 

“Code, Design, Documentation, support! Everything is perfect with this guy!”

11. iOS Recipe App

Cooking shows, cooking competitions, cooking websites, Instagram food porn. In the last decade or so, we’ve become positively obsessed with food and how to prepare it well. So of course recipe apps have gained in popularity as well, and developers will love the iOS Recipe App template.

iOS Recipe App

iOS Recipe App allows users to organize their recipes into categories, which are accessible both from the home screen and the menu. Users can build their own favourite category and add both video and images to each recipe. Other features include push notification, search, shopping list, and the ability to share recipes. The app also supports AdMob.

12. Feedews

Another thing that has proliferated in the past ten years is the number of blogs and online independent and alternative news sources we have access to—so much so that it is impossible to keep track of our favourites without a good RSS feed reader. Feedews is a highly customisable RSS feed reader app template that allows users to get all their articles and news in one place. 

Feedews

Users can organise their sources into categories and can share articles with their social networks or via email. The template also supports the translation of the app into other languages.

Many users say the app is “well designed and documented”.

13. ToDo List and Task Reminder

If you accept that good organisation is key to high productivity, then a to-do app is an indispensable tool for you. The ToDo List and Task Reminder is one of the newest iOS app templates on CodeCanyon and has a few cool features that will interest developers in the market for an organising app.

ToDo List and Task Reminder

The app allows users to set tasks according to their priority from high to low and displays either a progress wheel of their task or a pie chart based on the priority you’ve assigned it. It includes a map feature which allows users to mark the place where the task is taking place. 

Users can also include an image with a task and set reminders using their favourite ringtone or set each reminder with a different tone or talking alarm. Best of all, users can create secret lists that they can keep hidden from prying eyes. These are just a few of the great features that set this app apart from other to-do list apps already on the market.

14. Mustage

Love Instagram? Want to create your own Instagram-type app? We have just the thing for you. The Mustage app template allows developers to create a photo and video sharing app in the vein of Instagram where users can follow, like, comment and share photos. 

The app allows users to log in with their email, Google or Facebook accounts and supports monetisation with AdMob. It also supports push notifications and comes with built-in Analytics to monitor performance.

Mustage

Customers have not only been impressed with the template itself, but have also commented on the high quality of support offered to customers. One such customer, birdiesawyer, said: 

“This template is AWESOME and as a person learning Swift I can see how things were structured and why they were structured that way. The support has been outstanding and every question I had was answered to my satisfaction.”

15. Four Dots

Our roundup of the 15 best iOS app templates wouldn’t be complete without including a game, and our choice to round out the list is the highly rated Four Dots game template.

Four Dots

This game is made up of a cluster of four circles, each of a different colour, at the bottom of the screen. Once the game begins, dots are randomly generated from the top of the screen and fall down the screen towards the cluster. The player must rotate the cluster of circles at the bottom of the screen by tapping the screen quickly so that the circle facing the falling dot matches it in colour. For every correct match, the player gains a point. 

Give it a whirl. I dare you to not get addicted. The template supports AdMob and comes with PSD files and a comprehensive user guide.

Conclusion

These 15 best iOS app templates of 2017 are just a small selection of the hundreds of iOS app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills building iOS apps and templates, then check out some of the ever-so-useful iOS tutorials we have on offer!

  • Swift
    What's New in Swift 4
    Patrick Balestra
  • iOS SDK
    In-App Purchases in iOS With Swift 3
    Francesco Franchini
  • iOS
    How to Add AdMob Banner Ads to Your iOS Swift App
    Francesco Franchini

Or, if you want to really dig in and learn iOS development, check out one of our comprehensive video courses!

  • Swift
    Create iOS Apps With Swift 3
    Markus Mühlberger
  • iOS
    Go Further With Swift: Animation, Networking, and Custom Controls
    Markus Mühlberger

12:00

Should You Use a PHP Framework? Five Pros and Cons

From routing HTTP requests to accessing the database and rendering the user interface, most web applications have a lot in common with each other. Many of them allow their visitors to sign in, and it's hard to imagine a web application without email sending. 

A software framework is a way to put this observation into use. 

By extracting the common traits and the application's underlying architecture and bundling them into a reusable template and collection of libraries, a framework allows developers to focus on what makes their project stand out.

In fact, when you use your previous project as a boilerplate instead of starting from scratch, you are already using an ad-hoc framework. The popular PHP frameworks—such as Laravel, Yii, or Symfony—take this approach to its logical conclusion by placing a strong focus on designing the framework's architecture and tooling and then making it available for other developers to use in their projects.

But is using a framework always the best way to go, or does it sometimes make sense just to start from scratch using nothing but plain PHP? 

To answer the question, in this tutorial, we will look at five pros and cons of using a PHP framework.

Five Pros of Using a PHP Framework

Let's start by looking at how using a PHP framework can help you in your application development.

1. Rapid Development

In today's startups based on experimentation, rapid prototyping, and getting your minimum viable product out in the world as fast as possible, development speed can be what makes or breaks your business.

Using a PHP framework is one way to answer this requirement.

A well-designed PHP framework selects the best implementations to common problems from the open-source community and, building on top of them, provides you with an application architecture (in most cases, based on the Model-View-Controller pattern) to guide your development.

This way, instead of spending time planning your application's architecture and evaluating the various libraries available, you get to start from a fully functional, if bare bones, template and get right to building the features specific to your application. Many PHP frameworks also come with a command-line tool that you can use to generate code and save more of your precious development time. 

2. A Framework Makes Your Application More Secure

While speeding up your development, a framework can also make you more secure: You are working fast, but that doesn't happen by hacking your way using quick and dirty solutions but �by using proven best practices and ready-made components.

The solutions included in a modern PHP framework are continuously tested and peer reviewed and validated by multiple developers using the framework. As the frameworks are open source, security issues and other �problems that you might overlook in your proprietary code get quickly noticed and fixed.

That said, it's important to remember that using a framework doesn't mean you can forget all about security and good development practices. Make sure you use the framework as it is meant to be used, keep it updated, and do your part in things such as parameter validation—using the frameworks' tools, it isn't all that difficult.

3. Easier Maintenance

By providing a sound structure for your application and nudging you towards software development best practices and patterns, a PHP framework guides you towards writing code that is loosely coupled and repeats itself as little as possible. In other words, it's easy to read, test, maintain, and develop further. 

Virtually all popular PHP frameworks today are object oriented and developed with automated testing and even test-driven development in mind.

You will still have to do your part. But compared to starting from scratch, a framework and its documentation reminding you of the concepts and nudging you towards using them will surely help.

Another way in which using a framework makes maintaining your application easier is through its shared components. As the framework libraries and helpers are developed independently of your application, you get to offload a big part of your application's maintenance to the framework developers.

In a way, it's like having a team of developers working for you, for free!

4. Stronger Teamwork

As a developer, you know your classes and functions by heart and can use them easily. But as you bring in team members, the situation changes. 

Without knowledge of your design decisions and complete documentation (let's face it: especially in the world of rapid development, documentation is often an afterthought), they will find it hard to wrap their heads around your application's code.

Using a PHP framework �will help make it easier for new developers to get started with working on the project. Chances are they are already familiar with the framework and can put all of their attention into understanding the specifics of the application. And even if the framework is new to them, the documentation, �online tutorials, and the familiar design patterns will help them get up to speed with minimal effort. 

All this while you can keep working on the application rather than teaching the developers your ways of thinking.

5. The Community Is There for You

Finally, a significant benefit of using a PHP framework comes from the active communities of developers and users that gather around them.

All major frameworks attract open-source contributors who, in addition to working on the framework itself, develop additional widgets, libraries, and helper components for others to include in their applications. �Other contributors write tutorials and books or create videos to explain the ins and outs of how they use the frameworks in real-life projects.

As a part of such a developer community, you will grow as a developer, learning quickly and applying what you learn to your application development.

And if you are so inclined, you can give back and participate in the open-source projects in any way that feels natural and fulfilling to you.

Five Cons of Using a PHP Framework

Now that we have seen how using a PHP framework can help you in your development, let's take a look at the downsides and why going without one might sometimes be the better option.

1. Slower Execution

Compared to running a simple PHP script, a PHP framework always adds complexity and overhead in the form of classes and libraries loaded before your code even gets called. The difference can be significant in quick scripts and APIs with a limited set of functionality that needs to run fast. 

In most web applications, however, the efficiency implications of a framework have more to do with how you use it than the framework itself. For example, while an Active Record implementation is a handy way of accessing the database, it doesn't make sense to use it in places where you have to work on multiple rows in the database at once. 

So this comes down to knowing your application's needs, but also not allowing yourself to be attached to a specific way of using it. Sometimes, even when working with a framework, it makes sense to sidestep and write some of the code at a lower abstraction level.

2. General Solutions for Specific Problems 

The idea of a PHP framework is to be a general solution for the recurring requirements most developers will face in developing a web application. But where should we draw the line in what to include in the framework and what to leave for the applications—or third-party add-ons—to implement?

According to some developers, this is where many frameworks go wrong. 

PHP's creator, Rasmus Lerdorf, has said: 

“Nobody has a general problem. Everyone has a very specific problem they’re trying to solve. And a general purpose framework, while it can solve it, usually solves it in a way that you get so many other things that you don’t need. That ends up being done on every request.”

Because of this, if you decide to use a framework, it's important to make sure you pick one that fits your application's needs. 

While most frameworks are based on lazy loading and won't include the parts of the framework that your application doesn't use, the added complexity will still be there, leading to unnecessary tinkering in removing functionality that came with the framework but that you don't need.

3. A Framework Takes Time to Learn and Master

While a PHP framework nudges you towards good code, it is no guarantee for it. If you work with a framework without understanding it and the design patterns behind it, you will most likely end up with a big, structured mess.

For someone who is already familiar with these design principles, from other frameworks or projects, the learning curve will be relatively short. For a developer with less experience, learning will take longer. Not to mention mastering the framework.

So, if you are in a hurry—and your project is small—it may not be the time to start learning a new framework. Instead, consider using a micro-framework or even starting from scratch and using some libraries you are familiar with. 

Then, take the time to learn a full-blown PHP framework when your schedule allows.

4. Limited Visibility and Control

Using a software framework moves your application development to a higher level of abstraction. This is by design, and usually a good thing. However, it's good to realize that it too can lead to problems.

While many parts of the framework's template are meant to be customized, the framework's core and its libraries are like a black box you use but don't have much control over. You may suggest improvements but ultimately, it's up to the framework's developers to decide whether they will include that change or not.

Also, if you start using a framework before fully understanding the PHP language itself, you may confuse the framework's features with language features—and will end up using the framework's functionality even when plain PHP would be a better choice.

5. A Framework Introduces an External Dependency

A framework is always an external dependency for your application—code controlled by someone other than you and your team. While this is usually not a problem, it's something worth considering if the software you are building is a core part of your business

Ask yourself what you will do if the framework’s development is dropped or moves in a direction you don’t want to follow. 

A good way to mitigate this risk is to use a reliable, popular framework with an active community of developers and users. But even then, it's something to give some thought to: are the benefits of using a framework big enough to make the risk worth taking?

Conclusion

A modern PHP framework is a powerful tool in a software developer's tool chest: it can save you a lot of time and effort and provide peace of mind as you develop your PHP application. Just remember that this shouldn’t replace learning core PHP first!

The key in the above conclusion, however, is selecting the right tool for the job. Every project is different, and even a framework that is perfect for one project might not be quite right for the next. Go for simplicity and ask yourself if a full-blown framework is right for the project, or if using a micro-framework such as Lumen could be a better solution. 

Starting from scratch using vanilla PHP is rarely the best option, but that too is worth considering when developing a very simple application (such as a website without much interactivity)—and remember that you can always extend it by using Composer to pick libraries of your choosing.

When selecting a framework, make sure the framework you choose is actively developed and supported and follows sound software engineering practices. This way, you're future-proofing your application by making sure the underlying framework will not suffer a quiet death.

And finally, even if you decide not to use one, it's a good idea to get familiar with one or more of the modern PHP frameworks. Studying them is an excellent way to learn and improve your craft in software development and help you stay on top of the evolving world of PHP development.

Additional Round-Ups

July 10 2017

12:00

Essential Meteor Tips

The Meteor project is an open-source web app development platform that enables you to create apps written entirely in JavaScript. 

Meteor provides development tools for essential web app needs, making it naturally suitable for start-ups and new projects in general. It offers features such as deployment to many devices from one code base (iOS, Android, Desktop), with hot push updates supported out of the box. 

This means that you can update the app on the user's device, without waiting for App Store approval. The wealth of packages available via npm and its own Atmosphere library make Meteor an interesting tool to work with.

Rapid Development in Meteor

One of the main reasons I started using Meteor, three years ago now, was the rapid ability it has to deliver a working web app within hours. It enabled me to deliver for my clients' high expectations and their pre-first-round funding budget. 

Finally, with this web framework that can accommodate big ideas with humble beginnings, top-quality reactive mobile web apps are within the reach of a single-person development team. 

NPM + Atmosphere Packages

Any package from npm is available in Meteor, so if you like using tools like Grunt, Browserify, Webpack, Bootstrap, React, jQuery and Angular, you will have no issues using these in Meteor. 

To search for new packages:

To install an npm package in Meteor, just run:

Running this command will update your package.json with the dependency, and also download the package into your app’s local node_modules/ directory. 

Version Control

An important note: For portability, I recommend you don’t commit the node_modules/ into git, and on passing to a new developer instead ask them to run meteor npm install, which will install all of the packages required.

User Accounts

Meteor accounts-ui

The accounts-ui package enables users to log in and register for the app, and it also gives oAuth support, interfacing it with Meteor Accounts. 

For brand and communication purposes, customizing the email verification (sendVerificationEmail) or invitations (sendEnrollmentEmail) to fit the overall theme of the app is a common request.

A great way to do HTML email in Meteor is to use the pretty emails package by yogiben.

Now you can change the verification email with just a few lines:

For your company information, you can configure PrettyEmail.options like so:

To send the email out, use the following methods:

If you want to add a template, you can do so by customizing the following options:

Changing styles is also very easy:

Here is an example of the activation email the user will receive in their email client.

Pretty Emails activation email

Pretty email has a whole ton more options for social, back links, the header and footer and so on—read more on the manual page.

Ratchet, Materialize and Bootstrap Support

There are also user accounts packages for each of these popular front-end libraries, as well as Ionic. Each can be fully configured to meet your needs.

  • Ratchetmeteor add useraccounts:ratchet
  • Ionicmeteor add useraccounts:ionic
  • Bootstrapmeteor add useraccounts:bootstrap
  • Materializemeteor add useraccounts:materialize

UI

Similar to the user accounts, there are packages available for popular front-end libraries like Bootstrap, Angular, React and the Blaze template engine, along with many others such as Semantic UI

Searching on atmosphere yields many results; here are some of my favorites:

React + Bootstrap

You will need to have installed the React npm packages first with:

Now, for the meteor package, run meteor add universe:react-bootstrap.

You can use Bootstrap components within your React JSX now:

Page Transitions

If you are using Iron Router then you can utilise the meteor-transitioner package. Working on your Blaze template, add the following handlebars around your {{yield}}:

Now set the transition between routes:

For more information on transitions, check the README.

Mongo

For editing your mongo database in the web browser, the Mongol tool is one of the best I have used. Once you have installed Mongol with:

Just press Control-M and you will have access to your collections with full in-browser CRUD support. 

I find using Mongol very useful when debugging new apps or data changes to existing ones. 

Mongol for debugging

Browser Extensions

For users who are working in Chrome, there is a Mongo plugin available called MiniMongo which will enable you to browse the Meteor database in the developer tools pane.

The MiniMongo Explorer project is available on GitHub if you want to build the source yourself.

Deployment

Using the excellent free tool mup, you can deploy a site to a Digital Ocean VPN within minutes. 

The configuration is very simple, and you will only need to have your app, SSH credentials, and maybe an SSL certificate if you would like to enable HTTPS.

To set up mup, start by making a directory for deployment:

Install mup:

Initialize the directory:

Now you need to configure the deployment by setting up the mup.js file that has been created via the previous step.

Now set up the server:

And deploy:

You will see confirmation of each step of the process in your terminal. Once the deployment has finished, the app is now live on your server, and you can check it out in your browser.

For more information on configuration with SSL, please refer to this guide.

Caching

Meteor comes with appcache, which will cache the app after the first load, but not for offline usage. 

If you would like to cache offline then you will need to use GroundMeteor. This is a client-side only storage which works on LocalCollection.

For an example, we can monitor a collection and store it locally:

Here, the contents of the Data.find() publication will be cached into an offline Ground Collection.

Key Stores Caches

For memory keystore caching, you can use the memcache package or redis package to enable you to access data caching on the server. 

The package assumes the memcache or redis server is already running, and then a key can be stored in memcache.

Or in Redis Collection:

The redis implementation is very nice as it can be used to broadcast via the publish/subscribe architecture of Meteor.

Development Tools

Besides the tools already mentioned, the Firebug-like browser extensions available in Chrome for Meteor make debugging a lot easier. You can monitor the data being passed from the server to the client easily inside the DDP tab and review your Blaze template via the Blaze inspector.

Reviewing a Blaze Template

IDE Tools

For development in Sublime text editor, a custom version of the Tern.js package provides autocompletion for Meteor. Download it on GitHub.

JetBrains provides automatic integration of Meteor projects with syntax highlighting and debugging. Atom also provides several packages for syntax, code snippets, and autocomplete. 

Boiler Plates

Yeoman

If you just want to get going quickly with an app that's already set up, you can look at yogiben's starter. The Meteor chef also has an excellent base starter. If you want to use React, you can look at this Yeoman generator for a starting point.

For further help in starting your app, Meteor Kitchen will provide a GUI for routes and configuration. 

Admin Panels

AdminLTE theme admin panel from Yogiben

If you are using Yogiben's Meteor Starter, you can also be sure the admin panel he has created will work fine in conjunction. Almost all other projects that are using mongo and blaze should be suitable for this, although React Router apps may have a conflict with Iron Router.

The theme for the admin panel is extensibly modifiable, and you can read the documentation.

Meteor From Meteorites

Meteor Preview 052

Before we wrap up here, let me give you some background on the Meteor project. Meteor was publicly released in January 2012, the results of a Y Combinator incubator project which received $11.2 million in funding from venture capitalist firm Andreessen Horowitz. 

It initially launched with a package manager named Meteorite (mrt on the cli), and extendability has always been a core element to Meteor. With the release of Meteor 0.9, things changed for good with the inception of Atmosphere packages.

Adding packages to Meteor apps became as simple as meteor add mrt:moment.

As momentum for the project continued, it garnered public interest and was adopted by a wide range of developers old and new. One of the core drivers for this, I believe, was the flexibility of being able to work fully in JavaScript—client and server.

Initially, npm packages were not available, until Meteor released version 1.3, which marked a serious milestone in the development cycle so far. 

Working in JavaScript fully throughout meant Meteor had the ability to interface with the vast library of existing JS and Node libraries now with the integration of npm. This gave Meteor a cutting edge as a framework.

It gives perspective of our progress in web development certainly to think of the sheer magnitude of power that Meteor, npm and its atmosphere packages deliver to your fingertips. This is a big change from how we used to do it, with a large development workforce, in the pre-jQuery, pre-npm, pre-Bower days of Flash, NotePad/Dreamweaver and PHP 3. I have worked on teams of over ten employees to produce works which, without sounding ridiculous, can be literally finished in weeks in Meteor by one or two developers. 

With these tools at your disposal, there has never been a better time to be a technically minded web entrepreneur. Building your dream apps yourself is certainly within reach.

For an example, earlier today I put together a database-backed CMS with a complete user system and admin back office with Facebook and Google+ oAuth logins. I deployed it to a new server to share with people to debug, and I could see the data being changed in real time. 

Meteor is really that fast to work with. Form validation is done and proper data entry work can begin tomorrow, after just eight hours development time.

Conclusion

Meteor is a robust and powerful web application engine that will give you a head start in app development.

Hopefully the packages and advice mentioned here will enable you to make your app in no time at all. For me, realizing my app ideas in a short time span can mean creativity flourishes and innovation is easier. 

You can speed through development with ease as in Meteor there is practically a package for everything, and more of the focus is on configuration, which makes the development experience much nicer.

To get support with issues on a specific project, you may wish to search the project on GitHub and make an issue on the repository for the developers to deal with.

If you are looking for more advice on Meteor, the official forums are always a good place to ask.

July 07 2017

12:00

Python's Pickles

Pickles in Python are tasty in the sense that they represent a Python object as a string of bytes. Many things can actually be done with those bytes. For instance, you can store them in a file or database, or transfer them over a network. 

The pickled representation of a Python object is called a pickle file. The pickled file thus can be used for different purposes, like storing results to be used by another Python program or writing backups. To get the original Python object, you simply unpickle that string of bytes.

To pickle in Python, we will be using the pickle module. As stated in the documentation:

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”.

The pickle module allows us to store almost any Python object directly to a file or string without the need to perform any conversions. What the pickle module actually performs is what's so called object serialization, that is, converting objects to and from strings of bytes. The object to be pickled will be serialized into a stream of bytes that can be written to a file, for instance, and restored at a later point.

Installing pickle

The pickle module actually comes already bundled with your Python installation. In order get a list of the installed modules, you can type the following command in the Python prompt: help('modules').

So all you need to do to work with the pickle module is to import pickle!

Creating a Pickle File

From this section onwards, we'll take a look at some examples of pickling to understand the concept better. Let's start by creating a pickle file from an object. Our object here will be the todo list we made in the Python's lists tutorial.

In order to pickle our list object (todo), we can do the following:

Notice that we have made an import pickle to be able to use the pickle module. We have also created a pickle file to store the pickled object in, namely todo.pickle. The dump function writes a pickled representation of todo to the open file object pickle_file. In other words, the dump function here has two arguments: the object to pickle, which is the todo list, and a file object where we want to write the pickle, which is todo.pickle.

Unpickling (Restoring) the Pickled Data

Say that we would like to unpickle (restore) the pickled data; in our case, this is the todo list. To do that, we can write the following script:

The above script will output the todo list items:

As mentioned in the documentation, the load(file) function does the following:

Read a string from the open file object file and interpret it as a pickle data stream, reconstructing and returning the original object hierarchy. This is equivalent to Unpickler(file).load().

Pickles as Strings

In the above section, we saw how we can write/load pickles to/from a file. This is not necessary, however. I mean that if we want to write/load pickles, we don't always need to deal with files—we can instead work with pickles as strings. We can thus do the following:

Notice that we have used the dumps (with an "s" at the end) function, which, according to the documentation:

Returns the pickled representation of the object as a string, instead of writing it to a file.

In order to restore the pickled data above, we can use the loads(string) function, as follows:

According to the documentation, what the loads function does is that it:

Reads a pickled object hierarchy from a string. Characters in the string past the pickled object’s representation are ignored.

Pickling More Than One Object

In the above examples, we have dealt with pickling and restoring (loading) only one object at a time. In this section, I'm going to show you how we can do that for more than one object. Say that we have the following objects:

If you would like to learn more about Python dictionaries and tuples, check the following tutorials:

We can simply pickle the above objects by running a series of dump functions, as follows:

This will pickle all the four objects in the pickle file pickled_file.pickle.

There is another wonderful way to write the above script using the Pickler class in the pickle module, as follows:

To restore (load) the original data, we can simply use more than one load function, as follows:

The output of the above script is:

As with the Pickler class, we can rewrite the above script using the Unpickler class in the pickle module, as follows:

Note that the variables have to be written and read in the same order to get the desired output. To avoid any issues here, we can use a dictionary to administer the data, as follows:

To restore (load) the data pickled in the above script, we can do the following:

Pickles and Pandas

Well, this seems an interesting combination. If you are wondering what Pandas are, you can learn more about them from the Introducing Pandas tutorial. The basic data structure of pandas is called DataFrame, a tabular data structure composed of ordered columns and rows.

Let's take an example of DataFrame from the Pandas tutorial:

In order to pickle our DataFrame, we can use the to_pickle() function, as follows:

To restore (load) the pickled DataFrame, we can use the read_pickle() function, as follows:

Putting what we have mentioned in this section all together, this is what the script that pickles and loads a pandas object looks like:

Conclusion

In this tutorial, I have covered an interesting module called pickle. We have seen how easily this module enables us to store Python objects for different purposes, such as using the object with another Python program, transferring the object across a network, saving the object for later use, etc. We can simply pickle the Python object, and unpickle (load) it when we want to restore the original object.

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.

July 06 2017

18:43

10 Best iOS Game Templates

Have a great idea for an iOS game but are turned off by the hours of tedious work involved in bringing your concept to life? Well, that’s what templates are for. Why waste time reinventing the wheel when CodeCanyon is filled with a brilliant range of iOS game templates that will help you cut through the drudgery and focus on the best parts of creating your own game?

To get you started, we’ve scoured through the almost 300 iOS game templates we have available and found the ten best and most current we have available today.

1. FIVES

One of the top sellers at CodeCanyon, FIVES challenges players to create as many five-letter words as they can before the game’s timer runs out. Every time players match a word the timer decreases its time a little, to give them a bit of a reward. Players also have the option of sharing their best scores on Facebook and Twitter.

FIVES game template

The FIVES template uses Xcode 8.x and Swift. It supports internationalization to multiple languages and comes with a comprehensive PDF User Guide to help you customise the game to suit your interests and tastes.

Users have commented on the template's “excellent code”, “good documentation” and “great support follow up”.

2. Brain Teaser

A great app for priming the memory and deepening concentration, the aim of Brain Teaser is for players to remember and draw connections between faces, shapes or words displayed.

Brain Teaser

The template is designed to be edited with Xcode. It's easy to reskin and supports AdMob out of the box.

3. iMath Educational Game for Kids

Designed to increase concentration and enhance problem-solving skills and information-processing speeds, iMath is a fun app that challenges children and adults alike to complete basic addition, subtraction, multiplication and division equations under time constraints.

iMath

The app is easy to reskin and supports monetisation with Chartboost and AdMob ads. It also includes Yahoo Flurry Analytics so that you can track every aspect of your app's performance. This template is written in Objective-C.

4. Sudoku

Sudoku is a popular puzzle game that initially displays a partially filled grid. The aim of the game is to fill each square with a number from 1 to 9. Each number can only appear once in the same column, row or 3 x 3 box. This app comes in five levels—from easy to expert—and once begun a level can be saved to continue playing later.

Sudoku

Written in Objective-C, the template supports AdMob and is easy to reskin.

5. Catch The Monsters Geolocation Game

Following on the huge popularity of Pokemon Go, the goal of Catch The Monsters is for the player to find monsters in their area or an area they're visiting. When the app locates a monster, the player needs to get within at least 50 meters of them in order to catch them, earn points and move up the Top 10 Leaderboard. Players can also share their stats on social media, by mail or SMS.

Catch the Monsters game template

The Catch The Monsters template comes with an admin interface, using the Parse SDK on back4app, that allows an administrator to name the monsters and place them in anywhere in the world. The app comes with a PDF User Guide and PSD icons included.

It's one of the best rated apps in its category on CodeCanyon, and users comment that Catch The Monsters has “easy code, great design, excellent customer support”.

6. 2048 Rounded

The 2048 Rounded game is a spin-off of the classic 2048 number puzzle game. The aim of the game is to get one tile to the number 2048 as quickly as possible by swiping the numbered tiles up, down, left or right so that matching tiles merge and are added together. 

2018 Rounded

The template is written in Swift and can be edited with Xcode. AdMob is supported for easy monetization.

7. Flappy Clumsy Dragon

Tap the screen to fly the Flappy Clumsy Dragon, avoid obstacles, and fight with enemy birds. The best score is displayed on the leaderboard, and players can share results on Facebook and Twitter.

Flappy Clumsy Dragon

Graphics aren’t included with this template, so you'll need to reskin it with your own assets. The developer has created a reskinning tutorial to make it easy for you to create your own version of the game. 

The template is made with the Lua language and the Corona SDK, so it will be easy to create an Android version too, if you want. The template also allows admins to include a popup window to encourage ratings. If you want to see how it works, you can try the demo right now on the Apple App Store.

8. Rush Hero Game

Made with Cocos2dx and Objective-C, the aim of the Rush Hero Game is to move the hero to the left or right out of the path of falling rocks which will crush him. The template includes some fun graphics and great sound effects that are triggered when the hero gets hit. 

Rush Hero Game

The game comes with layered PSD files for all the assets, which makes it easy to reskin. Some of its outstanding features are the best score and game rating social features, as well as support for monetization through ad networks and AdMob banners. It is also Game Centre integrated and comes with detailed instructions for customisation.

9. Dragon Jump

With the Dragon Jump template, the player is a knight defending the kingdom from dragons flying overhead. The player can jump on the dragons to kill them or can kill them with a spear. Players may share their scores on various social media.

Dragon Jump

This template is integrated with Game Centre, so users can share their highscores, as well as with Google Analytics, ad networks, and AdMob banner ads for easy tracking and monetization. The template also comes with complete documentation to guide users through customisation.

10. Tic Tac Toe

One of the newest iOS games in CodeCanyon, this template for the classic Tic Tac Toe game allows players to play against the phone or against another player on the same phone.

Tic Tac Toe game

Coded with Swift 3 and the latest version of Xcode, the game interface is fully customizable through Storyboard. Detailed instructions for reskinning and customising are included.

The app will auto resize for various screen sizes and supports AdMob. Users have found that “the app functions really well.”

Conclusion

This is just a small selection of hundreds of iOS game templates we have available at CodeCanyon, so if none of these featured templates quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills building iOS games, head on over to the site and check out some of the ever so useful mobile development tutorials and courses we have on offer.

  • iOS SDK
    Create a Blackjack Game in Swift 3 and SpriteKit
    James Tyner
  • SpriteKit
    Introducing SpriteKit
    James Tyner
  • Swift
    Code a Side-Scrolling Game With Swift 3 and SpriteKit
    Derek Jensen
  • iOS
    Power Up Your Mobile Game With Design, Sound, and Music
    Bart Jacobs

12:00

CodeIgniter Form Validation: From Start to Finish

As a web application developer, form validation is a crucial part of your work, and it should not be underrated as it could lead to security flaws in your application. You should consider it a must if you're striving to provide a professional end user experience.

In this article, we'll go through the built-in form validation library in the CodeIgniter framework.

Here are the highlights of today's article:

  • Basic form validation
  • Cascading and prepping
  • Custom error messages
  • Custom validation callback
  • Validation configuration

Go Through Basic Validation Rules

In this section, we'll go through the basic form validation concepts in CodeIgniter.

As a part of that, we need to create controller and view files. The controller file loads the validation library and runs validation rules against the submitted form data. The view file holds the form XHTML code, and we'll keep it simple for our needs.

Let's go ahead and create these two files.

Create the controller file application/controllers/Validation.php with the following contents.

Next, create the view file application/views/validate_form.php as shown below.

With this setup, you should see a form when you run http://your-codeigniter-site/validation/basic in your browser. Try to submit it without filling any of the form fields, and you'll see the list of error messages! Don't worry if you don't understand how it works altogether as we'll go through every piece of code in detail.

The story starts with the __construct method.

I always prefer to load common libraries and helpers in the constructor of the controller itself as it's a nice habit to avoid code duplication elsewhere in controller methods. That's exactly what we've done above—we load the form and url helpers so that we can use the utility methods provided by those helpers throughout the rest of the application.

Next, we load the form validation library so that it allows us to bind form validation rules on form elements, as we'll see in the very next section.

Let's go through the code of the basic method. What does this method do? If you call it with the GET method, it'll display the form, and if it was called using the POST method, it applies validation rules on the submitted data and displays error messages, if any, along with the form.

As we've already loaded the form validation library in the constructor, you can access it using the $this->form_validation convention.

The set_rules method is used to bind a validation rule on a form field. Generally, it takes three arguments:

  • The first argument is the name of a form field.
  • The second argument is a label that is used to reference a form field while displaying the error message for that field.
  • The third argument is the rule that you want to apply on a form field. The form validation library comes with lots of built-in rules that you could use already.

Let's go through some of these rules as we've used them in the basic method.

One of the most frequently used rules is the required rule, which makes a form field compulsory.

Next, if you want to make a form field of a certain length, you can use the min_length and max_length rules.

The first one makes sure that the min_text_field form field is a compulsory field and the user must enter at least eight characters in it. The second one puts a limit on the maximum characters that can be entered in the max_text_field text field, in addition to making it a compulsory field.

You may have noticed that we've used the | operator to apply multiple rules at once. It's called cascading, and we'll get back to it later.

On the other hand, if you want to make a form field of an exact length, you can use the exact_length rule.

What if you want to validate a form field to alphabets or alphanumeric only?

The next candidate is the email validation.

Next, the matches rule allows you to compare the value of a form field with another form field's value. The best example of this is the password field, which must match the password confirmation field when you submit the form.

The last example in our basic method is about validating the IP address.

The valid_ip rule validates the IP address against the first argument passed. In the following example, we're only looking for ipv4 type of IP addresses!

So that's it as far as basic validation is concerned in CodeIgniter.

How Cascading and Prepping Works

In this section, we'll explore cascading and prepping, which allow you to combine multiple validation rules in a single go.

In fact, I would say that we've thoroughly used cascading in our earlier examples. Recall that pipe operator that was used to combine multiple rules—and yes, the so-called cascading validation rules.

Grab the code of the cascade method.

As shown in the example above, we've applied four validation rules separated by the | operator to the text_field text box. So it has to go through each and every rule for the form validation to succeed in this case!

Give it a try and see how it works!

Next, there's a prepping that allows you to apply certain operations on the data that's being submitted. More often than not, you want to remove leading and trailing spaces in the user submitted data. Probably the first thing that comes to your mind in this case is to use the trim function, and the good news is that you can use it!

That's exactly what our prep method does.

As you can see, we've used the word trim in addition to validation rules. So the data is trimmed first, and then it'll go through the other validation rules. In fact, you could use any PHP function that takes a single argument as per the CodeIgniter documentation.

Try running our example by adding few trailing spaces, and see how it goes.

Customizing Error Messages

If you've had a chance to run the above examples, you may have noticed that the error messages displayed to the user are pretty systematic and machine generated. Maybe you want to be more creative and change them in certain cases.

Let's see how you could change the error message for any validation rule. Pull in the code of the custom_message method.

Please note the fourth argument supplied to the set_rules method. It contains an array of custom validation messages for each validation rule, and the key of each array item is the validation rule itself.

Give it a try, and you should see our custom error messages! Pretty cool, huh?

Custom Validation Callbacks

Although the built-in validation library provides a handful of validation rules already, there's always a need to create a custom one in your day-to-day development work. That's exactly what we'll discuss in this section.

To demonstrate that, we'll create a custom validation callback, and later on we'll see how to use it along with the set_rules method.

To start with, let's have a quick look at the custom_rule method.

It's no different than the usual set_rules method call except that we've provided the custom validation callback custom_validation instead of any core validation rule. The important thing to note here is that you need to prefix the custom validation callback with callback_ when you pass it as an argument.

Next, let's implement the custom validation callback.

When your custom validation callback is called, the value entered by the user will be passed as the first argument. So the $field_value contains a value that's entered by a user, against which you can implement your custom validation logic.

In the example above, you should see the error message if you enter either a blank value or demo in the text field Text Field Five. It's important to note that when you set the error message using the set_message method, the first argument is the name of the custom validation callback method itself.

And that's the story of custom validation callbacks.

Last but not least, it's the validation configuration that deserves some attention as we move towards the conclusion of this article.

Validation Configuration

As a CodeIgniter developer, you should already be familiar with the config directory, which allows you to configure different aspects of your CodeIgniter application.

For example, database.php allows you to define the database-related settings, while autoload.php allows you to define the components that should be auto-loaded during the bootstrapping of an application.

In the same way, you could create the form_validation.php file under the config directory and use that file to define application-level validation rules that can be used globally. If that sounds alien to you, there's no better way to understand it than actually looking at a practical example.

Create the file application/config/form_validation.php with the following contents.

Now, let's quickly look at what our configuration method looks like.

Try running http://your-codeigniter-site/validation/configuration and submit an empty form. You'll see error messages for three form fields! But wait, where do they come from, since we haven't set up any validation rules in our configuration method in the first place?

Users with sharp eyes would have noticed that it's automatically picked up from the validation configuration file defined at application/config/form_validation.php. Isn't that amazing? It allows you to centralize the rules in one place and reduces the code duplication in action methods.

In fact, you could group the rules and apply validation to the fields of only a certain group. Let's see how to do that.

Replace the code in application/config/form_validation.php with the following.

In your configuration method, find the following line:

And replace it with:

Now, try to submit an empty form, and you'll see an error for only Text Field One. That's because we've passed group_one as a group id, so only the elements in that group will be validated.

Finally, let's have a look at the type of configuration that allows you to define rules based on the URL.

Replace the code in application/config/form_validation.php with the following code.

In this type of configuration, you need to use a combination of the controller name and the method name separated by the / character. In this way, you could define rules for several action methods at once.

Now, you should see the error message for Text Field Three should you try to submit an empty form at http://your-codeigniter-site/validation/configuration.

And that ends the story of validation configuration and this article as well!

Conclusion

In this article, we thoroughly discussed form validation in CodeIgniter. 

We started our journey with the basic validation rules, and then we moved to more advanced topics like cascading, prepping, and configuration validation.

I hope you've enjoyed this article, and you can share your valuable views using the feed below!

July 05 2017

13:00

Creating a Blogging App Using React, Part 3: Add & Display Post

In the previous part of this tutorial series, you saw how to implement the sign-up and sign-in functionality. In this part of the tutorial, you'll implement the user home page and the functionality to add and display the blog posts.

Getting Started

Let's get started by cloning the source code from the first part of the tutorial.

Once the directory has been cloned, navigate to the project directory and install the required dependencies.

Start the Node.js server and you will have the application running at http://localhost:7777/index.html#/.

Creating the User Home Page

Once the user tries to sign in to the application, you need to validate the user credentials and, if valid, create a session. To use sessions in a Node.js app, you need to install express-session using Node Package Manager (npm).

Require the express-session in the app.js file.

To use the session, you need to set a session secret.

Now define a variable called sessions in the global scope.

Assign the sessions variable in the /signin method using the request parameter.

Using the sessions variable, you keep the signed-in username in session.

Create a file called home.html inside the html folder in the application. Here is how it looks:

Create an express route called /home which will render the home page for a valid user.

As seen in the above code, when the user is redirected to the /home route, if sessions and sessions.username exist, the home page is rendered.

Modify the signin method to send a success response on successful user validation.

The above success response is parsed on the React side and, if successful, the user is redirected to the /home express route. In the main.jsx file, inside the Signin component inside the signIn method, modify the code to redirect to the home page.

Save the above changes and restart the Node server. Sign in using a valid username and password, and you will be redirected to the home page.

React Blog App - User Home Page

Modify the above blog post display into a React component. Create a file called home.jsx. Inside the home.jsx file, create a React component called ShowPost which will render the blog post list. Move the static HTML inside the React component render method. Here is how the ShowPost React component looks:

Modify the home.html page to include the required React libraries. Here is the modified home.html page:

As seen in the above HTML code, the container div has been named app, inside which the React components will be displayed.

Save the above changes and restart the node server. Sign in to the blog application and, once on the home page, you will have the ShowPost React component rendered.

Now you need to dynamically populate the values in the post list. Before doing that, let's create a page to add a post. On clicking the above Add hyperlink, you need to display the page to add the blog post. 

Add Post React Component

Let's create an add post React component to add the blog posts. It will consist of a title input box and a subject text area. In the home.jsx, create an AddPost React component to add blog posts. Here is how the AddPost React component looks:

When the user enters the title and the post subject, you need to handle the text change events in the React component. Add the following change event handler to the AddPost React component.

Add the on change event to the AddPost render HTML.

Bind the state variables and the events in the React constructor method.

When the user clicks on the Add Post button, you need to post the title and subject from the React user interface to the Node.js back end to save it in the MongoDB database. Create a method called addPost in the AddPost React component to post the title and subject to the Node.js request handler. Here is how the addPost method in the AddPost React component looks:

As seen in the above code, you have used axios to post the blog post details to the Node.js server. 

Now you need to create a post module which will deal with adding and getting the post details. Create a file called post.js in the project directory. In the post.js file, export an addPost method which will insert post details into the MongoDB database. Require the MongoClient and create the addPost method to insert post details in the MongoDB database. Here is how the post.js file looks:

As seen in the above code, you connected to the MongoDB database using the connector and inserted a record. Once the operation is executed, you checked the error, if any, and returned the status to the callback function.

Inside the app.js file, create a request handler called addPost which will call the addPost method from post.js. Here is how it looks:

Save the above changes and restart the Node.js server. Log in to the application, click on the Add link, and enter the details to add a post. Once done, click on the Add Post button and the details should be saved in the MongoDB database.

Add Post Screen

Display Post React Component

First you need to fetch the saved post details from MongoDB. Inside the post.js file, create a method called GetPost which will fetch post details. Here is how it looks:

The above code fetches details from the MongoDB collection, converts it into a list, and sends it back to the callback function. In the home.jsx file, inside the ShowPost component, fetch the post details in the componentDidMount  method. Here is how it looks:

The above code makes a post request to the Node.js server method /getPost which will call the getPost method in the post.js file. Here is the /getPost method in the app.js file.

Once the post details have been fetched in the axios success callback, keep the details inside a state array variable. Declare a variable called posts inside the ShowPost constructor.

In the success callback of the axios ajax call, set the state variable as shown:

Once you have the post details, you need to dynamically create the required HTML in the React component's render method. Here is how it looks: 

The above code iterates the posts state variable and creates the HTML dynamically. Save the above changes and restart the Node.js server. Sign in to the blog application and create a few blog posts using the Add button on the home page. Once the posts have been added, they will get displayed on the home page.

Display Post Page

Wrapping It Up

In this tutorial, you saw how to create React components for adding and displaying blog posts. In the next part of this tutorial series, you'll learn how to add the functionality to delete and update the blog posts. 

Let me know your thoughts about this tutorial in the comment section below. Source code from this tutorial is available on GitHub.

July 04 2017

16:38

New Course: Easy Mobile Apps With Ionic Creator

Final product image What You'll Be Creating

How would you like to build mobile apps with an easy drag-and-drop interface? In our new short course, Easy Mobile Apps With Ionic Creator, you'll learn exactly how to do that.

What You’ll Learn

In this course, you'll learn how to use Ionic Creator to build cross-platform mobile apps for the popular Ionic framework. First, you'll get a look at all the UI components you can use with Ionic Creator. After that, you'll see how to theme your app with Sass. Finally, you'll get a look at building a complete app user interface that can later be downloaded and customized.

Ionic Creator UI components

This is a simple, 38-minute course that introduces you to a fun and useful new subject. Instructor Reggie Dawson takes you through the whole process in easy-to-follow videos. Watch his introduction below to learn more.

Watch the Introduction

 

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 on Tuts+. 

Plus you now get to make unlimited downloads from the huge Envato Elements library of 200,000+ photos and 26,000+ design assets and templates. So no matter what kinds of projects you work on, you're sure to get good value from the subscription.

If you're looking for a quick and easy alternative, try Ionic Mobile App Creator on Envato Market, a web tool that makes it easy to build for the Ionic framework without coding. 

15:00

Android Things: Creating a Cloud-Connected Doorman

Android Things allows you to make amazing IoT devices with simple code. In this post, I'll show you how to put the pieces together to build a more complex project!

This won't be a complete top-to-bottom tutorial. I'll leave you lots of room to expand and customize your device and app—so you can explore and learn further on your own. My goal is to have fun while working with this new development platform, and show you that there's more to Android Things than just blinking LEDs.

What Are We Building?

Half the fun of an Internet of Things project is coming up with the "thing". For this article, I'll build a cloud-connected doorbell, which will take a picture when someone approaches, upload that image to Firebase, and trigger an action. Our project will require a few components before we can start:

  • Raspberry Pi 3B with Android Things on a SIM card
  • Raspberry Pi camera
  • Motion detector (component: HCSR501)

In addition, you can customize your project to fit your own creative style and have some fun with it. For my project, I took a skeleton decoration that had been sitting on my porch since Halloween and used that as a casing for my project—with the eyes drilled out to hold the camera and motion detector. 

Skeleton Android Things device

I also added a servomotor to move the jaw, which is held closed with a piece of elastic, and a USB speaker to support text-to-speech capabilities. 

Schematics for a simple customized smart doorbell

You can start this project by building your circuit. Be sure to note what pin you use for your motion detector and how you connect any additional peripherals—for example, the connection of the camera module to the camera slot on your Raspberry Pi. With some customization, everyone's end product will be a little different, and you can share your own finished IoT project in the comments section for this article. For information on hooking up a circuit, see my tutorial on creating your first project.

  • Android SDK
    Android Things: Your First Project
    Paul Trebilcox-Ruiz

Detecting Motion

There are two major components that we will use for this project: the camera and the motion detector. We'll start by looking at the motion detector. This will require a new class that handles reading digital signals from our GPIO pin. When motion is detected, a callback will be triggered that we can listen for on our MainActivity. For more information on GPIO, see my article on Android Things peripherals.

If you have been following along with the Android Things series on Envato Tuts+, you may want to try writing the complete motion detector class on your own, as it is a simple digital input component. If you'd rather skip ahead, you can find the entire component written in the project for this tutorial.

In your Activity you can instantiate your HCSR501 component and associate a new HCSR501.OnMotionDetectedEventListener with it.

Once your motion detector is working, it's time to take a picture with the Raspberry Pi camera.

Taking a Picture

One of the best ways to learn a new tool or platform quickly is to go through the sample code provided by the creators. In this case, we will use a class created by Google for taking a picture using the Camera2 API. If you want to learn more about the Camera2 API, you can check out our complete video course here at Envato Tuts+

  • Android SDK
    Take Pictures With Your Android App
    Ashraff Hathibelagal

You can find all of the source code for the camera class in this project's sample, though the main method that you will be interested in is takePicture(). This method will take an image and return it to a callback in your application. 

Once this class has been added to your project, you will need to add the ImageReader.OnImageAvailableListener interface to your Activity, initialize the camera from onCreate(), and listen for any returned results. When your results are returned in onImageAvailable(), you will need to convert them to a byte array for uploading to Firebase.

Uploading a Picture

Now that you have your image data, it's time to upload it to Firebase. While I won't go into detail on setting up Firebase for your app, you can follow along with this tutorial to get up and running. We will be using Firebase Storage to store our images, though once your app is set up for using Firebase, you can do additional tasks such as storing data in the Firebase database for use with a companion app that notifies you when someone is at your door. Let's update the onPictureTaken() method to upload our image.

Once your images are uploaded, you should be able to see them in Firebase Storage.

Images stored in Firebase Storage

Customize

Now that you have what you need to build the base functionality for your doorbell, it's time to really make this project yours. Earlier I mentioned that I did some customizing by using a skeleton with a moving jaw and text-to-speech capabilities. Servos can be implemented by importing the servo library from Google and including the following code in your MainActivity to set up and run the servo.

When you are done with your app, you will also need to dereference the servo motor.

Surprisingly, text to speech is a little more straightforward. You just need to initialize the text-to-speech engine, like so:

You can play with the settings to make the voice fit your application. In the sample above, I have set the voice to have a low, somewhat robotic pitch and an English accent. When you are ready to have your device say something, you can call speak() on the text-to-speech engine.

On a Raspberry Pi, if you are using a servo motor, you will need to ensure that your speaker is connected over a USB port, as the analog aux connection cannot be used while a PWM signal is also being created by your device. 

I highly recommend looking over Google's sample drivers to see what additional hardware you could add to your project, and get creative with your project. Most features that are available for Android are also supported in Android Things, including support for Google Play Services and TensorFlow machine learning. For a little inspiration, here's a video of the completed project:

 

Conclusion

In this article I've introduced a few new tools that you can use for building more complex IoT apps. 

This is the end of our series on Android Things, so I hope you've learned a lot about the platform, and use it to build some amazing projects. Creating apps is one thing, but being able to affect the world around you with your apps is even more exciting. Be creative, create wonderful things, and above all else, have fun! 

Remember that Envato Tuts+ is filled with information on Android development, and you can find lots of inspiration here for your next app or IoT project.

12:00

3 Things That Make Go Different

Go is a special language. It is very refreshing in its approach to programming and the principles it promotes. It helps that some of the language inventors were early C pioneers. The overall feeling of Go is 21st-century C. 

In this tutorial, you'll learn about three of the features that make Go unique: its simplicity, the concurrency model via goroutines, and the error handling mechanism.

1. Simplicity

Many successful modern languages like Scala and Rust are very rich and provide advanced type systems and memory management systems. Those languages took the mainstream languages of their time like C++, Java and C# and added or improved capabilities. Go took a different route and eliminated a lot of features and capabilities. 

No Generics

Generics or templates are a mainstay of many programming languages. They often add complexity, and the error messages associated with generics can sometimes be obscure. Go designers decided to just skip it. 

This is arguably the most controversial design decision of Go. Personally, I find a lot of value in generics and believe that it can be done properly (see C# for a great example of generics done right). Hopefully, generics will be incorporated into Go in the future. 

No Exceptions

Golang's error handling relies on explicit status codes. To separate status from the actual result of a function, Go supports multiple return values from a function. This is pretty unusual. I'll cover it in much more detail later, but here is a quick example:

Single Executable

Go has no separate runtime library. It generates a single executable, which you can deploy just by copying (a.k.a. XCOPY deployment). This is as simple as it gets. No need to worry about dependencies or version mismatches. It is also a great boon for container-based deployments (Docker, Kubernetes and friends). The single standalone executable makes for very simple Dockerfiles.   

No Dynamic Libraries

OK. This just changed recently in Go 1.8. You can now actually load dynamic libraries through the plugin package. But, since this capability wasn't introduced from the get go, I still consider it an extension for special situations. The spirit of Go is still a statically compiled executable. It is also available on Linux only.

2. Goroutines

Goroutines are probably the most attractive aspect of Go from a practical standpoint. Goroutines let you harness the power of multicore machines in a very user-friendly way. It is based on solid theoretical foundations, and the syntax to support it is very pleasant.

CSP

The foundation of Go's concurrency model is C. A. R. Hoare's Communicating Sequential Processes. The idea is to avoid synchronization over shared memory between multiple threads of execution, which is error-prone and labor-intensive. Instead, communicate through channels that avoid contention.

Invoke a Function as a Goroutine

Any function can be invoked as a goroutine by calling it via the go keyword. Consider first the following linear program. The foo() function sleeps for several seconds and prints how many seconds it slept. In this version, each call to foo() blocks before the next call.

The output follows the order of calls in the code:

Now, I'll make a slight change and add the keyword "go" before the first three invocations:

The output is different now. The 1 second call finished first and printed "1s", followed by "2s" and "3s". 

Note that the 4 second call is not a goroutine. This is by design, so the program waits and lets the goroutines finish. Without it, the program will immediately complete after launching the goroutines. There are various ways besides sleeping to wait for a goroutine to finish.

Synchronize Goroutines

Another way to wait for goroutines to finish is to use sync groups. You declare a wait group object and pass it to each goroutine, which is responsible for calling its Done() method when it's done. Then, you wait for the sync group. Here is the code that adapts the previous example to use a wait group.

Channels

Channels let goroutines (and your main program) exchange information. You can create a channel and pass it to a goroutine. The creator can write to the channel, and the goroutine can read from the channel. 

The opposite direction works too. Go also provides sweet syntax for channels with arrows to indicate the flow of information. Here is yet another adaptation of our program, in which the goroutines receive a channel they write to when they are done, and the main program waits to receive messages from all goroutines before terminating.

Write a Goroutine

That's sort of a trick. Writing a goroutine is the same as writing any function. Check out the foo() function above, which is called in the same program as a goroutine as well as a regular function.

3. Error Handling

As I mentioned earlier, the error handling of Go is different. Functions can return multiple values, and by convention functions that can fail return an error object as their last return value. 

There is also a mechanism that resembles exceptions via the panic() and recover() functions, but it is best suited for special situations. Here is a typical error handling scenario where the bar() function returns an error, and the main() function checks if there was an error and prints it.

Mandatory Checking

If you assign the error to a variable and don't check it, Go will get upset.

There are ways around it. You can just not assign the error at all:

Or you can assign it to the underscore:

Language Support

Errors are just values you can pass around freely. Go provides little error support by declaring the error interface that just requires a method named Error() that returns a string:

There is also the errors package that lets you create new error objects. The fmt package provides an Errorf() function to create formatted error objects. That's about it.

Interaction with Goroutines

You can't return errors (or any other object) from a goroutine. Goroutines can communicate errors to the outside world through some other medium. Passing an error channel to a goroutine is considered good practice. Goroutines can also write errors to log files or the database or call remote services.

Conclusion

Go has seen tremendous success and momentum over the last years. It is the go-to (see what I did there) language for modern distributed systems and databases. It got a lot of Python developers converted. 

A big part of it is undoubtedly due to Google's backing. But Go definitely stands on its own merits. Its approach to basic language design is very different from other contemporary programming languages. Give it a try. It's easy to pick up and fun to program in.  

July 03 2017

12:00

20 Best HTML5 Game Templates of 2017

Over the past several years, we have seen HTML5 used to create many great online solutions. We have also seen it used to create some great fun! With the vanishing of Flash, HTML5 quickly became the universal platform to create browser-based games for both desktop and mobile devices.

Whether you have a game concept you would like to flesh out further or would like a fun way to learn more of the ins and outs of HTML5, here are the 20 best HTML5 game templates of 2017 to get you started towards making something awesome:

1. Leaves Boy

You won't be able to leave this game alone as your friends grow jealous of your high scores.

Setting all puns aside, Leaves Boy is a game made for mobile.

Leaves Boy
“Leaves Boy is an addictive one touch game...”

Features include:

  • Facebook and Twitter high score sharer
  • documentation
  • HTML5 files
  • and more

Collect coins, avoid obstacles, and bounce your way to victory.

Use Leaves Boy to skin or use as a foundation to build your own game using Construct 2.

2. Indiara and the Skull Gold

Indiara and the Skull Gold is a mobile platformer with an Indiana Jones feel to it.

Collect the eight gold skulls, but be on the lookout—the caves are full of traps!

Indiara and the Skull Gold
“Meet and play with Indiara, a girl who loves to collect ancient artifacts.”

Features included:

  • supports both desktop and mobile
  • includes layered PSD and AI files
  • 860x480 graphics
  • and more

Easily reskin this HTML5 game template by editing and replacing the images.

Indiara and the Skull Gold includes eight complete levels and can be completely customized by using Construct 2.

3. Dont Crash

Don't crash while you play Dont Crash!

As two cars race around the track, tap the screen to change lanes and avoid a crash.

Dont Crash
“Don’t crash—this is the only rule of the game.”

Features include:

  • supports both mobile and desktop
  • easy, one-touch control
  • 1280x720 graphics
  • and more

Reskin this HTML5 game using the included AI files or completely change the game elements using Construct 2.

Dont Crash is simple, fast, and addictive.

4. Game FlapCat Steampunk

Game FlapCat Steampunk is a cute and simple HTML5 game that's perfectly made for mobile.

How high can you score?

Game FlapCat Steampunk
“Help the cat FlapCat to go through challenges that are super difficult.”

Features include:

  • includes PSD and AI files
  • 1280x720 graphics
  • infinite level
  • and more

Whether you're playing in your web browser or mobile phone, all you need is a single touch or mouse click to play. Easy to play, hard to master.

Game FlapCat Steampunk can easily be re-skinned by replacing the images or fully customized with Construct 2.

5. Panda Love

It's easy to love Panda Love.

With simple design and unique approach, everybody is going to love it—not just pandas.

Panda Love
“Panda Love is an adventure platformer with pixel art.”

Features include:

  • autosave using Webstorage
  • Ludei and ads supported
  • over 20 levels
  • and more

This HTML5 game supports all platforms and includes the Construct 2 file for full customization.

You'll love the look and one-touch control feel of Panda Love.

6. Jumper Frog - HTML5 Game

Frogger is a classic arcade game that makes a great adaptation to mobile.

Take a leap and jump on Jumper Frog - HTML5 Game for some fun.

Jumper Frog - HTML5 Game

“Enjoy this colorful version of the classic game Frogger.”

Features include:

  • includes PSD and AI files for customization
  • fully developed in HTML5 and CreateJS
  • fully customizable
  • and more

This is also compatible with CTL Arcade.

The Jumper Frog - HTML5 Game brings this arcade classic to any screen.

7. Bubble Shooter - HTML5 Games

Launch the colorful bubble into place, and when you get three or more in a row, they disappear. Clear all the bubbles to win!

The Bubble Shooter - HTML5 Games is a classic puzzler that's easy to learn, but hard to master.

Bubble Shooter - HTML5 Games
“The goal of the game is to clear all the bubbles from the level avoiding any bubble crossing the bottom line.”

Features include:

  • includes PSD and AI files for customization
  • fully developed in HTML5 and CreateJS
  • fully customizable
  • and more

If you think this HTML5 game is fun, be sure to also consider the 50 Levels Pack.

Bubble Shooter - HTML5 Games is also compatible with CTL Arcade.

8. HTML5 Tetris

There's hardly anything more addicting and fun than Tetris, and with HTML5 Tetris's unlimited levels, you literally won't be able to stop playing.

HTML5 Tetris
“Works on all HTML5 browsers.”

Features include:

  • easy to personalize
  • touch support
  • seven themes
  • and more

Fully customize the sights and sounds, but most of all, you'll have unlimited fun with HTML5 Tetris.

9. Katana Fruits - HTML5 Game

If you're familiar with Fruit Ninja, you'll be familiar with Katana Fruits - HTML5 Game.

Katana Fruits - HTML5 Game
“The goal is to cut all the fruits that appear on the screen without dropping them and avoid the bombs.”

Features include:

  • includes PSD and AI files for customization
  • fully developed in HTML5 and CreateJS
  • promote with social share buttons
  • fully customizable
  • and more

This HTML5 game is compatible with CTL Arcade for WordPress and can be easily customized.

Sharpen your Katana, it's time to slash some fruit with the Katana Fruits - HTML5 Game.

10. The Sorcerer - HTML5 Puzzle Game

The moment the screen loads, you'll know what to do. Inspired by Zuma, The Sorcerer - HTML5 Puzzle Game is an instant hit.

The Sorcerer - HTML5 Puzzle Game
“The Sorcerer was awarded as the best puzzle game in HTML5 Most Wanted contest”

Features include:

  • fully developed in HTML5 and CreateJS
  • source code included
  • fully customizable
  • and more

Mobile or desktop, the 960x540 resolution is fully optimized.

The Sorcerer - HTML5 Puzzle Game is hard to put down, so you may want to consider acquiring extra levels, too.

11. Rearrange Letters - HTML5 Game

You're given a clue and a jumbled mess of letters. With the clue in mind, rearrange the letters until you've got the word right as the timer counts down.

That's how Rearrange Letters - HTML5 Game works.

Rearrange Letters - HTML5 Game
“Rearrange Letters is an HTML5 game where you can arrange the letters and make the right word with the given description as a clue.”

Features include:

  • customize the text, game mode, and timer
  • social media high score sharer
  • mouse and touch control
  • 1024x768 resolution
  • and more

With plenty of customizations and built using CreateJS, you can reimagine Rearrange Letters - HTML5 Game any way you like.

12. Word Search Game

If you love word searches, search no more. You need this HTML5 game: Word Search Game.

Word Search Game
“Very addictive.”

Features include:

  • manage game options within the included admin interface
  • works on everything from the iPad to IE6
  • unicode support—use any characters
  • and more

Lightweight and easy to install, the Word Search Game is a great find.

13. Coloring Book - HTML5 Game

Simple. Creative. Great for kids.

The Coloring Book - HTML5 Game is a virtual coloring book with full touch support and responsive to any size, on any device.

Coloring Book - HTML5 Game
“This game is a coloring game and can be very interesting for children.”

Features include:

  • smooth coloring
  • print system
  • 24 colors
  • and more

In its third itineration, Coloring Book - HTML5 Game has evolved into a leading coloring book HTML5 game.

14. Canvas Puzzle

Using any image of your choosing, create a drag-and-drop puzzle HTML5 game using Canvas Puzzle.

Canvas Puzzle
“...a fully customizable and easy to implement HTML5 jigsaw puzzle...”

Features include:

  • drag and drop images from your desktop to create puzzles
  • choose any number of pieces
  • disable rotation of pieces
  • and more

Simple, lightweight, and customizable, Canvas Puzzle is an HTML5 game anyone can enjoy.

15. Sliding Puzzle

Another cool image puzzler, Sliding Puzzle works by letting you slide the pieces around until the image is complete.

Sliding Puzzle
“Three game modes!”

Features include:

  • three modes: classic, challenge, and fun
  • full window or fixed canvas size
  • customizable image packs
  • customizable and more

Sliding Puzzle mixes things up nicely with multiple game mode and the ability to add your own images.

16. Sweety Memory - HTML5 Game

Do you remember memory?

Sweety Memory - HTML5 Game works the same way. Flip the cards, make the matches, and win!

Sweety Memory - HTML5 Game
“Match all identical cards before time runs out!”

Features include:

  • fully customizable with included PSD and AI files
  • fully developed in HTML5 and CreateJS
  • source code included
  • and more

Mobile or desktop, the 960x1200 resolution scales to fit the whole screen of almost any device.

Sweety Memory - HTML5 Game is also compatible with CTL Arcade.

17. HTML5 3D BlackJack - HTML5 Casino Game

HTML5 3D BlackJack - HTML5 Casino Game isn't designed to be used with real money—it is simply a fun game to be played.

HTML5 3D BlackJack - HTML5 Casino Game
“Enjoy this blackjack game with hi-res 3D graphics!”

Features include:

  • fully customizable HTML5 and CreateJS files
  • insurance feature, double bet, and split hand
  • PSD and AI files for easy customization
  • and more

This HTML5 game is also compatible with CTL Arcade for WordPress.

Easily monetize with banner ads and promote with social share buttons included with HTML5 3D BlackJack - HTML5 Casino Game.

18. 3D Roulette - HTML5 Casino Game

This is another high-quality casino game built for fun. The 3D Roulette - HTML5 Casino Game includes many great features and is designed really well.

3D Roulette - HTML5 Casino Game
“The game contains all the main roulette game features like Voisins zero, tier, orphelins, neighbor, final bets.”

Features include:

  • fully customizable HTML5 and CreateJS files
  • PSD and AI files for easy customization
  • fully responsive 750x600 resolution
  • and more

This HTML5 game is also compatible with CTL Arcade for WordPress, but if you're looking for a mobile-centric version, I recommend Roulette Royale.

3D Roulette - HTML5 Casino Game is the perfect desktop, in-browser roulette HTML5 game.

19. Missiles Again - HTML5 game (Construct 2 Capx) + Admob

Missiles Again - HTML5 game (Construct 2 Capx) + Admob is a fun time-killer that works on almost every possible platform.

Missiles Again - HTML5 game Construct 2 Capx  Admobvvvvvvvvvvvvvvvvvvvvvvvv
“Control the plane to collect all stars and avoid all missiles!”

Features include:

  • easy code that can be customized with Construct 2
  • PNG and PSD files for easy reskin
  • supports AdMob Ads
  • and more

A fun, well-designed HTML5 game, Missiles Again - HTML5 game (Construct 2 Capx) + Admob is one you don't want to miss.

20. HTML5 Game Bundles

Sometimes it's better to buy in bulk.

If you are considering multiple HTML5 games, you may want to look through these HTML5 Game Bundles to see if you can pay less and receive more.

HTML5 Game Bundles

A few titles from various bundles include:

  • Fruit Slasher
  • Brick Out
  • Ninja Run
  • Tank Defender
  • Billiards
  • Cars
  • Monster Match-3
  • Bubble Shooter
  • Space Purge
  • Duck Shooter
  • Girl Dress Up
  • and more!

Some of the best HTML5 Game Bundles to consider include Super Bundle No 1 (50 games), 24-Games in 1 Bundle, and HTML5 Games Bundle No. 2 (9 games).

Conclusion

Going through this list may inspire you to reskin, tweak, or build something completely new—using one of these HTML5 games as a template towards success. Whether you publish a game arcade on your website, earn revenue with advertising, or would like to dig deeper in HTML5 using game templates, you're sure to find something you're looking for from the Envato Market.

You can also find useful Envato Tuts+ code tutorials on game design or game mechanics, as well as HTML5 tutorials to get you started.

Gaming and coding. Two things that are incredibly fun to do.

12:00

Code a Real-Time NativeScript App: SQLite

NativeScript is a framework for building cross-platform native mobile apps using XML, CSS, and JavaScript. In this series, we're trying out some of the cool things you can do with a NativeScript app: geolocation and Google Maps integration, SQLite database, Firebase integration, and push notifications. Along the way, we're building a fitness app with real-time capabilities that will use each of these features.

In this tutorial, you'll learn how to integrate a SQLite database into the app to store data locally. Specifically, we'll be storing the walking sessions data that we gathered in the previous tutorial.

What You'll Be Creating

Picking up from the previous tutorial, you'll be adding a tab view for displaying the different portions of the app. Previously our app just had the Tracking page, so we didn't need tabs. In this post, we'll be adding the Walks page. This page will display the user's walking sessions. A new data point will be added here every time the user tracks their walking session. There will also be a function for clearing the data.

Here's what the final output will look like:

SQL Lite Final Output

Setting Up the Project

If you have followed the previous tutorial on geolocation, you can simply use the same project and build the features that we will be adding in this tutorial. Otherwise, you can create a new project and copy the starter files into your project's app folder.

After that, you also need to install the geolocation and Google Maps plugins:

Once installed, you need to configure the Google Maps plugin. You can read the complete instructions on how to do this by reading the section on Installing the Google Maps Plugin in the previous tutorial.

Once all of those are done, you should be ready to follow along with this tutorial.

Running the Project

You can run the project by executing tns run android. But since this app will build on the geolocation functionality, I recommend you use a GPS emulator for quickly setting and changing your location. You can read about how to do so in the section on Running the App in the previous tutorial

Installing the SQLite Plugin

The first thing that you need to do to start working with SQLite is to install the plugin:

This allows you to do things like connecting to a database and doing CRUD (create, read, update, delete) operations on it.

Connecting to the Database

Open the main-page.js file and import the SQLite plugin:

You can now connect to the database:

The walks.db file was created from the terminal using the touch command, so it's just an empty file. Copy it into the app folder.

If it successfully connected, the promise's resolve function will be executed. Inside that, we run the SQL statement for creating the walks table. To keep things simple, all we need to save is the total distance covered (in meters) and the total steps, as well as the start and end timestamps. 

Once the query executes successfully, we pass the database instance (db) into the page context. This will allow us to use it from the main-view-model.js file later on.

Fetching Data

Now we're ready to work with the data. But since we'll be working with dates, we first need to install a library called fecha. This allows us to easily parse and format dates:

Once it's installed, open the main-view-model.js file and include the library:

Next is the code for checking if geolocation is enabled. First, create a variable (walk_id) for storing the ID of a walking record. We need this because the app will immediately insert a new walk record into the walks table when the user starts location tracking. walk_id will store the ID that's auto-generated by SQLite so that we'll be able to update the record once the user stops tracking.

Next, get the current month and year. We'll use it to query the table so it only returns records that are in the same month and year. This allows us to limit the number of records that appear in the UI.

We also need a variable for storing the start timestamp. We'll use it later on to update the UI. This is because we're only querying the table once when the app is loaded, so we need to manually update the UI of any new data which becomes available. And since the starting timestamp will only have a value when the user starts tracking, we need to initialize it outside the scope so we can update or access its value later on.

Initialize the walks data that will be displayed in the UI:

Get the data from the walks table using the all() method. Here, we're supplying the month and the year as query parameters. The strftime() function is used to extract the month and year part of the start_datetime

Once a success response is returned, we loop through the result set so that we can format the data correctly. Note that the indexes in which we access the individual values depend on the table structure that was described earlier in the main-page.js file. The first column is ID, the second is the total distance, and so on.

The formatted data is then pushed to the walks array and is used to update the UI. has_walks is used as a toggle for the UI so that we can show or hide things based on its value.

This will supply the data for the ListView in the main-page.xml file:

Saving Data

Once the user starts tracking, set the current datetime as the start_datetime and insert initial values into the table using the execSQL() function. Just like the all() function, this expects the SQL query as the first argument and an array of parameters as the second.

If the query is successful, it should return the auto-generated ID for the inserted record. We then assign it as the value for the walk_id so it can be used later on to update this specific record.

Once the user stops tracking, we again get the current timestamp and format it accordingly for storage:

Since we've ordered the results from most to least recent, we use unshift() (instead of push()) to add the new item to the top of the walks array.

After that, we once again we use the execSQL() function to update the record that we inserted earlier:

Be sure to move the code for resetting the tracking UI (to reset the total distance and steps) inside the promise's resolve function so you can easily test whether the update query executed successfully or not. 

Clearing Data

Deleting data is done by clicking on the Clear Data button below the list of walk data:

In the main-view-model.js file, add the code for deleting all the data from the walks table. If you're used to MySQL, you might be wondering why we're using the DELETE query instead of TRUNCATE for emptying the table. Well, that's because SQLite doesn't have the TRUNCATE function. That's why we have to use the DELETE query without supplying a condition so that it will delete all the records that are currently in the table. 

Conclusion

In this tutorial, you've learned how to locally store data in your NativeScript apps using the SQLite plugin. As you have seen, SQLite allows you to reuse your existing SQL skills in managing a local database. It's important to note that not all functions that you're used to in MySQL are supported in SQLite. So it's always wise to consult the documentation if you're not sure whether a certain function is supported or not. 

If you want to learn about other options for storing data in NativeScript apps, I recommend you read this article on Going Offline With NativeScript.

In the final post of this series, we'll add push notifications to our app.

In the meantime, check out some of our other posts on NativeScript and cross-platform mobile coding.

  • Mobile App
    Create a Weather App With TypeScript and NativeScript
    Wernher-Bel Ancheta
  • Mobile Development
    Introducing Vue and Weex for Native Mobile Apps
    Lawrence Turton
  • Ionic
    Get Started With Ionic Services: Auth
    Wernher-Bel Ancheta

For a comprehensive introduction to NativeScript, try our video course Code a Mobile App With NativeScript. In this course, Keyvan Kasaei will show you step by step how to build a simple application. Along the way, you'll learn how to implement a simple app workflow with network requests, an MVVM architecture, and some of the most important NativeScript UI components. By the end, you'll understand why you should consider NativeScript for your next mobile app project.

 
Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl