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

Introduction to API Calls With React and Axios

$
0
0

This tutorial will teach you how to use Axios to fetch data and then how to manipulate it and eventually display it on your page with filtering functionality. You will learn how to use the map, filter and includes methods along the way. On top of that, you will be creating a Higher-Order Component (HOC) to handle the loading state of the fetched data from the API endpoint.

Let's start with a clean React app. I assume you use create-react-app, and the filenames will be in accordance with its outputs.

We only need to install the Axios module for this tutorial.

Go to your project directory through the terminal window and then type in npm install axios -save in order to install Axios for your project locally.

Fetching the Data

We will be using the Random User Generator API to fetch random user information to use in our application.

Let's add the Axios module to our application by importing it into our App.js file.

The Random User Generator API offers a bunch of options for creating various types of data. You can check the documentation for further information, but for this tutorial, we will keep it simple.

We want to fetch ten different users, and we only need the name, surname, and a unique ID, which is required for React when creating lists of elements. Also, to make the call a bit more specific, let's include the nationality option as an example.

Below is the API that we will make a call for.

Note that I didn't use the id option provided in the API due to the fact that it sometimes returns null for some users. So, just to make sure that there will be a unique value for each user, I included the registered option in the API.

https://randomuser.me/api/?results=10&inc=name,registered&nat=fr

You can copy and paste it into your browser and you will see the returned data in JSON format.

Now, the next thing is to make an API call through Axios.

First of all, let's create a state so that we can store the fetched data.

Inside our App component, add a class constructor and then create the state.

Here you see users and store states. One will be used for filtering purposes and will not be edited, and the other one will hold the filter results that will be shown in the DOM.

Now go ahead and create the componentDidMount() lifecycle hook.

Inside this lifecycle hook, we will fetch the data, and then by using the map method, we will create new intermediate data that we will use inside the setState method.

If you check the result of the API call in your browser, you will see that there are first and last key-value pairs inside the name object but no key-value pair for a full name. So we will be combining first and last to create a full name inside a new JavaScript Object. Note that JSON and JavaScript Object are different things, although they basically work the same way.

Let's move step by step.

Add the following code to your App component.

When you check the console, you will see an object output. If you open up this object, there is another object inside it named data, and inside data, there is an array named results.

Let's further change the console.log(json).

Here we reached the name of the first value inside the results array.

Now let's use the built-in map method of JavaScript in order to iterate through each element inside the array and create a new array of JavaScript Objects with a new structure.

Here, we called the map method on json.data.results, which is an array, and then referred each element of the array as result (notice the singular/plural difference). Then, by using the key-value pair of each object inside the array, we created another object with name and id key-value pairs.

At the end, we used another then method in order to be able to refer to our new data. We referred it as newData, and then we just logged to the console to see if everything went as planned.

You should see a new array with objects having name and id pairs.

Storing the Data

Instead of logging the result to the console, we have to store it. In order to do that, we will use setState.

Here, we initially set both users and store data with our new newData array.

We need two variables due to the fact that we need to store the original data and should never lose it. By using the information inside the store state, we can filter the data and then populate the users state and show it on the page. This will be clearer when we implement the filtering functionality.

Last but not least, we added catch to actually catch any possible errors during fetching and display the error as an alert message.

Filtering Functionality

The idea of filtering is quite simple. We have our store state, and it always keeps the original data without changing. Then, by using the filter function on this state, we only get the matching elements and then assign them to the users state.

The filter method requires a function as an argument, a function to be run for each element in the array. Here we refer each element inside the array as item. Then we take the name key of each item and convert it to lower case in order to make our filtering functionality case insensitive. 

After we have the name key for the item, we check if this one includes the search string we typed in. includes is another built-in JavaScript method. We pass the search string typed in the input field as an argument to includes, and it returns if this string is included in the variable it was called on. Again, we convert the input string to lower case so that it does not matter whether you type upper or lower case inputs. 

In the end, the filter method returns the matching elements. So we simply take these elements and store them inside the users state through setState.

Below you can find the final version of the function we created.

Creating the Components

Although for this small example we could put everything inside the App component, let's take advantage of React and make some small functional/stateless components.

Let's add the following structure to the render method of the App component.

For the time being, we will be just focusing on the functionality. Later, I will provide the CSS file I have created.

Notice that we have the searchFunc prop for the SearchBar component and the usernames prop for the List component.

Note that we use the users state instead of the store state to show the data because the users state is the one containing the filtered results.

The SearchBar Component

This component is quite straightforward. It only takes the filterNames function as a prop and calls this function when the input field changes.

The List Component

This one will simply list the names of the users.

Here, we again used the map method to get each item in the array and create a <li> item out of it. Note that when you use map to create a list of items, you need to use a key in order for React to keep track of each list item.

Notice that we wrapped List with another component named LoadingHOC before exporting it. This is how Higher-Order Components (HOCs) work. 

What we did here is to pass our component as an argument to another component before exporting it. So this LoadingHOC component will be enhancing our component with new features.

The LoadingHOC Component

As I briefly explained before, a HOC takes a component as an input and then exports an enhanced version of the input component.

Inside the HOC, we can directly access the props of the input component. So we just check whether the length of the usernames prop is 0 or not. If it is 0, this means that the data has yet to be fetched because it is an empty array by default. So we just show a spinner GIF that we imported. Otherwise, we just show the input component itself.

It's imported in order not to forget to pass any props and states back to the input component with a spread operator. Otherwise, your component would be deprived of them.

CSS File

Below you can find the CSS file specific to this example.

Conclusion

Throughout this tutorial, we took a quick look at the Random User Generator API as a source of random data. Then we fetched the data from an API endpoint and restructured the results inside a new JavaScript Object with the map method.

The next thing was to create a filtering function with the filter and includes methods. Finally, we created two different components and enhanced one of them with a Higher-Order Component (HOC) by introducing a loading indicator when the data is not there yet.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in Envato Market that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.


Getting Started With Redux: Learn by Example

$
0
0

Redux helps you manage state by setting the state up at a global level. In the previous tutorial, we had a good look at the Redux architecture and the integral components of Redux such as actions, action creators, the store, and reducers. 

In this second post of the series, we are going to bolster our understanding of Redux and build on top of what we already know. We will start by creating a realistic Redux application—a contact list—that's more complex than a basic counter. This will help you strengthen your understanding of the single store and multiple reducers concept which I introduced in the previous tutorial. Then later we'll talk about binding your Redux state with a React application and the best practices that you should consider while creating a project from scratch. 

However, it's okay if you haven't read the first post—you should still be able to follow along as long as you know the Redux basics. The code for the tutorial is available in the repo, and you can use that as a starting point. 

Creating a Contact List Using Redux

We're going to build a basic contact list with the following features:

  • display all contacts
  • search for contacts
  • fetch all contacts from the server
  • add a new contact
  • push the new contact data into the server

Here's what our application is going to look like:

Getting Started With Redux  Final View of the Contact List
Final product — Contact list View


Getting Started With Redux  Final View of the Contact Form
Final Product — Add contact view

Covering everything in one stretch is hard. So in this post we're going to focus on just the Redux part of adding a new contact and displaying the newly added contact. From a Redux perspective, we'll be initializing the state, creating the store, adding reducers and actions, etc. 

In the next tutorial, we'll learn how to connect React and Redux and dispatch Redux actions from a React front-end. In the final part, we'll shift our focus towards making API calls using Redux. This includes fetching the contacts from the server and making a server request while adding new contacts. Apart from that, we'll also create a search bar feature that lets you search all the existing contacts. 

Create a Sketch of the State Tree

You can download the react-redux demo application from my GitHub repository. Clone the repo and use the v1 branch as a starting point. The v1 branch is very similar to the create-react-app template. The only difference is that I've added a few empty directories to organise Redux. Here's the directory structure.

Alternatively, you can create a new project from scratch. Either way, you will need to have installed a basic react boilerplate and redux before you can get started. 

It's a good idea to have a rough sketch of the state tree first. In my opinion, this will save you lots of time in the long run. Here's a rough sketch of the possible state tree. 

Our store needs to have two properties—contacts and ui. The contacts property takes care of all contacts-related state, whereas the ui handles UI-specific state. There is no hard rule in Redux that prevents you from placing the ui object as a sub-state of contacts. Feel free to organize your state in a way that feels meaningful to your application. 

The contacts property has two properties nested inside it—contactlist and newContact. The contactlist is an array of contacts, whereas newContact temporarily stores contact details while the contact form is being filled. I am going to use this as a starting point for building our awesome contact list app. 

How to Organize Redux

Redux doesn't have an opinion about how you structure your application. There are a few popular patterns out there, and in this tutorial, I will briefly talk about some of them. But you should pick one pattern and stick with it until you fully understand how all the pieces are connected together.

The most common pattern that you'll find is the Rails-style file and folder structure. You'll have several top-level directories like the ones below:

  • components: A place to store the dumb React components. These components do not care whether you're using Redux or not.
  • containers: A directory for the smart React components that dispatch actions to the Redux store. The binding between redux and react will be taking place here. 
  • actions: The action creators will go inside this directory. 
  • reducers: Each reducer gets an individual file, and you'll be placing all the reducer logic in this directory.
  • store: The logic for initializing the state and configuring the store will go here. 

The image below demonstrates how our application might look if we follow this pattern:

Organising Folder structure in Redux

The Rails style should work for small and mid-sized applications. However, when your app grows, you can consider moving towards the domain-style approach or other popular alternatives that are closely related to domain-style. Here, each feature will have a directory of its own, and everything related to that feature (domain) will be inside it. The image below compares the two approaches, Rails-style on the left and domain-style on the right. 

Comparison of two popular techniques for organising Redux and React

For now, go ahead and create directories for components, containers, store, reducers, and action. Let's start with the store. 

Single Store, Multiple Reducers

Let's create a prototype for the store and the reducer first. From our previous example, this is how our store would look: 

The switch statement has three cases that correspond to three actions that we will be creating. Here is a brief explanation of what the actions are meant for. 

  • HANDLE_INPUT_CHANGE: This action gets triggered when the user inputs new values into the contact form.
  • ADD_NEW_CONTACT: This action gets dispatched when the user submits the form.
  • TOGGLE_CONTACT_FORM: This is a UI action that takes care of showing/hiding the contact form. 

Although this naive approach works, as the application grows, using this technique will have a few shortcomings.

  1. We're using a single reducer. Although a single reducer sounds okay for now, imagine having all your business logic under one very large reducer.  
  2. The code above doesn't follow the Redux structure that we've discussed in the previous section.

To fix the single reducer issue, Redux has a method called combineReducers that lets you create multiple reducers and then combine them into a single reducing function. The combineReducers function enhances readability. So I am going to split the reducer into two—a contactsReducer and a uiReducer

In the example above, createStore accepts an optional second argument which is the initial state. However, if we are going to split the reducers, we can move the whole initialState to a new file location, say reducers/initialState.js. We will then import a subset of initialState into each reducer file. 

Splitting the Reducer 

Let's restructure our code to fix both the issues. First, create a new file called store/createStore.js and add the following code:

Next, create a root reducer in reducers/index.js as follows:

Finally, we need to create the code for the contactsReducer and uiReducer.

reducers/contactsReducer.js

reducers/uiReducer.js

When you're creating reducers, always keep the following in mind: a reducer needs to have a default value for its state, and it always needs to return something. If the reducer fails to follow this specification, you will get errors.

Since we've covered a lot of code, let's have a look at the changes that we've made with our approach:

  1. The combineReducers call has been introduced to tie together the split reducers.
  2. The state of the ui object will be handled by uiReducer and the state of the contacts by the contactsReducer
  3. To keep the reducers pure, spread operators have been used. The three dot syntax is part of the spread operator. If you're not comfortable with the spread syntax, you should consider using a library like Immutability.js.
  4. The initial value is no longer specified as an optional argument to createStore. Instead, we've created a separate file for it called initialState.js. We're importing initialState and then setting the default state by doing state = initialState.ui

State Initialization

Here's the code for the reducers/initialState.js file.

Actions and Action Creators

Let's add a couple of actions and action creators for adding handling form changes, adding a new contact, and toggling the UI state. If you recall, action creators are just functions that return an action. Add the following code in actions/index.js.

Each action needs to return a type property. The type is like a key that determines which reducer gets invoked and how the state gets updated in response to that action. The payload is optional, and you can actually call it anything you want. 

In our case, we've created three actions.

The TOGGLE_CONTACT_FORM doesn't need a payload because every time the action is triggered, the value of ui.isContactFormHidden gets toggled. Boolean-valued actions do not require a payload. 

The HANDLE_INPUT_CHANGE action is triggered when the form value changes. So, for instance, imagine that the user is filling the email field. The action then receives "email" and "bob@example.com" as inputs, and the payload handed over to the reducer is an object that looks like this:

The reducer uses this information to update the relevant properties of the newContact state. 

Dispatching Actions and Subscribing to the Store

The next logical step is to dispatch the actions. Once the actions are dispatched, the state changes in response to that. To dispatch actions and to get the updated state tree, Redux offers certain store actions. They are:

  • dispatch(action): Dispatches an action that could potentially trigger a state change. 
  • getState(): Returns the current state tree of your application.
  • subscriber(listener): A change listener that gets called every time an action is dispatched and some part of the state tree is changed. 

Head to the index.js file and import the configureStore function and the three actions that we created earlier:

Next, create a store object and add a listener that logs the state tree every time an action is dispatched:

Finally, dispatch some actions:

If everything is working right, you should see this in the developer console.

Redux store being logged in developer console

That's it! In the developer console, you can see the Redux store being logged, so you can see how it changes after each action.

Summary

We've created a bare-bones Redux application for our awesome contact list application. We learned about reducers, splitting reducers to make our app structure cleaner, and writing actions for mutating the store. 

Towards the end of the post, we subscribed to the store using the store.subscribe() method. Technically, this isn't the best way to get things done if you're going to use React with Redux. There are more optimized ways to connect the react front-end with Redux. We'll cover those in the next tutorial.  

New Course: Connect a Database to Your Python Application

$
0
0

Python is a great way to create web apps, but what happens when you need to add a database? You'll find out exactly how to handle that in our new short course, Connect a Database to Your Python Application.

What You’ll Learn

In this short course, Derek Jensen will show you how easy it is to integrate a simple database into an existing Python application. 

Database in a Python app

In this course, you'll be using SQLite, but you'll learn how to implement your database in a way that makes it easy to change or upgrade later. You'll learn how to use the Repository pattern to make your app more maintainable, testable, and flexible.

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

Boost Your Website Performance With PhpFastCache

$
0
0

In this article, we're going to explore the PhpFastCache library, which allows you to implement caching in your PHP applications. Thus, it helps to improve overall website performance and latency on page load times.

What Is PhpFastCache?

PhpFastCache is a library that makes implementation of caching in your PHP applications a breeze and a fun experience. It's an easy-to-use and yet powerful library that provides several APIs that allow you to implement caching strategy of your choice without much hassle.

Make no mistake by assuming that it's merely a traditional file system caching scheme. In fact, PhpFastCache supports plethora of adapters that let you choose from high-performance back-ends like Memcache, Redis, Mongodb, Couchdb and others.

Let's have a quick look at couple of the most popular adapters:

  • file system
  • Memcache, Redis and APC
  • Couchdb and Mongodb
  • Zend Disk Cache and Zend Memory Cache

If you don't find your choice of adapter in the above list, you could easily develop a custom driver that plugs into the system and works effortlessly.

In addition to basic functionalities, the PhpFastCache library also provides the event mechanism that allows you to respond to certain predefined events. For example, when something is deleted from the cache, you could catch this event and refresh or delete related data as well.

In the upcoming sections, we'll go through the installation and configuration of PhpFastCache, along with the demonstration of a few examples.

Installation and Configuration

In this section, we'll go through installation and configuration of the PhpFastCache library. There are different ways you could approach this in your project.

If you just want to download the .zip or .tar.gz version of the library without much hassle, you could go ahead and grab it from the official site.

On the other hand, you could install it as a Composer package as well. That should be the preferred way as it makes maintenance and upgrading easier in the future. If you haven't installed Composer yet, you'll have to do that first.

Once you've installed the composer, let's go ahead and grab the PhpFastCache library using the following command.

Upon the successful completion of that command, you should have the vendor directory in place containing everything you need to run the PhpFastCache library. On the other hand, if you're missing any libraries or extensions required by the PhpFastCache library, Composer would ask you to install them first.

You should also find the composer.json file that looks like following.

No matter the way you've chosen to install the PhpFastCache library, the only thing that's necessary is to include the autoload.php file in your application to kick off things.

If you're using the composer based workflow, the autoload.php is located under the vendor directory.

On the other hand, if you've downloaded the .zip or .tar.gz package, the autoload.php should be available at src/autoload.php.

And with that, you're all set to start caching and gain the benefits of the amazing PhpFastCache library. In the next section, we'll go through couple of practical examples that demonstrate how you're supposed to use PhpFastCache in your application.

Demonstration

We've already discussed that the PhpFastCache library supports various adapters when it comes to caching. In this section, we'll demonstrate using the filesystem and Redis adapters.

Caching Using the Files Adapter

Go ahead and create the file_cache_example.php file with the following contents. I assume that you're using the composer workflow and thus the vendor directory is at the same level as that of file_cache_example.php. If you've installed PhpFastCache manually, you can change the file structure accordingly.

Let's go through this to understand what each piece of code stands for. The first obvious thing is to include the autoload.php file and import the namespace that we intend to use.

When you're using the files cache, you're supposed to provide the directory path that holds files generated by the caching system. And that's what exactly we've configured in the following snippet.

Of course, we need to make sure the cache directory exists and it's writable by the web server.

Next, we instantiate the cache object and try to load the cached item by the welcome_message key.

If the item doesn't exist in the cache, we'll add it to the cache for 60 seconds and display it from the cache. On the other hand, if it exists in the cache, we'll just fetch it!

That was fairly easy setup, wasn't it? In fact, you can go ahead and run the file to check results!

When you run it for the first time, you should see the following output:

In the next run, the output looks something like this:

So, that was files system caching at your disposal. In the next section, we'll mimic the same example using the Redis cache adapter.

Caching Using the Redis Adapter

Before we move ahead, I assume that you've already installed the Redis server and it's running at 6379 port, which is the default port for Redis.

With that setup, let's go ahead and create the redis_cache_example.php file with the following contents.

As you can see that, the file is pretty much the same except the section that initializes configuration specific to Redis adapter.

Of course, you would like to change host and port settings to match your requirements if you're running the Redis server other than localhost.

Go ahead and run the redis_cache_example.php file to see how it works. You could also confirm it by checking the output in the Redis CLI.

So, that's all you need to use the Redis adapter. I would encourage you to try different adapters and their options!

Conclusion

Today, we went through one of the most popular caching libraries for PHP—PhpFastCache. In the first half of the article, we discussed the basics along with installation and configuration. Later in the article, we took the opportunity to introduce couple of examples to demonstrate concepts that we discussed.

I hope you've enjoyed the article and that you will be motivated to integrate the PhpFastCache library in your upcoming projects. Feel free to post any questions and comments below!

Getting Started with Redux: Connecting Redux with React

$
0
0

This is the third part of the series on Getting Started with Redux and in this tutorial, we're going to learn how to connect a Redux store with React.  Redux is an independent library that works with all the popular front-end libraries & frameworks. And it works flawlessly with React because of its functional approach.

You don't need to have followed the previous parts of this series for this tutorial to make sense. If you're here to learn about using React with Redux, you can take the Quick Recap below and then check out the code from the previous part and start from there. 

Quick Recap

In the first post, we learned about the Redux workflow and answered the question, Why Redux?. We created a very basic demo application and showed you how the various components of Redux—actions, reducers, and the store— are connected.

In the previous post, we started building a contact list application that lets you add contacts and then displays them as a list. A Redux store was created for our contact list and we added a few reducers and actions. We attempted to dispatch actions and retrieve the new state using store methods like store.dispatch() and store.getState().

By the end of this article, you'll learn

  1. the difference between container components and presentational components
  2. about the react-redux library
  3. how to bind react and redux using connect()
  4. how to dispatch actions using mapDispatchToProps
  5. how to retrieve state using mapStateToProps

The code for the tutorial is available on GitHub at the react-redux-demo repo. Grab the code from the v2 branch and use that as a starting point for this tutorial. If you're curious to know how the application looks by the end of this tutorial, try the v3 branch. Let's get started.

Designing a Component Hierarchy: Smart vs. Dumb Component

This is a concept that you've probably heard of before. But let's have a quick look at the difference between smart and dumb components. Recall that we had created two separate directories for components, one named containers/, and the other components/. The benefit of this approach is that the behavior logic is separated from the view.

The presentational components are said to be dumb because they are concerned about how things look. They are decoupled from the business logic of the application and receive data and callbacks from a parent component exclusively via props. They don't care if your application is connected to a Redux store if the data is coming from the local state of the parent component. 

The container components, on the other hand, deal with the behavioral part and should contain very limited DOM markup and style. They pass the data that needs to be rendered to the dumb components as props. 

I've covered the topic in-depth in another tutorial, Stateful vs. Stateless Components in React.

Moving on, let's see how we're going to organize our components.

Designing component Hierarchy

Presentational Components

Here are the presentational components that we'll be using in this tutorial. 

components/AddContactForm.jsx

This is an HTML form for adding a new contact. The component receives onInputChange and onFormSubmit callback as props. The onInputChange event is triggered when the input value changes and onFormSubmit when the form is being submitted.

components/ContactList.jsx

This component receives an array of contact objects as props and hence the name ContactList. We use the Array.map() method to extract individual contact details and then pass on that data to <ContactCard />.

components/ContactCard.jsx

This component receives a contact object and displays the contact's name and image. For practical applications, it might make sense to host JavaScript images in the cloud.

Container Components

We're also going to construct barebones container components.

containers/Contacts.jsx

The returnContactList() function retrieves the array of contact objects and passes it to the ContactList component. Since returnContactList() retrieves the data from the store, we'll leave that logic blank for the moment.

containers/AddContacts.jsx

We've created three barebones handler method that corresponds to the three actions. They all dispatch actions to update the state. In the render method, we've left out the logic for showing/hiding the form because we need to fetch the state. 

Now let's see how to bind react and redux together

The react-redux Library

React bindings are not available in Redux by default. You will need to install an extra library called react-redux first. 

The library exports just two APIs that you need to remember, a <Provider /> component and a higher-order function known as connect()

The Provider Component

Libraries like Redux need to make the store data accessible to the whole React component tree starting from the root component. The Provider pattern allows the library to pass the data from top to the bottom. The code below demonstrates how Provider magically adds the state to all the components in the component tree. 

Demo Code

The entire app needs to have access to the store. So, we wrap the provider around the app component and then add the data that we need to the tree's context. The descendants of the component then have access to the data. 

The connect() Method 

Now that we've provided the store to our application, we need to connect the React to the store. The only way that you can communicate with the store is by dispatching actions and by retrieving the state. We've previously used store.dispatch() to dispatch actions and store.getState() to retrieve the latest snapshot of the state. The connect()lets you do exactly this, but with the help of two methods known as mapDispatchToProps and mapStateToProps. I have demonstrated this concept in the example below:

Demo Code

mapStateToProps and mapDispatchToProps both return an object and the key of this object becomes a prop of the connected component. For instance, state.contacts.newContact is mapped to props.newContact. The action creator addContact() is mapped to props.addContact.  

But for this to work, you need the last line in the code snippet above. 

Instead of exporting the AddContact component directly, we're exporting a connected component. The connect provides addContact and newContact as props to the <AddContact/> component. 

How to Connect React and Redux?

Next, we're going to cover the steps that you need to follow to connect React and Redux.

Install the react-redux Library

Install the react-redux library if you haven't already. You can use NPM or Yarn to install it. 

Provide the Store to your App Component

Create the store first. Then, make the store object accessible to your component tree by passing it as a prop to <Provider />.

index.js

Connect React Containers to Redux

The connect function is used to bind React container to Redux. What that means is that you can use the connect feature to:

  1. subscribe to the store and map its state to your props
  2. dispatch actions and map the dispatch callbacks into your props

Once you've connected your application to Redux, you can use this.props to access the current state and also to dispatch actions. I am going to demonstrate the process on theAddContact component. AddContact needs to dispatch three actions and get the state of two properties from the store. Let's have a look at the code.

First, import connect into AddContact.jsx.

Second, create two methods mapStateToProps and mapDispatchToProps.

mapStateToProps receives the state of the store as an argument. It returns an object that describes how the state of the store is mapped into your props. mapDispatchToProps returns a similar object that describes how the dispatch actions are mapped to your props. 

Finally, we use connect to bind the AddContact component to the two functions as follows:

Update the Container Components to Use the Props

The component's props are now equipped to read state from the store and dispatch actions. The logic for handeInputChange, handleSubmit and showAddContactBox should be updated as follows:

We've defined the handler methods. But there is still one part missing—the conditional statement inside the render function.

If isHidden is false, the form is rendered. Otherwise,a button gets rendered. 

Displaying The Contacts

We've completed the most challenging part. Now, all that's left is to display these contacts as a list. The Contacts container is the best place for that logic. 

We've gone through the same procedure that we followed above to connect the Contacts component with the Redux store. The mapStateToProps function maps the store object to the contactList props. We then use connect to bind the props value to the Contact component. The second argument to the connect is null because we don't have any actions to be dispatched. That completes the integration of our app with the state of the Redux store. 

What Next?

In the next post, we'll take a deeper look at middlewares and start dispatching actions that involve fetching data from the server. Share your thoughts in the comments!

10 Best React Native App Templates of 2018

$
0
0

React Native has been gaining in popularity for one obvious reason: it allows developers to write code across different mobile operating systems. This means that you no longer have to build the same app for iOS and for Android from scratch or specialise in one or the other operating system. Now you can code apps for both platforms with the same powerful JavaScript technologies you use for building web apps.

Pioneered by Facebook and released as open source, React Native is being used by apps such as Facebook, Instagram, Netflix, Airbnb, etc., and can only go from strength to strength.

To help keep you updated about the best React Native app templates on the market, we've compiled a list of the 10 best available at CodeCanyon for 2018.

1. MStore Pro

One of the most popular React Native app templates available at CodeCanyon, MStore Pro allows users to convert their existing online shop to a mobile store app.

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.

User Abhibavishi says:

"Awesome product, great support! Love the quality of the code, along with the final output. I wish I could give more than 5 stars!”

2. App Platform

App Platform only came on the market in January but is already one of the best-selling app templates at CodeCanyon for the year. That’s probably because it’s a bundle of multiple apps that follow the same design and coding pattern, and it enables developers to create any number of apps including recipe, restaurant, events and/or shopping apps.  

App Platform

In addition as part of this bundle, developers also get the Firebase Admin Panel to be used as the admin for all the apps, from which you can manage the app content, layout and design, send push notifications, and manage orders. 

3. BeoNews

Currently one of the top-selling and best-rated templates in this category, BeoNews allows users to convert any of the content on their WordPress site, including video, photos, and blog, into a mobile app. BeoNews stores user data on Firebase and synchronises across devices.

BeoNews

User bull-tech says: 

“Excellent support! Code is very good and clear. Best WordPress to React Native project on the market.”

4. Tudu

With our demanding jobs and busy family lives, it is no wonder that productivity apps are among the most popular of mobile apps.

Tudu

The cleverly named Tudu React Native app template aims to help developers create a simple, streamlined productivity app that will appeal to a wide cross-section of users. The app features a splash screen, offline storage, swipe actions to complete or remove items, insights charts, and more.

5. gikApp

If you need to convert WordPress or Shopify sites into professional and fully functioning mobile apps quickly and easily, the gikApp React Native mobile app template is ideal. 

gikApp

The developers provide step-by-step video instructions, and if you’re not sure the app is right for you, you can take advantage of the free trial on offer and take it for a test run before you buy.

Template user phowr says: 

“I decided to use gikApp to build a mobile for my spa business. Work like a charm. Very smooth, no lag.”

6. Antiqueruby

Antiqueruby is every app developer's dream. That’s because the app template, which is another newcomer to the market, is designed to save developers hours of work by providing them with stylish and clever UI and UX components to customise their apps. 

Antiqueruby

Created using Material Design and offering over 140 screens for profiles, sign-ins and sign-ups, social media, navigation, etc., it’s no wonder that Antiqueruby has become one of CodeCanyon’s bestsellers. 

7. ListApp

ListApp is a great React Native app template for developers looking to create any app with content that takes the form of lists. So if you’re interested in creating an app for the top restaurants, shops, sights, etc. in a specific area, this would be the template for you. 

ListApp

Some key features available with the app are the map and booking features, social login, and the ability to track bookings.

User harik567 says:

"The design is really good and while the actual UX is going to need some work it's very customizable and built on a solid code base. Definitely, a product to "grow" with if you are building a listing directory."

8BeoUI

BeoUI is a React Native app template for e-commerce. The template focuses on creating an attractive user interface that is easy to use. 

BeoUI

Its best features are the intro page with parallax effect, its choice of list or two-column views, the product slideshow, its selection of categories, and the profile page where shoppers can track their orders, receive notifications, or create a wish list.

9. Real Time Chat

If you’re looking for a template to help you create a messaging app that can be used for membership groups, Real Time Chat could be a good choice for you.

Real Time Chat

This React Native app template allows users to register with their name, email and a password, and lets them start chatting with other members in the group. As with the other templates included here, the Real Time Chat app template includes good documentation and video tutorials.

10. BeOnboard

First impressions count. So polish up your app’s initial appearance with BeOnboard, a collection of 18 React Native app templates which are designed to be used with any app in order to explain the app’s functionality to new users. 

BeOnboard

Easy to customise and use, the template aims to provide a great user interface and experience.

Conclusion

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

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

15 Best iOS App Templates of 2018

$
0
0

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 of 2018 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.

User nyskateboarding says:

“Very clear documentation and intuitive to setup. Had a support question and they got back to me quickly. Worth every dollar!”

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 their site easily and seamlessly. That’s what the BeoNews app template does. 

BeoNews

One of the best-rated templates in this category, this React Native mobile app allows users to convert any of the content of their WordPress site, including video, photos and blog, into a mobile app. The app stores user data on Firebase and synchronises across devices.

User sahilamanu says:

“The design quality of the app is so good. Also Minh (the author) was so supportive he helped me setup the app.”

3. WebViewGold 

The WebViewGold app template is another great template that allows users to convert website content 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 is optimised for iPhone, iPod touch, and iPad.

User Zyn said: 

“The script is awesome and 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 are trying to make the most of their time by doing their shopping while commuting or waiting in a queue. 

For those who own a physical shop but don’t yet have an online store, MStore provides a variety of ready-to-use e-commerce templates to create a mobile store app from scratch. 

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?

User abhibavishi says:

“Awesome product, great support! Love the quality of the code, along with the final output. I wish I could give more than 5 stars!”

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

User Simorq, says:

“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. 

The woopy app template 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.

User Larrybird1 says:

“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 or 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. Radio Play

For developers eager to create a radio station app, there’s the Radio Play app template. One of the best-rated apps in this category on CodeCanyon, not only does the template allow developers to add unlimited radio stations, but also the software includes all the features of TVML and all the files to build an application for tvOS. The app is wonderfully easy to customise and monetise.

Radio Play

User Arja7 says:

“This app is great, easy to use and install. Even though I do not have good coding skills it was all documented nicely and the steps are clear. Today I received approval from the Apple store.”

10. PikLab

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. 

The PikLab app template will appeal to users who prize simplicity and ease of use and are looking for a photo editing app that allows for creative play using features such as collage frames, stickers, borders, textures, and custom fonts. Users can share their pictures directly to Facebook, Twitter, Instagram, WhatsApp, etc. 

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

PikLab

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. Of course recipe apps have gained in popularity as well, so developers will love the iOS Recipe App template.

iOS Recipe App

The app allows users to organise 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. Template developers provide extensive documentation to guide developers through the modification of the template but do not provide direct support. 

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.

User sainthua says:

“Amazing coding. Highly recommended!”

13. Classify

Classify is the perfect app template for developers looking to develop a mobile classified ad app. Allows users to post and edit ads via their iOS device, search for what they need, browse listings by categories, and contact sellers. The app also supports AdMob.

Classify

User Arudkoksky says:

“The developer has created an amazing product that is easy to customise. Fast and accurate customer support.”

14. Instagram Mobile Template

Love Instagram? Want to create your own Instagram-type app? We have just the thing for you. The Instagram Mobile 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. 

Instagram Mobile Template

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.

User Mbosoft says:

“Customer support, code quality, customizability. I recommend it to everyone. Always new, updated and easy to use. No need for coding knowledge. Just follow the steps.

15. Four Dots

Our roundup of the 15 best iOS app templates for 2018 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 2018 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!

Building a Shopping List Application With CloudKit: Adding Records

$
0
0

In the first tutorial of this series, we explored the CloudKit framework and infrastructure. We also laid the foundation for the sample application that we're going to build, a shopping list application. In this tutorial, we are focusing on adding, editing, and removing shopping lists.

Prerequisites

As I mentioned in the previous tutorial, I will be using Xcode 7 and Swift 2. If you are using an older version of Xcode, then keep in mind that you are using a different version of the Swift programming language.

In this tutorial, we will continue working with the project we created in the first tutorial. You can download it from GitHub (tag adding_records).

1. Setting Up CocoaPods

The shopping list application will make use of the SVProgressHUD library, a popular library created by Sam Vermette that makes it easy to display a progress indicator. You can add the library manually to your project, but I strongly recommend using CocoaPods for managing dependencies. Are you new to CocoaPods? I've written an introductory tutorial to CocoaPods that will help you get up to speed.

Step 1: Creating a Podfile

Open Finder and navigate to the root of your Xcode project. Create a new file, name it Podfile, and add the following lines of Ruby to it.

The first line specifies the platform, iOS, and the project's deployment target, iOS 8.0. The second line is important if you're using Swift. Swift does not support static libraries, but CocoaPods does provide the option since version 0.36 to use frameworks. We then specify the dependencies for the Lists target of the project. Replace Lists with your target's name if your target is named differently.

Step 2: Installing Dependencies

Open Terminal, navigate to the root of your Xcode project, and run pod install. This will do a number of things for you, such as installing the dependencies specified in Podfile and creating an Xcode workspace.

After completing the CocoaPods setup, close the project and open the workspace CocoaPods created for you. The latter is very important. Open the workspace, not the project. The workspace includes two projects, the Lists project and a project named Pods.

2. Listing Shopping Lists

Step 1: Housekeeping

We're ready to refocus on the CloudKit framework. First, however, we need to do some housekeeping by renaming the ViewController class to the ListsViewController class.

Start by renaming ViewController.swift to ListsViewController.swift. Open ListsViewController.swift and change the name of the ViewController class to the ListsViewController class.

Next, open Main.storyboard, expand View Controller Scene in the Document Outline on the left and select View Controller. Open the Identity Inspector on the right and change Class to ListsViewController.


Step 2: Adding a Table View

When the user opens the application, it is presented with their shopping lists. We'll display the shopping lists in a table view. Let's start by setting up the user interface. Select the Lists View Controller in the Lists View Controller Scene and choose Embed In > Navigation Controller from Xcode's Editor menu.

Add a table view to the view controller's view and create the necessary layout constraints for it. With the table view selected, open the Attributes Inspector and set Prototype Cells to 1. Select the prototype cell and set Style to Basic and Identifier to ListCell.

With the table view selected, open the Connections Inspector. Connect the table view's dataSource and delegate outlets to the Lists View Controller.

Step 3: Empty State

Even though we're only creating a sample application to illustrate how CloudKit works, I'd like to display a message if something goes wrong or if no shopping lists were found on iCloud. Add a label to the view controller, make it as large as the view controller's view, create the necessary layout constraints for it, and center the label's text.

Since we're dealing with network requests, I also want to display an activity indicator view as long as the application is waiting for a response from iCloud. Add a activity indicator view to the view controller's view and center it in its parent view. In the Attributes Inspector, tick the checkbox labeled Hides When Stopped.

Lists View Controller

Step 4: Connecting Outlets

Open ListsViewController.swift and declare an outlet for the label, the table view, and the activity indicator view. This is also a good time to make the ListsViewController class conform to the UITableViewDataSource and UITableViewDelegate protocols.

Note that I've also added an import statement for the SVProgressHUD framework and that I've declared a static constant for the reuse identifier of the prototype cell we created in the storyboard.

Head back to the storyboard and connect the outlets with the corresponding views in the Lists View Controller Scene.

Step 5: Preparing the Table View

Before we fetch data from iCloud, we need to make sure the table view is ready to display the data. We first need to create a property, lists, to hold the records we're about to fetch. Remember that records are instances of the CKRecord class. This means the property that will hold the data from iCloud is of type [CKRecord], an array of CKRecord instances.

To get started, we need to implement three methods of the UITableViewDataSource protocol:

  • numberOfSectionsInTableView(_:)
  • numberOfRowsInSection(_:)
  • cellForRowAtIndexPath(_:)

If you have any experience working with table views, then the implementation of each of these methods is straightforward. However, cellForRowAtIndexPath(_:) may require some explanation. Remember that a CKRecord instance is a supercharged dictionary of key-value pairs. To access the value of a particular key, you invoke objectForKey(_:) on the CKRecord object. That's what we do in cellForRowAtIndexPath(_:). We fetch the record that corresponds with the table view row and ask it for the value for key "name". If the key-value pair doesn't exist, we display a dash to indicate the list doesn't have a name yet.

Step 6: Preparing the User Interface

There's one more step for us to take, prepare the user interface. In the view controller's viewDidLoad method, remove the fetchUserRecordID method call and invoke setupView, a helper method.

The setupView method prepares the user interface for fetching the list of records. We hide the label and the table view, and tell the activity indicator view to start animating.

Build and run the application on a device or in the iOS Simulator. If you've followed the above steps, you should see an empty view with a spinning activity indicator view in the center.

Busy Pretending to Be Fetching Data

Step 7: Creating a Record Type

Before we fetch any records, we need to create a record type for a shopping list in the CloudKit dashboard. The CloudKit dashboard is a web application that lets developers manage the data stored on Apple's iCloud servers.

Select the project in the Project Navigator and choose the Lists target from the list of targets. Open the Capabilities tab at the top and expand the iCloud section. Below the list of iCloud containers, click the button labeled CloudKit Dashboard.

Open CloudKit Dashboard

Sign in with your developer account and make sure the Lists application is selected in the top left. On the left, select Record Types from the Schema section. Every application has by default a Users record type. To create a new record type, click the plus button at the top of the third column. We will follow Apple's naming convention and name the record type Lists, not List.

Adding a New Record Type

Note that the first field is automatically created for you. Create a field  name and set type to Field Type to String. Don't forget to click the Save button at the bottom to create the Lists record type. We'll revisit the CloudKit Dashboard later in this series.

Next, enable indexing for your document property by going to the Indexes tab and adding a new SORTABLE and another QUERYABLE index type for name, and click Save.

Adding SORTABLE and QUERYABLE indexing

Finally, go to the SECURITY ROLES tab and for the purposes of this development exercise, check all the checkboxes to ensure your user has access to the table. 

Step 8: Performing a Query

With the Lists record type created, it's finally time to fetch some records from iCloud. The CloudKit framework provides two APIs to interact with iCloud, a convenience API and an API based on the NSOperation class. We will use both APIs in this series, but we're going to keep it simple for now and use the convenience API.

In Xcode, open ListsViewController.swift and invoke the fetchLists method in viewDidLoad. The fetchLists method is another helper method. Let's take a look at the method's implementation.

Because a shopping list record is stored in the user's private database, we first get a reference to the default container's private database. To fetch the user's shopping lists, we need to perform a query on the private database, using the CKQuery class.

We initialize a CKQuery instance by invoking the init(recordType:predicate:) designated initializer, passing in the record type and an NSPredicate object. 

Before we execute the query, we set the query's sortDescriptors property. We create an array containing an NSSortDescriptor object with key "name" and ascending set to true.

Executing the query is as simple as calling performQuery(_:inZoneWithID:completionHandler:) on privateDatabase, passing in query as the first argument. The second parameter specifies the identifier of the record zone on which the query will be performed. By passing in nil, the query is performed on the default zone of the database and we get an instance of each record returned from the query. 

At the end of the method, we invoke updateView. In this helper method, we update the user interface based on the contents of the lists property.

Build and run the application to test what we've got so far. We currently don't have any records, but we'll fix that in the next section of this tutorial.

No Records Found

3. Adding a Shopping List

Step 1: Creating the AddListViewController Class

Because adding and editing a shopping list are very similar, we are going to implement both at the same time. Create a new file and name it AddListViewController.swift. Open the newly created file and create a UIViewController subclass named AddListViewController. At the top, add import statements for the UIKitCloudKit, and SVProgressHUD frameworks. Declare two outlets, one of type UITextField! and one of type UIBarButtonItem!. Last but not least, create two actions, cancel(_:) and save(_:).

Step 2: Creating the User Interface

Open Main.storyboard and add a view controller to the storyboard. With the view controller selected, open the Identity Inspector on the right and set Class to AddListViewController.

Adding a View Controller and setting it to AddListViewcontroller

The user will be able to navigate to the add list view controller by tapping a button in the lists view controller. 

Drag a bar button item from the Object Library to the navigation bar of the lists view controller. With the bar button item selected, open the Attributes Inspector and set System Item to Add. Press Control and drag from the bar button item to the add list view controller and select Show Detail from the menu that appears.

Select the segue you just created and set Identifier to ListDetail in the Attributes Inspector on the right.

Adding ListDetail to inspector of segue

Add two bar button items to the navigation bar of the add list view controller, one on the left and one on the right. Set System Item of the left bar button item to Cancel and that of the right bar button item to Save. Finally, add a text field to the add list view controller. Center the text field and set its Alignment to center in the Attributes Inspector.

Add List View Controller

Finally, connect the outlets and actions you created in AddListViewController.swift to the corresponding user interface elements in the scene.

Step 3: AddListViewControllerDelegate Protocol

Before we implement the AddListViewController class, we need to declare a protocol that we'll use to communicate from the add list view controller to the lists view controller. The protocol defines two methods, one for adding and one for updating a shopping list. This is what the protocol looks like.

We also need to declare three properties, one for the delegate, one for the shopping list that is created or updated, and a helper variable that indicates whether we're creating a new shopping list or editing an existing record.

The implementation of the AddListViewController class is straight forward. The methods related to the view life cycle are short and easy to understand. In viewDidLoad, we first invoke the setupView helper method. We'll implement this method in a moment. We then update the value of the newList helper variable based on the value of the list property. If list is equal to nil, then we know that we're creating a new record. In viewDidLoad, we also add the view controller as an observer for UITextFieldTextDidChangeNotification notifications.

In viewDidAppear(_:), we call becomeFirstResponder on the text field to present the keyboard to the user.

In setupView, we invoke two helper methods, updateNameTextField and updateSaveButton. In updateNameTextField, we populate the text field if list is not nil. In other words, if we're editing an existing record, then we populate the text field with the name of that record.

The updateSaveButton method is in charge of enabling and disabling the bar button item in the top right. We only enable the save button if the name of the shopping list is not an empty string.

Step 4: Implementing Actions

The cancel(_:) action is as simple as it gets. We pop the top view controller from the navigation stack. The save(_:) action is more interesting. In this method, we extract the user's input from the text field and get a reference to the default container's private database.

If we're adding a new shopping list, then we create a new CKRecord instance by invoking init(recordType:), passing in RecordTypeLists as the record type. We then update the name of the shopping list by setting the value of the record for the key "name".

Because saving a record involves a network request and can take a non-trivial amount of time, we show a progress indicator. To save a new record or any changes to an existing record, we call saveRecord(_:completionHandler:) on privateDatabase, passing in the record as the first argument. The second argument is another completion handler that is invoked when saving the record completes, successfully or unsuccessfully.

The completion handler accepts two arguments, an optional CKRecord and an optional NSError. As I mentioned before, the completion handler can be invoked on any thread, which means that we need to code against that. We do this by explicitly invoking the processResponse(_:error:) method on the main thread.

In processResponse(_:error:), we verify if an error was thrown. If we did run into problems, we display an alert to the user. If everything went smoothly, we notify the delegate and pop the view controller from the navigation stack.

Last but not least, when the view controller receives a UITextFieldTextDidChangeNotification notification, it invokes updateSaveButton to update the save button.

Step 5: Tying Everything Together

In the ListsViewController class, we still need to take care of a few things. Let's start by conforming the class to the AddListViewControllerDelegate protocol.

This also means that we need to implement the methods of the AddListViewControllerDelegate protocol. In the controller(_:didAddList:) method, we add the new record to the array of CKRecord objects. We then sort the array of records, reload the table view, and invoke updateView on the view controller.

The sortLists method is pretty basic. We call sortInPlace on the array of records, sorting the array based on the record's name.

The implementation of the second method of the AddListViewControllerDelegate protocol, controller(_:didUpdateList:), looks almost identical. Because we're not adding a record, we only need to sort the array of records and reload the table view. There's no need to call updateView on the view controller since the array of records is, by definition, not empty.

To edit a record, the user needs to tap the accessory button of a table view row. This means that we need to implement the tableView(_:accessoryButtonTappedForRowWithIndexPath:) method of the UITableViewDelegate protocol. Before we implement this method, declare a helper property, selection, to store the user's selection.

In tableView(_:accessoryButtonTappedForRowWithIndexPath:), we store the user's selection in selection and tell the view controller to perform the segue that leads to the add list view controller.

We're almost there. When the segue with identifier ListDetail is performed, we need to configure the AddListViewController instance that is pushed onto the navigation stack. We do this in prepareForSegue(_:sender:).

The segue hands us a reference to the destination view controller, the AddListViewController instance. We set the delegate property, and, if a shopping list is updated, we set the view controller's list property to the selected record.

Build and run the application to see the result. You should now be able to add a new shopping list and edit the name of existing shopping lists.

4. Deleting Shopping Lists

Adding the ability to delete shopping lists isn't much extra work. The user should be able to delete a shopping list by swiping a table view row from right to left and tapping the delete button that is revealed. To make this possible, we need to implement two more methods of the UITableViewDataSource protocol:

  • tableView(_:canEditRowAtIndexPath:)
  • tableView(_:commitEditingStyle:forRowAtIndexPath:)

The implementation of tableView(_:canEditRowAtIndexPath:) is trivial as you can see below.

In tableView(_:commitEditingStyle:forRowAtIndexPath:), we fetch the correct record from the array of records and invoke deleteRecord(_:) on the view controller, passing in the record that needs to be deleted.

The deleteRecord(_:) method should look familiar by now. We show a progress indicator and call deleteRecordWithID(_:completionHandler:) on the default container's private database. Note that we're passing in the record identifier, not the record itself. The completion handler accepts two arguments, an optional CKRecordID and an optional NSError.

In the completion handler, we dismiss the progress indicator and invoke processResponseForDeleteRequest(_:recordID:error:) on the main thread. In this method, we inspect the values of recordID and error that the CloudKit API has given us and we update message accordingly. If the delete request was successful, then we update the user interface and the array of records.

That's it. It's time to properly test the application with some data. Run the application on a device or in the iOS Simulator and add a few shopping lists. You should be able to add, edit, and delete shopping lists.

Conclusion

Even though this article is fairly long, it's good to remember that we only briefly interacted with the CloudKit API. The convenience API of the CloudKit framework is lightweight and easy to use.

This tutorial, however, has also illustrated that your job as a developer isn't limited to interacting with the CloudKit API. It's important to handle errors, show the user when a request is in progress, update the user interface, and tell the user what is going on.

In the next article of this series, we take a closer look at relationships by adding the ability to fill a shopping list with items. An empty shopping list isn't of much use and it certainly isn't fun. Leave any questions you have in the comments below or reach out to me on Twitter.


Envato Elements Now Offers Video!

$
0
0

Welcome to video on Envato Elements!

If you work with video, your life just got a little easier. Instead of having to create everything from scratch or chase around the web looking for stock footage, motion graphics and After Effects templates, you can now access more than 60,000 top-quality video items, all in one place.

Read all about it on the Envato Blog, check out our related articles and courses, or go and check out the stock video and video templates for yourself!

Related Content

JavaScript Regular Expressions: Beyond the Basics

$
0
0

In our previous tutorial about regular expressions in JavaScript, you learned about the usefulness of regular expressions and how to write some of your own to match simple patterns.

After reading the previous tutorial, you should now have a good understanding of special characters like a backslash and character sequences like \w or \W. Here is a real quick summary of those character sequences:

  1. You can use \d or \D to match a digit or non-digit character in any given string respectively. Digit characters include 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. All other characters besides these nine will be matched by \D.
  2. You can use \w or \W to match a word or non-word character in any given string. Word characters include alphabets, digits and underscore. Everything else, like ₹, % etc. is considered a non-word character.
  3. You can use \s or \S to match space characters or non-space characters in a string. Space characters will include space, tab, form feed and line feed.

Instead of matching one character at a time, you can use the * symbol to match the preceding expression zero or more times. The + character will similarly match the preceding expression 1 or more times.

You can match a pattern any specific number of times by appending {n, m} to it. Here n is the minimum number of times you want to match it and m is the maximum limit. If you don't specify a value for m, the preceding expression will be matched as many times as possible.

You should check out my previous tutorial if anything that we just covered is not clear. I have explained everything in more detail there.

Now, let's move on to some more sophisticated character sequences in regular expressions, so that you can get the most out of them and figure out how to write expressions that match complicated patterns.

Non-Greedy Matches Using the ? Character

The ? character means different things in different situations.

When used alone, this character matches the expression that came before it 0 or 1 times. In this sense, it is the same as {0,1}.

You can also use ? immediately after other quantifiers like *, + and {} to match the minimum possible number of characters. In other words, it will turn those greedy quantifiers into non-greedy. This can be a bit hard to understand without looking at live examples so let's see an example first.

Consider the following sentence:

I have been assigned 17321HDGE as user id while my friend was assigned FHES193EK1.

Now, let's see all the matches that would have been returned by different quantifiers and their non-greedy counterpart.

If we use the expression /\d+/g in the example, it will match one or more consecutive digit characters. Due to the global flag, there will be three matches: 17321, 193 and 1.

You should note that 193 and 1 are considered different matches because they are separated by EK.

The following example shows the matches without the use of any quantifiers.

Now, adding a ? character after \d+ will return nine different matches. Basically, /\d+?/ will turn each digit character into a separate match. Why is that?

It is because \d+ is by definition supposed to match one or more digits. Since the ? character is supposed to match minimum possible number of characters, it just matches a single digit at a time.

The non-greedy ? quantifier, will return 9 smaller single digit matches this time. For brevity, I have commented out the line that logs the matches to console.

Let's take another example, the regular expression /\w+/ will keep matching word characters as long as they are not interrupted by a non-word character like space. In our case, it will match whole space separated words like assigned and 17321HDGE one a time.

If we replace our original regular expression with /\w+/, we will get 14 different matches, Basically, each word will be its own match. You can see the output yourself by commenting out the line.

Now, changing the expression to /\w+?/ will return each word character as a separate match and you will get 68 matches.

Let's take a look at one last example before we proceed further. The regular expression /\w{4,}/ will return all words in our sentence that are four characters or longer. So, it matches have, been, assigned and 17321HDGE among others. Now turning it to /\w{4,}?/ would return multiple matches from words with more than four characters. In our example, the returned matches would be have, been, assi, gned, 1732 and 1HGD.The character E at the end of 17321HDGE is not part of any matchbecause it could not be in the group of any four consecutive word characters.

Using Parentheses With the ? Character

In my previous regex tutorial, I briefly covered how parentheses can be used to remember part of a match. When used with a ? character, they can serve other purposes as well.

Sometimes, you want a group of characters to match as a unit. For instance, you could be looking for the occurrences of na once or twice as a match in the following text.

na naa nnaa nana naana

For clarification, you are looking for the bold text as matches: nanaa nnaa (nana)naana.The part in the bracket is supposed to be matched as a unit so it just counts as one match.

Almost everyone who is just starting out with regex will use the expression /na{1,2}/ with the intention of getting the expected outcome. In their minds, the {1,2} part is supposed to match one or two occurrences of n and a together. However, it actually matches a single occurrence of n followed by 1 or 2 occurrences of the character a.

I have rendered the matches returned by /na{1,2}/ in bold for clarification: nanaa nnaa(na)(na)(naa)(na). The parts in the brackets are separate matches. As you can see, we are not getting the result we wanted because {1,2} is not considering na to be a single unit that has to be matched.

The solution here is to use parentheses to tell JavaScript to match na as a unit. However, we saw in the previous tutorial, JavaScript will start remembering the match because of the parentheses.

If you don't want JavaScript to remember the match, then you will have to add ?: before the group of characters that you are trying to match. In our case, the final expression would become /(?:na){1,2}/. The group na will be matched as a unit now and it won't be remembered. I have highlighted the final matches returned with this expression in bold: nanaa nnaa (nana) naana.

The following example logs all the matches to console. Since there are 6 total matches, the total match count is 6.

Lookahead and Negated Lookahead

There are many situations where we are looking to match a given set of characters but only if they are or aren't followed by another set of characters. For example, you could be looking for the word apples in a text but only want those matches which are followed by are. Consider the following sentence.

apples are yummy. We ate apples all day. Everyone who ate apples liked them.

In the above example, we just want the first word as a match. Every other occurrence of the word should not be in the matches.

One way to achieve this is to use the following regular expression a(?=b). The word we want to match is a and the word which should come after a is b. In our case, the expression would become /apples(?=\sare)/. Remember that the word are is not included in this match.

This regular expression where we look at what comes next in the string before deciding if the word is a match is called a lookahead.

A very similar situation would arise if you decided to match apples only if it was not followed by a specific set of characters. In such cases, you need to replace ?= with ?! in your regular expression. If we were looking for all occurrences of apples which are not followed by are, we will use /apples(?!\sare)/ as our regular expression. There will be two successful matches for our test sentence.

One more thing, you don't need to use two separate regular expressions to find all matches which are followed by either of two given words. All you have to do is add the pipe operator between those words and you are good to go. For example, if you are looking for all occurrences of apple which are followed by are or were, you should use /apples(?!\sare|\swere)/ as your regular expression.

Final Thoughts

In this tutorial, we learned how to write complicated regular expressions to match the patterns we are looking for. We can use the special ? character to return the minimum required number of the preceding character as a match. Similarly, we can use the ? inside parentheses to make sure that the group we were matching is not remembered. Finally, we learned that the ?= and ?! character sequences in a regular expression give us the opportunity to return a particular set of characters as a match only if they are or aren't followed by another given set of characters.

If you have any questions related to this tutorial, feel free to let me know and I will do my best to explain them.

How to Update the Launcher Icon for Your Android App

$
0
0

Giving a product a professional user interface look and feel add value to it. When the user likes what he or she sees in an app UI, the chances that they will install it increases a great deal. There are a set of defined rules for the design, colour, icon and other UI elements that your Android app should follow. In this article, we will stick to the icons, the launcher icon, for your Android app.

The icons for an android app are segregated into several categories. These include:

  • Launcher Icon: this icon represents your app on the user's device's home screen or application list. This can either be an Adaptive Launcher Icon, for Android 8.0 (API level 26) or above, or a Legacy Launcher Icon, for Android 7.1 (API level 25) or below.
  • Action Bar Icons: for the items in the action bar. 
  • Tab Icons: for the tab items that have icons, if any

You can learn more about these icon categories by looking at other apps. Here is the example of the Whatsapp icons:

WhatsApp Icons Example

Now, creating these icons may seem easy if you are a designer, or if you are a developer who has a designer on your team. But it is not as easy as it seems. You will have to create icons for each different dimension, based on the Android device screen resolutions and density. To give you a sense of how much work this can be, here is the list of sizes for which you need to create the launcher icon if you are going to do it in the traditional way:

DensityIcon 
ldpi36 x 36 px
mdpi48 x 48 px
tvdpi
64 x 64 px
hdpi
72 x 72 px
xhdpi
96 x 96 px
xxhdpi
144 x 144 px
xxxhdpi
192 x 192 px
Web
512 x 512 px

And this is just the launcher icon. There is a similar list for each category of icon. But thankfully, Android Studio provides us with a tool called Image Asset Studio that handles the creation of icons for all screen densities very easily.

What is Image Asset Studio?

Android Studio 3 has introduced Image Asset Studio for creating icons for your app. It takes care of generating the app icons of appropriate resolution for different screen density and places them in the respective mipmap-density folders in the resource directory. It also generates the icon for the web (512 x 512 px) which is required for uploading the application to the Google Play Store. These icons are then fetched accordingly from the folders based on the screen density of the devices during runtime.

For adaptive launcher icons, the Image Asset Studio provides a complete preview of the icon set which includes circle, square, rounded square, squircle, full bleed layer, legacy icon, round and Google Play Store versions of the icon as well. 

Adaptive launcher Icons Preview

For legacy launcher icons, on the other hand, the devices do not support icons of varying shapes. So a more restricted set of icons will be generated.

Legacy Launcher Icons Preview

Using Image Asset Studio

Let's take a look at how to create an icon set using Image Asset Studio.

Update Icon using Image Asset Studio:

To start the Image Asset Studio, select Android in the Project Window. Right click on the res folder and select New -> Image Asset. You have now opened the Image Asset Studio. you can now create an Adaptive Launcher Icon or Legacy Only Launcher Icon as per your requirement.

Create an Adaptive Launcher Icon

        Adaptive Launcher Icon

You'll use this icon type for Android 8.0 support.

First, select Launcher Icons (Adaptive & Legacy) for Icon Type. Change the name of the icon if you wish to. If the name already exists, there will be a warning at the bottom of the dialog, telling the existing one will be overwritten. 

In the Foreground Layer Tab select the Asset Type: 

  • Image: Set the path of the custom icon image. 
  • Clip Art: Select icon from the set of material design icons and set the colour. 
  • Text: Set a specified string, set the font and the colour.

Similarly, in the Background Layer tab you can select an Image, Clip Art, or Text asset type.

For both the foreground and background layers, you also have the following optional settings: 

  • Layer Name: You can give the layer a unique name.
  • Scaling Parameters: can be set to your requirements. This option is disabled if you select a colour for the background layer.
  • Trim: Chose if you want to remove the transparent spaces around your icon.
  • Resize: Change the size of the icon.

The Legacy Tab lets you decide whether to also generate a legacy icon. Here you can choose whether you want to generate a legacy icon, a Google Play Store icon, and a round icon, as well as what shape to use for each of them.

Create a Legacy Launcher Icon

This is the kind of icon you'll create if you want to support versions of Android less than or equal to 7.1.

First select Launcher Icons (Legacy Only) for the Icon Type. You can change the Name of the icon at this time if you wish to. If the name already exists, there will be a warning at the bottom that the existing one will be overwritten. Select the Asset Type and configure the associate settings.

  • Image: Set the path of the custom icon image. 
  • Clip Art: Select icon from the set of material design icons and set the colour. 
  • Text: Set a specified string, set the font and the colour.

You can also configure some optional settings for the icon's appearance:

  • Trim: Chose if you want to remove the transparent spaces around your icon. 
  • Padding: Set the padding for the icon.
  • Foreground: Set the foreground colour.
  • Background: Set the background colour.
  • Scaling: Chose crop or shrink to fit.
  • Shape: To add a backdrop to the icon, select the shape. For a transparent backdrop, select none.
  • Effect: Chose whether to have a dog eared effect for your square or rectangular shaped icon.

Any changes you make, will be reflected in the preview section. Once you're happy with your icon's look and feel, click Next.

You will then be taken to the settings screen where you can change the Resource Directory where your icons will be emitted. Update it if you want. Following are the available options:

  • main/res:  for all build variants, including release and debug.
  • release/res: overrides the main source set for the single release version of the build.
  • debug/res: for debugging only.
  • custom source set: you can define your own source set.

Finally, wrap it up by pressing Finish.

Now we are ready with our new launcher icon in all the respective folders. The name of my launcher icon is ic_launcher_demo. You can see all the icons that were generated for this icon in the screenshot below.

Update the AndroidManifest File

Now it's time to update the AndroidManifest file so that our app knows to use the new icon. To start, open your AndroidManifest.xml file. Here is the default launcher icon set is set on line 7 and 9. You need to update it with the new icon that you created.

Change the android:icon and android:roundIcon to the name you have chosen for your launcher icon.

Congratulations! You have successfully updated the launcher icon for your app. 

Conclusion

In this post you learned about the different kinds of icons that are used in an Android app, as well as all the different screen resolutions that must be generated for each icon. Then you learned about the Image Asset Studio tool and how it makes generating icons for your Android app much easier.

Fetching Data in Your React Application

$
0
0

React is arguably the most popular library for building interactive web applications. However, React is not a full-fledged web framework. It focuses on the view part of the venerable MVC model. 

There is a whole React ecosystem that addresses other aspects. In this tutorial, you'll learn about one of the most basic elements of any web application—how to fetch data to display. This is not trivial. There are several places in the React component hierarchy where you can fetch data. When to fetch data is another concern. You also need to consider what technology to use for fetching your data and where to store it. 

At the end of this tutorial, you'll have a clear picture of how data fetching works in React, the pros and cons of different approaches, and how to apply this knowledge to your React applications.

Getting Started

Let's create a skeleton for our React app with create-react-app:

> create-react-app react-data-fetcher

The result is a pretty elaborate directory structure. Read the excellent README file if you're unfamiliar with create-react-app.

Creating a Simple Server

I created a simple server for storing and serving quotes. It is not the focus of this tutorial, and its role is to provide a remote API for demonstrating how to fetch data with React. Just to satisfy your curiosity, it is a Python 3 application based on the hug framework and uses Redis as persistent storage. 

The API is extremely simple. There is a single endpoint, /quotes. It returns all the stored quotes in response to an HTTP GET request, and you can add new quotes by sending an HTTP POST request.

The full source code is available on GitHub.

Demo App Overview

The demo app is a React application that communicates with the quote service, displays all the quotes, and lets you add new quotes. 

Here is a screenshot:

A screenshot of the demo application

The app structure is very simple. I started with a skeleton created by create-react-app and added two components in the src sub-directory: QuoteList and AddQuoteForm. Here is the directory structure (excluding node_modules):

The full source code is available on GitLab.

Displaying Quotes

The QuoteList functional component displays a list of quotes as a bullet list. It expects an array of strings:

It is a child component of the main App component.

Fetching Data With the Fetch API

The fetch API is a promise-based API that returns a response object. In order to get to the actual JSON content, you need to invoke the json() method of the response object.

Placing Your Data-Fetching Code

React is, of course, all about components. The question of where to place data-fetching code is important. If you factor your code well, you'll have a lot of generic components and some application-specific components. React and JavaScript in general are very flexible, so it is possible to inject logic anywhere. 

Fetching quotes from a REST API requires some form of polling, since I want the quotes to be always up to date. But the initial fetch is also important. React components have lifecycle methods where you can implement logic that will execute at a particular time. The componentDidMount() method fires when the component can be accessed and its state modified. It is the perfect spot to initiate data fetching. 

Here is what it looks like:

If you really want to cut down on the time to first view, you may consider using the componentWillMount() to initiate your async fetching, but you risk having the fetch complete before the component is mounted. I don't recommend this approach.

Check out Mastering the React Lifecycle Methods for further details.

Choosing How Often to Fetch Data

The initial fetch in componentDidMount() is great, but I want to update the quotes frequently. In a REST-based API, the only solution is to periodically poll the server. The quote service is very basic and always returns all the quotes. 

More scalable services will provide a way to check for updates or even using HTTP if-modify-since or eTag. Our demo application just fetches everything every five seconds by starting a timer in componentDidMount() and cleaning up in componentWillUnmount():

The polling duration is an app-specific decision. If you need real-time updates and/or polling is stressing the back end too much, consider using WebSockets instead of REST.

Dealing With Long-Running Data Fetching

Sometimes data fetching can take a long time. In that case, displaying a progress bar or a shiny animation to let the user know what's going on can contribute a lot to the user experience. This is especially important when the user initiates the data fetching (e.g. by clicking a search button). 

In the demo app, I simply display a message saying "Fetching quotes..." while a fetch is ongoing. In the render() method of the main App component, I utilize conditional rendering by checking the state.isFetching member. 

The fetchQuotes() method takes care of updating state.isFetching by initializing it to true when it starts and setting it back to false when receiving the quotes:

Handling Errors

I do the very minimum of error handling here by logging caught errors to the console. Depending on your application, you may invoke some retry logic, notify the user, or display some fallback content.

Fetch API vs. Axios

The fetch API has a couple of gotchas. It requires the extra step of extracting the JSON from a response. It also doesn't catch all errors. For example, 404 will be returned as a normal response. You'll have to check the response code and also deal with network errors that are getting caught. 

So you'll have to deal with errors in two places. But you can use the axios.js library to address these issues and have slightly more concise code at the price of adding an external dependency. Here is what the code looks like with axios:

This doesn't look like much, but it helps. The code to add a new quote is much more concise with axios. Here is the fetch version:

And here is the axios version:

Conclusion

In this tutorial you learned how to fetch data asynchronously in a React application. We discussed the relevant lifecycle methods, polling, progress reporting, and error handling. 

We looked at two promise-based libraries: the fetch API and axios.js. Now, go out there and build awesome React applications that access remote APIs.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.

New Course: Get Started Coding Android Apps With Kotlin

$
0
0

In our new course, Get Started Coding Android Apps With Kotlin, you will learn how to create a simple app with Kotlin. Your instructor, Annapurna Agrawal, will give you a comprehensive, practical introduction to this powerful language. 

You'll start by installing Android Studio with the Kotlin plugins in order to create and run your first Android app. You'll then go on to learn some of the basics of views and layouts in Android, how to use Android Intents, and how to use some of Kotlin's special features to write safer, more concise code. By the end of this course, you'll be able to use Android and Kotlin to build a basic app with cleaner code.

Get Started Coding Android Apps With Kotlin

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

 

Building a Shopping List Application With CloudKit: Adding Relationships

$
0
0

In the previous tutorial of this series, we added the ability to add, update, and remove shopping lists. A shopping list without any items in it isn't very useful, though. In this tutorial, we'll add the ability to add, update, and remove items from a shopping list. This means that we'll be working with references and the CKReference class.

We'll also take a closer look at the data model of the shopping list application. How easy is it to make changes to the data model, and how does the application respond to changes we make in the CloudKit Dashboard?

Prerequisites

Remember that I will be using Xcode 7 and Swift 2. If you are using an older version of Xcode, then keep in mind that you are using a different version of the Swift programming language.

In this tutorial, we will continue where we left off in the second tutorial of this series. You can download or clone the project from GitHub.

1. Shopping List Details

Currently, the user can modify the name of a shopping list by tapping the detail disclosure indicator, but the user should also be able to see the contents of a shopping list by tapping one in the lists view controller. To make this work, we first need a new UIViewController subclass.

Step 1: Creating ListViewController

The ListViewController class will display the contents of a shopping list in a table view. The interface of the ListViewController class looks similar to that of the ListsViewController class. We import the CloudKit and SVProgressHUD frameworks and conform the class to the UITableViewDataSource and UITableViewDelegate protocols. Because we'll be using a table view, we declare a constant, ItemCell, that will serve as a cell reuse identifier.

We declare three outlets: messageLabel of type UILabel!tableView of type UITableView!, and activityIndicatorView of type UIActivityIndicatorView!. The list view controller keeps a reference to the shopping list it is displaying in the list property, which is of type CKRecord!. The items in the shopping list are stored in the items property, which is of type [CKRecord]. Finally, we use a helper variable, selection, to keep track of which item in the shopping list the user has selected. This will become clear later in this tutorial.

Step 2: Creating the User Interface

Open Main.storyboard, add a view controller, and set its class to ListViewController in the Identity Inspector. Select the prototype cell of the lists view controller, press the Control key, and drag from the prototype cell to the list view controller. Choose Show from the menu that pops up, and set the identifier to List in the Attributes Inspector.

Add a table view, a label, and an activity indicator view to the view controller's view. Don't forget to wire up the outlets of the view controller as well as those of the table view.

Select the table view and set Prototype Cells to 1 in the Attributes Inspector. Select the prototype cell, and set Style to Right Detail, Identifier to ItemCell, and Accessory to Disclosure Indicator. This is what the view controller should look like when you're finished.

List View Controller

Step 3: Configuring the View Controller

Before we revisit the CloudKit framework, we need to prepare the view controller for the data it's going to receive. Start by updating the implementation of viewDidLoad. We set the view controller's title to the name of the shopping list and invoke two helper methods, setupView and fetchItems.

The setupView method is identical to the one we implemented in the ListsViewController class.

While we're at it, let's also implement another familiar helper method, updateView. In updateView, we update the user interface of the view controller based on the items stored in the items property.

I'm going to leave fetchItems empty for now. We'll revisit this method once we're finished setting up the list view controller.

Step 4: Table View Data Source Methods

We're almost ready to take the application for another test run. Before we do, we need to implement the UITableViewDataSource protocol. If you've read the previous installments of this series, then the implementation will look familiar.

Step 5: Handling Selection

To tie everything together, we need to revisit the ListsViewController class. Start by implementing the tableView(_:didSelectRowAtIndexPath:) method of the UITableViewDelegate protocol.

We also need to update prepareForSegue(segue:sender:) to handle the segue we created a few moments ago. This means that we need to add a new case to the switch statement.

To satisfy the compiler, we also need to declare the SegueList constant at the top of ListsViewController.swift.

Build and run the application to see if everything is wired up correctly. Because we haven't implemented the fetchItems method yet, no items will be displayed. That's something we need to fix.

2. Fetching Items

Step 1: Create a Record Type

Before we can fetch items from the CloudKit backend, we need to create a new record type in the CloudKit Dashboard. Navigate to the CloudKit Dashboard, create a new record type, and name it Items. Each item should have a name, so create a new field, set the field name to name, and set the field type to String.

Each item should also know to which shopping list it belongs. That means each item needs a reference to its shopping list. Create a new field, set the field name to list, and set the field type to Reference. The Reference field type was designed for this exact purpose, managing relationships.

Item Record Type

Head back to Xcode, open ListsViewController.swift, and declare a new constant at the top for the Items record type.

Step 2: Fetching Items

Open ListViewController.swift and navigate to the fetchItems method. The implementation is similar to the fetchLists method of the ListsViewController class. There is an important difference, though.

The difference between fetchItems and fetchLists is the predicate we pass to the CKQuery initializer. We're not interested in every item in the user's private database. We're only interested in the items that are associated with a particular shopping list. This is reflected in the predicate of the CKQuery instance.

We create the predicate by passing in a CKReference instance, which we create by invoking init(recordID:action:). This method accepts two arguments: a CKRecordID instance that references the shopping list record and a CKReferenceAction instance that determines what happens when the shopping list is deleted.

Reference actions are very similar to delete rules in Core Data. If the referenced object (the shopping list in this example) is deleted, then the CloudKit framework inspects the reference action to determine what should happen to the records that hold a reference to the deleted record. The CKReferenceAction enum has two member values:

  • None: If the reference is deleted, nothing happens to the records referencing the deleted record.
  • DeleteSelf: If the reference is deleted, every record referencing the deleted record is also deleted.

Because no item should exist without a shopping list, we set the reference action to DeleteSelf.

The processResponseForQuery(records:error:) method contains nothing new. We process the response of the query and update the user interface accordingly.

Build and run the application. You won't see any items yet, but the user interface should update to reflect that the shopping list is empty.

3. Adding Items

Step 1: Creating AddItemViewController

It's time to implement the ability to add items to a shopping list. Start by creating a new UIViewController subclass, AddItemViewController. The interface of the view controller is similar to that of the AddListViewController class.

At the top, we import the CloudKit and SVProgressHUD frameworks. We declare the AddItemViewControllerDelegate protocol, which will serve the same purpose as the AddListViewControllerDelegate protocol. The protocol defines two methods, one for adding items and one for updating items.

We declare two outlets, a text field and a bar button item. We also declare a property for the delegate and a helper variable, newItem, that helps us determine whether we're creating a new item or updating an existing item. Finally, we declare a property list for referencing the shopping list to which the item will be added and a property item for the item we're creating or updating.

Before we create the user interface, let's implement two actions that we'll need in the storyboard, cancel(_:) and save(_:). We'll update the implementation of the save(_:) action later in this tutorial.

Step 2: Creating the User Interface

Open Main.storyboard, add a bar button item to the navigation bar of the list view controller, and set System Item to Add in the Attributes Inspector. Drag a view controller from the Object Library and set its class to AddItemViewController. Create a segue from the bar button item we just created to the add item view controller. Choose Show from the menu that pops up, and set the segue's identifier to ItemDetail.

Add two bar button items to the navigation bar of the add item view controller, a cancel button on the left and a save button on the right. Connect each bar button item to its corresponding action. Add a text field to the view controller's view and don't forget to connect the outlets of the view controller. This is what the add item view controller should look like when you're finished.

Add Item View Controller

Step 3: Configuring the View Controller

The implementation of the add item view controller contains nothing that we haven't covered yet. There's one exception, though, which we'll discuss in a moment. Let's start by configuring the view controller in viewDidLoad.

We invoke setupView, a helper method, and update the value of newItem. If the item property is equal to nilnewItem is equal to true. This helps us determine whether we're creating or updating a shopping list item.

We also add the view controller as an observer for notifications of type UITextFieldTextDidChangeNotification. This means that the view controller is notified when the contents of the nameTextField change.

In viewDidAppear(animated:), we show the keyboard by calling becomeFirstResponder on nameTextField.

The setupView method invokes two helper methods, updateNameTextField and updateSaveButton. The implementation of these helper methods is straightforward. In updateNameTextField, we populate the text field. In updateSaveButton, we enable or disable the save button based on the contents of the text field.

Before we take a look at the updated implementation of the save(_:) method, we need to implement the textFieldDidChange(_:) method. All we do is invoke updateSaveButton to enable or disable the save button.

Step 4: Saving Items

The save(_:) method is the most interesting method of the AddItemViewController class, because it shows us how to work with CloudKit references. Take a look at the implementation of the save(_:) method below.

Most of its implementation should look familiar since we covered saving records in the AddListViewController class. What interests us most is how the item keeps a reference to its shopping list. We first create a CKReference instance by invoking the designated initializer, init(recordID:action:). We covered the details of creating a CKReference instance a few minutes ago when we created the query for fetching shopping list items.

Telling the item about this reference is easy. We invoke setObjec(_:forKey:) on the item property, passing in the CKReference instance as the value and "list" as the key. The key corresponds to the field name we assigned in the CloudKit Dashboard. Saving the item to iCloud is identical to what we've covered before. That's how easy it is to work with CloudKit references.

The implementation of processResponse(record:error:) contains nothing new. We check to see if any errors popped up and, if no errors were thrown, we notify the delegate.

Step 5: Updating ListViewController

We still have some work to do in the ListViewController class. Start by conforming the ListViewController class to the AddItemViewControllerDelegate protocol. This is also a good moment to declare a constant for the segue with the identifier ItemDetail.

Implementing the AddItemViewControllerDelegate protocol is trivial. In controller(_:didAddItem:), we add the new item to items, sort items, reload the table view, and invoke updateView.

The implementation of controller(_:didUpdateItem:) is even easier. We sort items and reload the table view.

In sortItems, we sort the array of CKRecord instances by name using the sortInPlace function, a method of the MutableCollectionType protocol.

There are two more features we need to implement: updating and deleting shopping list items.

Step 6: Deleting Items

To delete items, we need to implement tableView(_:commitEditingStyle:forRowAtIndexPath:) of the UITableViewDataSource protocol. We fetch the shopping list item that needs to be deleted and pass it to the deleteRecord(_:) method.

The implementation of deleteRecord(_:) doesn't contain anything new. We invoke deleteRecordWithID(_:completionHandler:) on the private database and process the response in the completion handler.

In processResponseForDeleteRequest(record:recordID:error:), we update the items property and the user interface. If something went wrong, we notify the user by showing an alert.

Step 7: Updating Items

The user can update an item by tapping the detail disclosure indicator. This means we need to implement the tableView(_:accessoryButtonTappedForRowWithIndexPath:) delegate method. In this method, we store the user's selection and manually perform the ListDetail segue. Note that nothing happens in the tableView(_:didSelectRowAtIndexPath:) method. All we do is deselect the row the user tapped.

In prepareForSegue(_:sender:), we fetch the shopping list item using the value of the selection property and configure the destination view controller, an instance of the AddItemViewController class.

That's all we need to do to delete and update shopping list items. In the next section, we explore how easy it is to update the data model in the CloudKit Dashboard.

4. Updating the Data Model

If you've ever worked with Core Data, then you know that updating the data model should be done with caution. You need to make sure you don't break anything or corrupt any of the application's persistent stores. CloudKit is a bit more flexible.

The Items record type currently has two fields, name and list. I want to show you what it involves to update the data model by adding a new field. Open the CloudKit Dashboard and add a new field to the Items record. Set field name to number and set the field type to Int(64). Don't forget to save your changes.

Update Item Record Type

Let's now add the ability to modify an item's number. Open AddItemViewController.swift and declare two outlets, a label and a stepper.

We also need to add an action that is triggered when the stepper's value changes. In numberDidChange(_:), we update the contents of numberLabel.

Open Main.storyboard and add a label and a stepper to the add item view controller. Connect the outlets of the view controller to the corresponding user interface elements and connect the numberDidChange(_:) action to the stepper for the Value Changed event.

Update Add Item View Controller

The save(_:) action of the AddItemViewController class also changes slightly. Let's see what that looks like.

We only need to add two lines of code. At the top, we store the value of the stepper in a constant, number. When we configure item, we set number as the value for the "number" key, and that's all there is to it.

We also need to implement a helper method to update the user interface of the add item view controller. The updateNumberStepper method checks if the record has a field named number and updates the stepper if it does.

We invoke updateNumberStepper in the setupView method of the AddItemViewController class.

To visualize the number of each item, we need to make one change to the ListViewController. In tableView(_:cellForRowAtIndexPath:), we set the contents of the cell's right label to the value of the item's number field.

That's all we need to do to implement the changes we made to the data model. There's no need to perform a migration or anything like that. CloudKit takes care of the nitty gritty details.

Conclusion

You should now have a proper foundation in the CloudKit framework. I hope you agree that Apple has done a great job with this framework and the CloudKit Dashboard. There's a lot that we haven't covered in this series, but by now you've learned enough to jump in and get started with CloudKit in your own projects.

If you have any questions or comments, feel free to leave them in the comments below or reach out to me on Twitter.

Set Up an OAuth2 Server Using Passport in Laravel

$
0
0

In this article, we’re going to explore how you could set up a fully fledged OAuth2 server in Laravel using the Laravel Passport library. We’ll go through the necessary server configurations along with a real-world example to demonstrate how you could consume OAuth2 APIs.

I assume that you’re familiar with the basic OAuth2 concepts and flow as we’re going to discuss them in the context of Laravel. In fact, the Laravel Passport library makes it pretty easy to quickly set up an OAuth2 server in your application. Thus, other third-party applications are able to consume APIs provided by your application.

In the first half of the article, we’ll install and configure the necessary libraries, and the second half goes through how to set up demo resources in your application and consume them from third-party applications.

Server Configurations

In this section, we're going to install the dependencies that are required in order to make the Passport library work with Laravel. After installation, there's quite a bit of configuration that we'll need to go through so that Laravel can detect the Passport library.

Let's go ahead and install the Passport library using composer.

That's pretty much it as far as the Passport library installation is concerned. Now let's make sure that Laravel knows about it.

Working with Laravel, you're probably aware of the concept of a service provider that allows you to configure services in your application. Thus, whenever you want to enable a new service in your Laravel application, you just need to add an associated service provider entry in the config/app.php.

If you're not aware of Laravel service providers yet, I would strongly recommend that you do yourself a favor and go through this introductory article that explains the basics of service providers in Laravel.

In our case, we just need to add the PassportServiceProvider provider to the list of service providers in config/app.php as shown in the following snippet.

Next, we need to run the migrate artisan command, which creates the necessary tables in a database for the Passport library.

To be precise, it creates following the tables in the database.

Next, we need to generate a pair of public and private keys that will be used by the Passport library for encryption. As expected, the Passport library provides an artisan command to create it easily.

That should have created keys at storage/oauth-public.key and storage/oauth-private.key. It also creates some demo client credentials that we'll get back to later.

Moving ahead, let's oauthify the existing User model class that Laravel uses for authentication. To do that, we need to add the HasApiTokens trait to the User model class. Let's do that as shown in the following snippet.

The HasApiTokens trait contains helper methods that are used to validate tokens in the request and check the scope of resources being requested in the context of the currently authenticated user.

Further, we need to register the routes provided by the Passport library with our Laravel application. These routes will be used for standard OAuth2 operations like authorization, requesting access tokens, and the like.

In the boot method of the app/Providers/AuthServiceProvider.php file, let's register the routes of the Passport library.

Last but not least, we need to change the api driver from token to passport in the config/auth.php file, as we're going to use the Passport library for the API authentication.

So far, we've done everything that's required as far as the OAuth2 server configuration is concerned.

Set Up the Demo Resources

In the previous section, we did all the hard work to set up the OAuth2 authentication server in our application. In this section, we'll set up a demo resource that could be requested over the API call.

We will try to keep things simple. Our demo resource returns the user information provided that there's a valid uid parameter present in the GET request.

Let's create a controller file app/Http/Controllers/UserController.php with the following contents.

As usual, you need to add an associated route as well, which you are supposed to add in the routes/web.php file. But what we are talking about is the API route, and thus it needs special treatment.

The API routes are defined in the routes/api.php file. So, let's go ahead and add our custom API route as shown in the following snippet.

Although we've defined it as /user/get, the effective API route is /api/user/get, and that's what you should use when you request a resource over that route. The api prefix is automatically handled by Laravel, and you don't need to worry about that!

In the next and last section, we'll discuss how you could create client credentials and consume the OAuth2 API.

How to Consume OAuth2 APIs

Now that we've set up the OAuth2 server in our application, any third party can connect to our server with OAuth and consume the APIs available in our application.

First of all, third-party applications must register with our application in order to be able to consume APIs. In other words, they are considered as client applications, and they will receive a client id and client secret upon registration.

The Passport library provides an artisan command to create client accounts without much hassle. Let's go ahead and create a demo client account.

When you run the artisan passport:client command, it asks you a few questions before creating the client account. Out of those, there's an important one that asks you the callback URL.

The callback URL is the one where users will be redirected back to the third-party end after authorization. And that's where the authorization code that is supposed to be used in exchange for the access token will be sent. We are about to create that file in a moment.

Now, we're ready to test OAuth2 APIs in the Laravel application.

For demonstration purposes, I'll create the oauth2_client directory under the document root in the first place. Ideally, these files will be located at the third-party end that wants to consume APIs in our Laravel application.

Let's create the oauth2_client/auth_redirection.php file with the following contents.

Make sure to change the client_id and redirect_uri parameters to reflect your own settings—the ones that you used while creating the demo client account.

Next, let's create the oauth2_client/callback.php file with the following contents.

Again, make sure to adjust the URLs and client credentials according to your setup in the above file.

How It Works Altogether

In this section, we'll test it altogether from the perspective of an end user. As an end user, there are two applications in front of you:

  1. The first one is the Laravel application that you already have an account with. It holds your information that you could share with other third-party applications.
  2. The second one is the demo third-party client application, auth_redirection.php and callback.php, that wants to fetch your information from the Laravel application using the OAuth API.

The flow starts from the third-party client application. Go ahead and open the http://localhost/oauth2_client/auth_redirection.php URL in your browser, and that should redirect you to the Laravel application. If you're not already logged into the Laravel application, the application will ask you to do so in the first place.

Once the user is logged in, the application displays the authorization page.

If the user authorizes that request, the user will be redirected back to the third-party client application at http://localhost/oauth2_client/callback.php along with the code as the GET parameter that contains the authorization code.

Once the third-party application receives the authorization code, it could exchange that code with the Laravel application to get the access token. And that's exactly what it has done in the following snippet of the oauth2_client/callback.php file.

Next, the third-party application checks the response of the CURL request to see if it contains a valid access token in the first place.

As soon as the third-party application gets the access token, it could use that token to make further API calls to request resources as needed from the Laravel application. Of course, the access token needs to be passed in every request that's requesting resources from the Laravel application.

We've tried to mimic the use-case in that the third-party application wants to access the user information from the Laravel application. And we've already built an API endpoint, http://your-laravel-site-url/api/user/get, in the Laravel application that facilitates it.

So that's the complete flow of how you're supposed to consume the OAuth2 APIs in Laravel.

And with that, we’ve reached the end of this article.

Conclusion

Today, we explored the Passport library in Laravel, which allows us to set up an OAuth2 server in an application very easily. 

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

Don't hesitate to share your thoughts and queries using the feed below!


Send Emails in PHP Using the Swift Mailer

$
0
0

In this article, we're going to explore the Swift Mailer library that allows you to send emails from PHP applications. Starting with installation and configuration, we'll go through a real-world example that demonstrates various aspects of sending emails using the Swift Mailer library.

What is Swift Mailer?

When it comes to sending emails in PHP applications, there are plethora of options to choose from. You might even end up creating your own wrapper to setup email features quickly. However, you're always in luck if you're using a well maintained and a feature-rich library.

The Swift Mailer is a popular library for sending emails from PHP applications, and is widely accepted by the PHP community. It's a feature-rich library in the sense that it covers almost every aspect of sending emails: from setting up different transports to customizing the message that's being sent.

In fact, it's a pretty straightforward process to send emails using the Swift Mailer library.

  1. initialize the Transport (SMTP/Sendmail) object
  2. initialize the Mailer object with that Transport
  3. initialize the Message object
  4. format and send the message

In the next section, we'll go through a real world example to demonstrate each of the aforementioned steps.

Installation And Configuration

In this section, we'll go through installation and configuration of the Swift Mailer library. The instillation is pretty straightforward, as it's already available as a Composer package. Before we go ahead, make sure you've installed the Composer because we'll need it to install the Swift Mailer library.

Once you've installed the Composer, go ahead and grab the Swift Mailer library using the following command.

With that, the Swift Mailer library should be installed, along with the necessary dependencies in the vendor directory. And the contents of the newly created composer.json should look like this:

So, that's the installation part, but how are you supposed to use it? In fact, it's just a matter of including the autoload.php file created by Composer in your application as shown in the following snippet.

How to Send Mails

In the earlier section, we explored how to install the Swift Mailer library using Composer. In this section, we'll start implementing a real world example.

Go ahead and create the email.php file with the following contents.

Let's go through how this code works.

Initialize Swift Mailer

The Swift Mailer library supports different transports like SMTP and Sendmail while sending an email. So, the first thing that you need to do is to initialize the transport object.

In the above example, I've used the SMTP transport to send mails.

Of course, if you would like to use the Sendmail protocol, you'll need to initialize the corresponding Swift_SendmailTransport object.

Once the transport is created, we need to initialize a mailer object and pass the transport that we've created already.

Create a Message

After creating the transport and mailer objects, the only remaining thing is to instantiate the Swift_Message object and decorate it with necessary attributes.

Now, we'll use the $message object to prepare contents of our message. To start with, the setSubject method allows you to set the subject of the email.

The setFrom method is used to set the from address of the email.

Moving ahead, let's set the To address of the email. In fact, there are couple of variations for setting recipients of the email. If you want to set a single recipient, you can use the addTo method and the setTo method on the other end is used to set multiple recipients.

The addCc and addBcc methods are used to set the CC and BCC addresses of the email respectively.

Attaching Files

Next, let's have a look at how you can attach a file to an email. 

You first need to instantiate the Swift_Attachment object with a valid filename. After creating the attachment object, you can add it to the email with the attach method. Also, you can use the setFilename method if you want to change the filename that will appear in the message attachment.

Along with regular file attachments, sometimes you want to embed images in the message text. You can do that by using the embed method as shown in the following snippet. The embed method returns the unique ID of the embedded object, which you can use later on in the message while referencing the image via src property.

The Message Body

Next, let's set the email body by using the setBody method.

If you want to set the HTML version of the message, you can use the addPart method as shown in the following snippet. As you can see, we're using $cid to reference the image we embedded earlier.

Send the Message!

Finally, we'll use the send method of the Mailer object to send the email.

Try running the script, and you should receive an email! Let me know in the comment section if you face any issues.

Conclusion

Today, we looked at one of the most popular PHP libraries for sending emails: Swift Mailer. With this library, you can effortlessly send emails from your PHP scripts.

Feel free to post your thoughts and queries using the form below.

Keys, Credentials and Storage on Android

$
0
0

In the previous post on Android user data security, we looked at encrypting data via a user-supplied passcode. This tutorial will shift the focus to credential and key storage. I'll begin by introducing account credentials and end with an example of protecting data using the KeyStore.

Often when working with a third-party service there will be some form of authentication required. This may be as simple as a /login endpoint that accepts a username and password. It would seem at first that a simple solution is to build UI that asks the user to log in, then capture and store their login credentials. However, this isn't the best practice because our app shouldn't need to know the credentials for a 3rd party account. Instead, we can use the Account Manager, which delegates handling that sensitive information for us.

Account Manager

The Account Manager is a centralized helper for user account credentials so that your app does not have to deal with passwords directly. It often provides a token in place of the real username and password that can be used to make authenticated requests to a service. An example is when requesting an OAuth2 token. Sometimes all the required information is already stored on the device, and other times the Account Manager will need to call a server for a refreshed token. You may have seen the Accounts section in your device's Settings for various apps. We can get that list of available accounts like this:


The code will require the android.permission.GET_ACCOUNTS permission. If you're looking for a specific account, you can find it like this:

Once you have the account, a token for the account can be retrieved by calling the getAuthToken(Account, String, Bundle, Activity, AccountManagerCallback, Handler) method. The token can then be used to make authenticated API requests to a service. This could be a RESTful API where you pass in a token parameter during an HTTPS request, without having to ever know the user's private account details.

Because each service will have a different way of authenticating and storing the private credentials, the Account Manager provides authenticator modules for a 3rd party service to implement. While Android has implementations for many popular services, it means you can write your own authenticator to handle your app's account authentication and credential storage. This allows you to make sure the credentials are encrypted. Keep in mind, this also means that credentials in the Account Manager that are used by other services may be stored in clear text, making them visible to anyone who has rooted their device.

Instead of simple credentials, there are times when you will need to deal with a key or a certificate for an individual or entity, for example, when a third party sends you a certificate file which you need to keep. The most common scenario is when an app needs to authenticate to a private organization's server. In the next tutorial, we will be looking at using certificates for authentication and secure communications, but I still want to address how to store these items in the meantime. The Keychain API was originally built for that very specific use—installing a private key or certificate pair from a PKCS#12 file.

The Keychain

Introduced in Android 4.0 (API Level 14), the Keychain API deals with key management. Specifically, it works with PrivateKey andX509Certificate objects and provides a more secure container than using your app's data storage. That's because permissions for private keys only allow for your own app to access the keys, and only after user authorization. This means that a lock screen must be set up on the device before you can make use of the credential storage. Also, the objects in the keychain may be bound to secure hardware, if available. The code to install a certificate is as follows:


The user will be prompted for a password to access the private key and an option to name the certificate. To retrieve the key, the following code presents UI that lets the user choose from the list of installed keys.

Once the choice is made, a string alias name is returned in the alias(final String alias) callback where you can access the private key or certificate chain directly.

Armed with that knowledge, let's now see how we can use the credential storage to save your own sensitive data.

The KeyStore

In the previous tutorial, we looked at protecting data via a user-supplied passcode. This kind of setup is good, but app requirements often steer away from having users login each time and remember an additional passcode. That's where the KeyStore API can be used. Since API 1, the KeyStore has been used by the system to store WIFI and VPN credentials. As of 4.3 (API 18), it allows working with your own app-specific asymmetric keys, and in Android M (API 23) it can store an AESsymmetric key. So while the API doesn't allow storing sensitive strings directly, these keys can be stored, and then used to encrypt strings. 

The benefit to storing a key in the KeyStore is that it allows keys to be operated on without exposing the secret content of that key; key data does not enter the app space. Remember that keys are protected by permissions so that only your app can access them, and they may additionally be secure hardware-backed if the device is capable. This creates a container that makes it more difficult to extract keys from a device. 

Generate a New Random Key

So for this example, instead of generating an AES key from a user-supplied passcode, we can auto-generate a random key that will be protected in the KeyStore. We can do this by creating a KeyGenerator instance, set to the "AndroidKeyStore" provider.

Important parts to look at here are the .setUserAuthenticationRequired(true) and .setUserAuthenticationValidityDurationSeconds(120) specifications. These require a lock screen to be set up and lock the key until the user has authenticated. Looking at the documentation for .setUserAuthenticationValidityDurationSeconds(), you will see that it means the key is only available a certain number of seconds from password authentication, and that passing in -1 requires finger print authentication every time you want to access the key. Enabling the requirement for authentication also has the effect of revoking the key when the user removes or changes the lock screen. Because storing an unprotected key along side the encrypted data is like putting a house key under the doormat, these options attempt to protect the key at rest in the event a device is compromised. An example might be an offline data dump of the device. Without the password being known for the device, that data is rendered useless.

The .setRandomizedEncryptionRequired(true) option enables the requirement that there is enough randomization (a new random IV each time) so that if the exact same data is encrypted a second time around, that encrypted output will still be different. This prevents an attacker from gaining clues about the ciphertext based on feeding in the same data. Another option to note is setUserAuthenticationValidWhileOnBody(boolean remainsValid), which locks the key once the device has detected it is no longer on the person.

Encrypting Data

Now that the key is stored in the KeyStore, we can create a method that encrypts data using the Cipher object, given theSecretKey. It will return a HashMap containing the encrypted data, and a randomized IV that will be needed to decrypt the data. The encrypted data, along with the IV, can then be saved to a file or into the shared preferences.

Decrypting to a Byte Array

For decryption, the reverse is applied. The Cipher object is initialized using the DECRYPT_MODE constant and a decrypted byte[] array is returned.

Testing the Example

We can now test our example!

Using RSA Asymmetric Keys for Older Devices

This is a good solution to store data for versions M and higher, but what if your app supports earlier versions? While AES symmetric keys are not supported under M, RSA asymmetric keys are. That means we can use RSA keys and encryption to accomplish the same thing. The main difference here is that an asymmetric keypair contains two keys, a private and a public key, where the public key encrypts the data and the private key decrypts it. A KeyPairGeneratorSpec is passed into the KeyPairGenerator that is initialized with KEY_ALGORITHM_RSAand the "AndroidKeyStore" provider.

To encrypt, we get the RSAPublicKey from the keypair and use it with theCipher object. 

Decryption is done using the RSAPrivateKey object.

One thing about RSA is that encryption is slower than it is in AES. This is usually fine for small amounts of information such as when you're securing shared preference strings. If you find there is a performance problem encrypting large amounts of data, however, you can instead use this example to encrypt and store just an AES key. Then, use that faster AES encryption that was discussed in theprevious tutorialfor the rest of your data. You can generate a new AES key and convert it to abyte[] array that is compatible with this example.

To get the key back from the bytes, do this:

That was a lot of code! To keep all of the examples simple, I have omitted thorough exception handling. But remember that for your production code, it's not recommended to simply catch all Throwable cases in one catch statement.

Conclusion

This completes the tutorial on working with credentials and keys. Much of the confusion around keys and storage has to do with the evolution of the Android OS, but you can choose which solution to use given the API level your app supports. 

Now that we have covered the best practices for securing data at rest, the next tutorial will focus on securing data in transit. 







Creating Stylish and Responsive Progress Bars Using ProgressBar.js

$
0
0

Nothing on the web happens instantly. The only difference is in the time it takes for a process to complete. Some processes can happen in a few milliseconds, while others can take up to several seconds or minutes. For example, you might be editing a very large image uploaded by your users, and this process can take some time. In such cases, it is a good idea to let the visitors know that the website is not stuck somewhere but it is actually working on your image and making some progress.

One of the most common ways to show readers how much a process has progressed is to use progress bars. In this tutorial, you will learn how to use the ProgressBar.js library to create different progress bars with simple and complex shapes.

Creating a Basic Progress Bar

Once you have included the library in your project, creating a progress bar using this library is easy. ProgressBar.js is supported in all major browsers, including IE9+, which means that you can use it in any website you are creating with confidence. You can get the latest version of the library from GitHub or directly use a CDN link to add it in your project.

To avoid any unexpected behavior, please make sure that the container of the progress bar has the same aspect ratio as the progress bar. In the case of a circle, the aspect ratio of the container should be 1:1 because the width will be equal to the height. In the case of a semicircle, the aspect ratio of the container should be 2:1 because the width will be double the height. Similarly, in the case of a simple line, the container should have an aspect ratio of 100:strokeWidth for the line.

When creating progress bars with a line, circle, or semicircle, you can simply use the ProgressBar.Shape() method to create the progress bar. In this case, the Shape can be a Circle, Line, or SemiCircle. You can pass two parameters to the Shape() method. The first parameter is a selector or DOM node to identify the container of the progress bar. The second parameter is an object with key-value pairs which determine the appearance of the progress bar.

You can specify the color of the progress bar using the color property. Any progress bar that you create will have a dark gray color by default. The thickness of the progress bar can be specified using the strokeWidth property. You should keep in mind that the width here is not in pixels but in terms of a percentage of the canvas size. For instance, if the canvas is 200px wide, a strokeWidth value of 5 will create a line which is 10px thick.

Besides the main progress bar, the library also allows you to draw a trailing line which will show readers the path on which the progress bar will move. The color of the trail line can be specified using the trailColor property, and its width can be specified using the trailWidth property. Just like strokeWidth, the trailWidth property also computes the width in percentage terms.

The total time taken by the progress bar to go from its initial state to its final state can be specified using the duration property. By default, a progress bar will complete its animation in 800 milliseconds.

You can use the easing property to specify how a progress bar should move during the animation. All progress bars will move with a linear speed by default. To make the animation more appealing, you can set this value to something else like easeIn, easeOut, easeInOut, or bounce.

After specifying the initial parameter values, you can animate the progress bars using the animate() method. This parameter accepts three parameters. The first parameter is the amount up to which you want to animate the progress line. The two other parameters are optional. The second parameter can be used to override any animation property values that you set during initialization. The third parameter is a callback function to do something else once the animation ends.

In the following example, I have created three different progress bars using all the properties we have discussed so far.

Animating Text Values With the Progress Bar

The only thing that changes with the animation of the progress bars in the above example is their length. However, ProgressBar.js also allows you to change other physical attributes like the width and color of the stroking line. In such cases, you will have to specify the initial values for the progress bar inside the from parameter and the final values inside the to parameter when initializing the progress bars.

You can also tell the library to create an accompanying text element with the progress bar to show some textual information to your users. The text can be anything from a static value to a numerical value indicating the progress of the animation. The text parameter will accept an object as its value. 

This object can have a value parameter to specify the initial text to be shown inside the element. You can also provide a class name to be added to the text element using the className parameter. If you want to apply some inline styles to the text element, you can specify them all as a value of the style parameter. All the default styles can be removed by setting the value of style to null. It is important to remember that the default values only apply if you have not set a custom value for any CSS property inside style.

The value inside the text element will stay the same during the whole animation if you don't update it yourself. Luckily, ProgressBar.js also provides a step parameter which can be used to define a function to be called with each animation step. Since this function will be called multiple times each second, you need to be careful with its use and keep the calculations inside it simple.

Creating Progress Bars With Custom Shapes

Sometimes, you might want to create progress bars with different shapes that match the overall theme of your website. ProgressBar.js allows you to create progress bars with custom shapes using the Path() method. This method works like Shape() but provides fewer parameters to customize the progress bar animation. You can still provide a duration and easing value for the animation. If you want to animate the color and width of the stroke used for drawing the custom path, you can do so inside the from and to parameters.

The library does not provide any way to draw a trail for the custom path, as it did for simple lines and circles. However, you can create the trail yourself fairly easily. In the following example, I have created a triangular progress bar using the Path() method.

Before writing the JavaScript code, we will have to define our custom SVG path in HTML. Here is the code I used to create a simple triangle:

You might have noticed that I created two different path elements. The first path has a light gray color which acts like the trail we saw with simple progress bars in the previous section. The second path is the one that we animate with our code. We have given it an id which is used to identify it in the JavaScript code below.

Final Thoughts

As you saw in this tutorial, ProgressBar.js allows you to easily create different kinds of progress bars with ease. It also gives you the option to animate different attributes of the progress bar like its width and color. 

Not only that, but you can also use this library to change the value of an accompanying text element in order to show the progress in textual form. This tutorial covers everything that you need to know to create simple progress bars. However, you can go through the documentation to learn more about the library.

If there is anything that you would like me to clarify in this tutorial, feel free to let me know in the comments.

How to Build Complex, Large-Scale Vue.js Apps With Vuex

$
0
0

It's so easy to learn and use Vue.js that anyone can build a simple application with that framework. Even novices, with the help of Vue's documentation, can do the job. However, when complexity comes into play the things get a bit more serious. The truth is that multiple, deeply nested components with shared state can quickly turn your application into an unmaintainable mess.

The main problem in a complex application is how to manage the state between components without writing spaghetti code or producing side effects. In this tutorial you'll learn how to solve that problem by using Vuex: a state management library for building complex Vue.js applications.

What is Vuex?

Vuex is a state management library specifically tuned for building complex, large-scale Vue.js applications. It uses a global, centralized store for all the components in an application taking advantage of its reactivity system for instant updates.

The Vuex store is designed in such a way that it is not possible to change its state from any component. This ensures that the state can only be mutated in a predictable manner. Thus your store becomes a single source of truth: every data element is only stored once and is read-only to prevent the application's components from corrupting the state that is accessed by other components.

Why Do You Need Vuex?

You may ask: Why I need Vuex at first place? Can I just put the shared state in a regular JavaScript file and import it in my Vue.js application?

You can, of course, but compared to a plain global object Vuex store has some significant advantages and benefits:

  • The Vuex store is reactive. Once components retrieve a state from it, they will reactively update their views every time the state changes.
  • Components cannot directly mutate the store's state. The only way to change the store's state is by explicitly committing mutations. This ensures every state change leaves a trackable record which makes the application easier to debug and test.
  • You can easily debug your application thanks to the Vuex integration with Vue's DevTools extension.
  • The Vuex store gives you a bird's eye view on how everything is connected and affected in your application.
  • It's easier to maintain and synchronize the state between multiple components, even if component hierarchy changes.
  • Vuex makes direct cross-components communication possible.
  • If some component is destroyed, the state in Vuex store will remain intact.

Getting Started With Vuex

Before we get started I want to make clear several things: First, to follow along this tutorial you need to have a good understanding of Vue.js and its components system, or at least minimal experience with the framework. 

Also, the aim of this tutorial is not to show you how to build actual complex application; the aim is to focus your attention more on Vuex concepts and how you can use it to build complex applications. For that reason, I'm going to use very plain and simple examples without any redundant code. Once you fully grasp the Vuex concepts you will be able to apply them on any level of complexity.

Finally, I'll be using ES2015 syntax. If you are not familiar with it, you can learn it here.

And now, let's get started!

Setting Up a Vuex Project

The first step to get started with Vuex is to have Vue.js and Vuex installed on your machine. There are several ways to do that but we'll use the easiest one. Just create an HTML file and put the needed CDN links:

I use some CSS to make the components look nicer, but you don't need to worry about that CSS code. It only helps you to gain a visual notion about what is going on. Just copy and paste the following inside the <head> tag:

Now, let's create some components to work with. Inside the <script> tag, right above the closing </body> tag, put the following Vue code:

Here, we have a Vue instance, a parent component, and two child components. Each component have a heading "Score:" where we'll output the app state.

The last thing you need to do is to put a wrapping <div> with id="app" right after the opening <body>, and then place the parent component inside:

So, the preparation work is done. We're ready to move on.

Exploring Vuex

State Management

In real life we deal with complexity by using strategies to organize and structure the content we want to use. We group related things together in different sections, categories, etc. Just as how in a book library, the books are categorized and put in different sections so that we can easily find what we are looking for. The same is true for Vuex. It arranges the application data and logic related to state in four groups or categories: state, getters, mutations, and actions.

State and mutations are the base for any Vuex store:

  • state is an object that holds the state of the application data.
  • mutations is also an object containing methods which affect the state.

Getters and actions are like logical projections of state and mutations:

  • getters contains methods used to abstract the access to the state, and to do some preprocessing jobs, if needed (data calculating, filtering, etc.)
  • actions are methods used to trigger mutations and execute asynchronous code.

Let's explore the following diagram to make the things a bit clear:

Vuex State Management Workflow Diagram

In the left side, we have an example of Vuex store, which we'll create later on in this tutorial. In the right side, we have a Vuex workflow diagram, which shows how the different Vuex elements work together and communicate each another.

In order to change the state, a particular Vue component must commit mutations (eg. this.$store.commit('increment', 3)), and then, those mutations change the state (score becomes 3). After that, the getters are automatically updated thanks to Vue's reactive system and they render the updates in the component's view (with this.$store.getters.score). 

Mutations cannot execute asynchronous code, because this would make it impossible to record and track the changes in debug tools like Vue DevTools. To use asynchronous logic you need to put it in actions. In this case a component first will dispatch actions (this.$store.dispatch('incrementScore', 3000)) where the asynchronous code is executed, and then those actions will commit mutations, which will mutate the state. 

Create a Vuex Store Skeleton

After we explored how Vuex work, let's create the skeleton for our Vuex store. Put the following code above the ChildB component registration:

To provide global access to the Vuex store from every component we need to add the store property in the Vue instance:

Now, we can access the store from every component with this.$store variable.

So far, if you open the project with CodePen in the browser, you should see the following result.

App Skeleton

State Properties

The state object contains all of the shared data in your application. Of course, if needed, each component can have its own private state too.

Imagine that you want to build a game application and you need a variable to store the game's score. So, you put it in the state object:

Now, you can access the state's score directly. Let's go back to the components and reuse the data from the store. In order to be able to reuse reactive data from the store's state, you should use computed properties. So, let's create a score() computed property in the parent component:

In parent component's template put the {{ score }} expression:

And now, do the same for the two child components.

Vuex is so smart that it will do all the work for us to reactively updates the score property whenever the state changes. Try to change the score's value and see how the result updates in all of the three components.

Creating Getters

It is, of course, good that you can reuse the this.$store.state keyword inside the components, as you saw above. But imagine the following scenarios:

  1. In a large-scale application, where multiple components access the state of the store by using this.$store.state.score, you decide to change the name of score. This means that you have to change the name of the variable inside each and every component that uses it! 
  2. You want to use a computed value of the state. For example, let's say you want to give the players a bonus of 10 points when the score reaches 100 points. So, when the score hits 100 points, 10 points bonus are added. This means each component has to contain a function that reuses the score and increment it with ten. You will have repeated code in each component, which is not good at all!

Fortunately, Vuex offers a working solution to handle such situations. Imagine the centralized getter that accesses the store's state and provides a getter function to each of the state's items. If needed, this getter can apply some computation to the state's item. And if you need to change the name of some of the state's properties, you only change them in one place, in this getter. 

Let's create a score() getter:

A getter receives the state as its first argument, and then uses it to access the state's properties.

Note: Getters also receive getters as the second argument. You can use it to access the other getters in the store.

In all components, modify the score() computed property to use the score() getter instead of state's score directly.

Now, if you decide to change the score to result you need to update it only in one place: in the score() getter. Try it out in this CodePen!

Creating Mutations

Mutations are the only way allowed to change the state. Triggering changes simply means committing mutations in component methods.

A mutation is pretty much an event handler function that is defined by name. Mutation handler functions receive a state as a first argument. You can pass an additional second argument too, which is called the payload for the mutation. 

Let's create a increment() mutation:

Mutations cannot be called directly! To perform a mutation, you should call the commit() method with a name of the corresponding mutation and possible additional parameters. It might be just one, as is the step in our case, or they might be multiple wrapped in an object.

Let's use the increment() mutation in the two child components by creating a method named changeScore():

We are committing a mutation instead of changing this.$store.state.score directly, because we want to explicitly track the change made by the mutation. This way we make our application logic more transparent, traceable and easy to reason about. In addition, it makes it possible to implement tools, like Vue DevTools or Vuetron, that can log all mutations, take state snapshots, and perform time-travel debugging.

Now, let's put the changeScore() method into use. In each template of the two child components, create a button and add a click event listener to it:

When you click the button, the state will be incremented by three, and this change will be reflected in all components. Now we have effectively achieved direct cross-components communication, which is not possible with the Vue.js built-in "props down, events up" mechanism. Check it out in our CodePen example.

Creating Actions

An action is just a function that commit a mutation. It changes the state indirectly which allows for executing of asynchronous operations. 

Let's create a incrementScore() action:

Actions get the context as first parameter, which contains all methods and properties from the store. Usually we just extract the parts we need by using ES2015 argument destructing. The commit method is one we need very often. Actions also get a second payload argument, just like mutations.

In the ChildB component modify the changeScore() method:

To call an action we use dispatch() method with a name of the corresponding action and additional parameters just as with mutations.

Now, the "Change Score" button from ChildA component will increment the score by three. The identical button from ChildB component will do the same, but after 3 seconds delay. In the first case we execute synchronous code and we use a mutation, but in the second case we execute asynchronous code and we need to use an action instead. See how it all works in our CodePen example.

Vuex Mapping Helpers

Vuex offers some useful helpers which can streamline the process of creating state, getters, mutations, and actions. Instead of writing those functions manually we can tell Vuex to create them for us. Let's see how it works.

Instead of writing the score() computed property like this:

We just use the mapState() helper like this:

And the score() property is created automatically for us.

The same is true for the getters, mutations, and actions. 

To create the score() getter we use mapGetters() helper:

To create changeScore() method we use mapMutations() helper like this:

When used for mutations and actions with payload argument, we must pass that argument in the template where we define the event handler:

If we want changeScore() to use an action instead of a mutation we use mapActions() like this:

Again, we must define the delay in the event handler:

Note: All mapping helpers return an object. So, if we want to use them in combination with other local computed properties or methods we need to merge them into one object. Fortunately with the object spread operator (...)  we can do it without using any utility. 

In our CodePen you can see an example of how all mapping helpers are used in practice.

Making the Store More Modular

It seems that the problem with complexity constantly obstructs our way. We solved it before by creating Vuex store, where we made the state management and components communication easy. In that store we have everything in one place, easy to manipulate and easy to reason about. However, as our application grows this easy to manage store file becomes larger and larger, and, as a result, harder to maintain. Again, we need some strategies and techniques for improving the application structure by returning it to its easy to maintain form. In this section, we'll explore several techniques which can help us in this undertaking.

Using Vuex Modules

Vuex allows us to split the store object into separate modules. Each module can contain its own state, mutations, actions, getters, and other nested modules. After we create the needed modules, we register them in the store.

Let's see it in action:

In the above example, we created two modules, one for each child component. The modules are just plain objects, which we register as scoreBoard and resultBoard in the modules object inside the store. The code for childA is the same as that in the store from the previous examples. In the code for childB we add some changes in values and names.

Let's now tweak ChildB component to reflect the changes in the resultBoard module. 

In ChildA component the only thing we need to modify is the changeScore() method:

As you can see, splitting the store into modules makes it much more lightweight and maintainable, while still keeps its great functionality. Check out the updated CodePen to see it in action.

Namespaced Modules

If you want or need to use one and the same name for particular property or method in your modules, then you should consider namespacing them. Otherwise you may observe some strange side effects, such as executing all the actions with same names, or getting the wrong state's values. 

To namespace a Vuex module you just set the namespaced property to true.

In the above example we made the property and method names the same for the two modules. And now we can use a property or method prefixed with the name of the module. For example, if we want to use the score() getter from the resultBoard module, we type it like this: resultBoard/score. If we want the score() getter from the scoreBoard module, then we type it like this: scoreBoard/score

Let's now modify our components to reflect the changes we made. 

As you can see in our CodePen example, we can now use the method or property we want and get the result we expect.

Splitting the Vuex Store Into Separate Files

In the previous section, we improved the application structure to some extent by separating the store into modules. We made the store cleaner and more organized, but still all of the store code and its modules lie in one and the same big file. 

So the next logical step is to split the Vuex store in separate files. The idea is to have an individual file for the store itself and one for each of its objects, including the modules. This means having separate files for the state, getters, mutations, actions, and for each individual module (store.jsstate.js, getters.js, etc.) You can see an example of this structure at the end of the next section.

Using Vue Single File Components

We've made the Vuex store as modular as we can. The next thing we can do is to apply the same strategy to the Vue.js components too. We can put each component in a single, self-contained file with a .vue extension. To learn how this works you can visit the Vue Single File Components documentation page

So, in our case, we'll have three files: Parent.vueChildA.vue, and ChildB.vue

Finally, if we combine all three techniques we'll end up with the following or similar structure:

In our tutorial GitHub repo you can see the completed project with the above structure.

Recap

Let's recap some main points you need to remember about Vuex:

Vuex is a state management library, which help us to build complex, large-scale applications. It uses a global, centralized store for all the components in an application. To abstract the state we use getters. Getters are pretty much like computed properties and are ideal solution when we need to filter or calculate something on runtime.

Vuex store is reactive and components cannot directly mutate the store's state. The only way to mutate the state is by commiting mutations, which are synchronous transactions. Each mutation should perform only one action, must be as simple as possible, and only responsible for updating just a piece of state.

Asynchronous logic should be encapsulated in actions. Each action can commit one or more mutations, and one mutation can be committed by more than one action. Actions can be complex but they never change the state directly.

Finally, modularity is the key to maintainability. To deal with complexity and make our code modular we use the "divide and conquer" principle and the code splitting technique.

Conclusion

So folks, that's it. You already know the main concepts behind Vuex and you are ready to start applying them in practice.  

For the sake of brevity and simplicity, I omitted intentionally some details and features of Vuex, so you'll need to read the full Vuex documentation to learn everything about Vuex and its feature set.

20 Useful Laravel Packages Available on CodeCanyon

$
0
0

Laravel is web application framework that many developers say is a dream to work with. That’s because it aims to take the tedium out of routine web projects tasks, like authentication, routing, sessions, and caching and make the development process simple and straightforward without sacrificing application functionality.

If you’re not familiar with the Laravel framework, then it’s time to discover what you’ve been missing by checking out these 20 popular Laravel tools and packages to be found at CodeCanyon.

1. Ninja Media Script

Ninja Media Script allows you to create your own media sharing site. It is easy to install and fully customisable so that you can use your own logo and preferred colour scheme. Users can sign up with Facebook, Google or email and upload an unlimited number of videos, GIFs, photographs, drawings, etc. 

Ninja Media Script

Key features:

  • easy-to-use Admin Panel
  • supports YouTube, Vimeo and Vine
  • multiple layouts available
  • and more 

User 68mustang says: 

“Great script. A lot of amazing functionalities.”

2. Buzzy

Buzzy is another Laravel package option for those who want to create their own media sharing sites. It offers users unlimited widgets, pages, categories and the ability to create featured posts, lists, polls, videos and more.  All media can be tracked daily, weekly, or monthly so that the site admin knows what is most popular and interesting to visitors. 

Buzzy

Key features: 

  • customisable layouts
  • a back-end administration panel
  • integration with various social media channels
  • and more

User Phalon says:

“This script is truly amazing. Professionally Coded and looked after well.”

3. Schoex

If you run a school or your own private classes Schoex is a powerful school management system that can help you get and stay organised. Schoex allows users to organise students by academic year or any other category, and helps manage class schedules, attendance, vacation and homework assignments, as well as online exams, mark sheets and reports. Once set up, the systems administrator can assign roles to teachers, students and parents so that they can access relevant areas of the system and keep updated with news and events. 

Schoex

Key features:

  • control information access based on user roles
  • manage class schedules, exams, etc
  • upload and share images, videos, news and events
  • and more

User debojyotidas says:

“This template has the best support, hands down! The developer is very helpful and has handled every bit of small or medium problem I had with the script.”

4. Acelle

A self-hosted email marketing web application written in Laravel 5, Acelle allows users to send a high-volume of marketing emails via their own server or through other email service providers. This means that users have full control of their entire email marketing system and can replace costly email marketing services like Mailchimp. 

Acelle

Key features:

  • manage list and subscribers 
  • integration with your own SMTP server
  • fully featured automation and autoresponder
  • and more

User jab1000 says:

“Acelle Email Marketing has allowed us to ditch our previous Mailchimp campaigns (and high monthly fees) while still delivering the same results and giving us far more features! Really excited about this!”

5. Josh

Josh is a user-friendly Laravel admin template that has every component necessary for making beautiful backend applications.  The template comes with more than 100 pages but if you need only a few pages for your application, the template includes a handy starter kit which includes the most necessary pages like login, register, forgot password and user management. If you require additional pages beyond those provided in the starter kit, you can easily get them from the main version of Josh.  

Josh

Key features:

  • backend  and frontend pages with master layouts
  • login, register functionality
  • blog module with comments
  • and more

User daveke7 says:

“I got great help with my problems. The creator really took his time to solve the issues I had. I highly advise buying this Admin panel.”

6. Vanguard 

Vanguard is a login and user management app that allows website owners to quickly add and enable user authentication and authorisation features to their website. It provides an easy-to-use interactive dashboard, a powerful admin panel and an unlimited number of user roles. It also comes with fully documented JSON API which allows you to easily authenticate users using your favourite mobile device.

Vanguard

Key features:

  • secure user registration and login
  • social authentication using Facebook, Twitter and Google+
  • password reset
  • Google reCAPTCHA on registration
  • and more

User Apiening says:

“Very nice package to get authentication and permission system up and running. Saves tons of work compared to custom implementation.”

7. Classic Invoicer

A web-based invoicing and client management system, Classic Invoicer allows users to create custom invoices and send them to clients directly. It also produced detailed reports which are useful in managing and tracking income. 

Classic Invoicer

Key features: 

  • responsive design 
  • stores client information for each invoice
  • handles estimates within the app
  • manages various payment types
  • and more

User Philomenas says: 

“Great features, probably wont use them all. The customer support is fast, friendly and they will make it work for you whatever problems you have.”

8. BeDrive

Looking to create your own version of Dropbox or Google Drive, then check out BeDrive. This Laravel package allows you to create your own self-hosted file sharing and hosting website in minutes with no coding knowledge.

BeDrive

Key features:

  • intuitive dashboard
  • configurable and easy to use subscriptions system
  • admin panel
  • Google analytics integrated
  • and more

User King123456 says:

This is the best file hosting script that i have ever used. Great design and great features. I definitely recommend people to buy this.

9. HelloVideo

Want to create your own video website? HelloVideo is a PHP script built with the Laravel framework that you install on your server. You can then customise it, add unlimited videos, posts, and pages to your site and make them available for free or only to subscribers.

HelloVideo

Key features:

  • add unlimited YouTube, Vimeo and other media files
  • organise all your content into categories and menus
  • view live stats and analytics about users
  • seamlessly integrates with Stripe
  • and more

User vegatow says:

“Love this code. It's exactly what I am looking for. Great Job!”

10. Chandra

One of our best-rated Laravel packages, Chandra may be just what you need if you’re looking for the perfect admin back-end application for your site. 

Chandra

Key features:

  • six colour schemes
  • different layout options
  • over forty pages included
  • multi-level menu
  • and more

11. GamePort

With video games ever growing in popularity, creating a site dedicated specifically to selling, buying and trading video games is simply genius and if you’re looking to create such a site, GamePort is a great choice. 

GamePort

Key features:

  • create trade lists 
  • powerful search and add function
  • support for over 15 platforms and digital distributors
  • social login 
  • and more

User mafikes says:

“Quality code and no bugs. Customer Support is really perfect! I can recommend it."

12. SmartEnd

SmartEnd provides developers with an admin dashboard containing all the options needed to build any type of website. It contains front-end site preview with a flexible RESTful API and uses open source code that is easy to update. 

SmartEnd

Key features:

  • dashboard with 4 different colours and styles
  • responsive admin panel
  • responsive Bootstrap flat design
  • dynamic menus and pages
  • and more

User abeaventh says:

“A nice, clean step-by-step guide to customise things. Documentation, design, features, flexibility and code quality are top notch.”

13. Fundme

Fundme is a crowdfunding platform that can be used to raise funds for any cause. The administrator adds users who can each create unlimited campaigns to support their causes.

Fundme

Key features:

  • members can create unlimited campaigns 
  • social sharing
  • option to delete account
  • PayPal integrated
  • and more

User reliablewebhosting says:

“This script is powerful. I like the fact that the installation documentation was direct and to the point. It takes just a few minutes to install. Most developers will sell a similar crowdfunding script for thousands of dollars. Thanks for a great software - I love it.”

14. Smile Media

Going viral on the internet, is today’s holy grail as more eyeballs on a page can raise the profile of an entire site or business and generate more revenue. With this in mind,  Smile Media bills itself as the package that helps promote content for going viral by providing a solid platform from which you and your users can share media throughout your various social media channels. 

Smile Media

Key features:

  • responsive design
  • Amazon S3 support
  • builtin analytics
  • and more

User Gkhngyk says:

"This theme is so cool.”

15. Filepicker

A file-uploader script that allows users to upload multiple files to a server easily and quickly, Filepicker also includes three plugins for pagination, taking pictures with the webcam and image cropping. It also makes use of the Intervention Image library allowing for advanced image editing options. 

Filepicker

Key features:

  • multi-file upload
  • file list display
  • Webcam plugin
  • multiple image versions
  • and more

User warrio4 says:

“Amazing plugin. Simple but yet complex and efficient. Just what you'd need.”

16. Socialite

Create your own social networking site with Socialite, a social networking script developed on Laravel which lets you create a website to suit your needs and tastes that makes it easier for clients, friends and fans to follow your updates.

Socialite

Key features:

  • login with major social networks
  • realtime notification
  • unified search
  • multilevel comments
  • and more

User ferithon says:

Very good code. Fantastics features. Competent, available and professional staff; Highly recommended!

17. Botble

Botble is a Laravel content management system that allows you to create, modify and manage any kind of digital content you want. The system accommodates multilingual admin back-end, has two readymade themes that can be modified as you like and has many great features like a gorgeous photo gallery, and integrated Google Analytics.

Botble

Key features:

  • theme and widget management
  • powerful permission system
  • social login
  • blog and news theme included
  • and more

User martinbeek says

"This is a great product for a very reasonable price. The best in it’s category in my opinion. Thoroughly coded and feature packed. This author has given me the best support to date. Fast response, always polite and helpful and can be reached through Skype."

18. Booksi

An ideal system for property managers, Booksi is a rental and directory management system that allows owners of rental or vacation properties to advertise their properties, approve or reject offers, and more. It also allows users to view available properties, reserve them and leave reviews on a property they’ve stayed in.

Booksi

Key features:

  • powerful admin panel
  • booking and reviews
  • ability to change design and colours
  • payment settings
  • and more

User christhoo says:

“This developer has done such a wonderful job with his script. His response is almost immediate and he is very patient and detailed when it comes to supporting me in all my enquiries! His work is highly recommended indeed!”

19. Laraship Subscriptions

Subscription are a very popular way of offering online goods and services today and Laraship Subscriptions is a great recurring billing platform that will help you manage your subscriptions. It can support multiple products with different subscriptions for each, offers Stripe integration, allows you to send out invoices and users to subscribe, cancel or upgrade subscriptions.

Laraship Subscriptions

Key features:

  • automatic remote updates for modules
  • theme management
  • custom fields
  • encrypted URLs and SSL tested to ensure security
  • and more

User mattltm says:

“An excellent package with great support. Clean code, great features and easy enough to understand and build a custom application around. Regular updates are great and the author even helped sort out a few issues I had by remote access. Very happy.”

20. Themeqx Classified

Themeqx Classified is a Laravel classified ads content management system with many powerful features like a built-in social login, Amazon S3, SEO, and a free blog with multi-language support. Users can add YouTube video or Vimeo video to every ad to help attract more customers.

Themeqx Classified

Key features:

  • easy setup wizard
  • regular and premium ads available
  • ability to monetise
  • PayPal and Stripe supported
  • and more

User PremierDigitalMarketing says:

"Outstanding script! I am really impressed with it and the support was fantastic in helping me resolve an issue with my server (which wasn't even their fault). Highly recommended. I will keep an eye out for your future releases."

Conclusion

Over the years Laravel has grown from a budding PHP framework into something that's used across the industry as a solid foundation for building PHP-based web applications. 

The 20 Laravel packages featured here just scratch the surface of options available at CodeCanyon that aid developers in building mature, robust solutions for their clients. So if none of them catch your fancy, there are plenty of other great options there to hold your interest.

And if you want to improve your skills using Laravel yourself,  head on over to the site and check out the ever so useful Laravel tutorials and Laravel courses we have on offer.

Viewing all 4704 articles
Browse latest View live