Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all 1836 articles
Browse latest View live

Get Wear OS and Android Talking: Exchanging Information via the Wearable Data Layer

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-30986

When it comes to performing quick, simple tasks, wearable apps have the advantage, as a smartwatch that’s right there on your wrist is always going to be more accessible than a smartphone or tablet that’s floating around somewhere in your bag.

But there’s no such thing as the perfect gadget, and no-one’s raving about their smartwatch’s battery life or claiming that it’s every bit as quick and powerful as their smartphone or tablet.

To deliver the best possible user experience, you need to play to a device’s strengths. If you’re developing for Wear OS (the operating-system-formerly-known-as-Android-Wear), then you’re in a unique position to cherry-pick the best features from two very different devices.

Basically, you can have the best of both worlds!

In this article, I’ll show you how to make the most out of everything Android OS and Wear OS have to offer, by opening a channel of communication between the two. Once your handheld app and its wearable counterpart are chatting, you can delegate tasks based on the device it’s best suited for—whether that’s offloading battery-intensive tasks to the handheld, or making sure your app’s most important information is always easily accessible by displaying it on the user’s wrist.

By the end of this article, you’ll have created a handheld and a wearable application that can exchange information via the Wearable Data Layer and the MessageClient API.

What Is the Wearable Data Layer?

The Wearable Data Layer provides access to various client classes that you can use to store and retrieve data, without having to get your hands dirty with technical details such as data serialization. Once this information is on the Data Layer, it’s accessible to both the handheld and the wearable device.

In this article, we’ll be focusing on the MessageClient API, which is a one-way communication mechanism that you can use to send information to the Wearable Data Layer. This API is particularly handy for executing remote procedure calls (RPC), such as launching an Activity remotely on the paired handheld or wearable device.

Let’s look at an example: imagine you’ve created a navigation app. This app needs to a) retrieve location updates, and b) give the user directions.

Monitoring the device’s location is an intensive task that can quickly drain the limited battery available to your typical wearable. Using the MessageClient API, your wearable app can instruct its handheld counterpart to perform this work instead. Once the handheld has performed this heavy lifting, it can send the resulting information back to the wearable via the Data Layer, so your app gets the information it needs without taking a chunk out of the wearable’s remaining battery.

As a general rule, if your wearable app needs to perform a task that requires significant battery or processing power, or complex user interactions, then you should consider offloading this work to the corresponding handheld app. By contrast, if your app deals with particularly time-sensitive information, or content that the user is likely to access on the go, then you should display this information on the wearable app. 

In our navigation app example, pushing each set of directions from the handheld to the wearable makes this information more easily accessible, especially for someone who’s out and about, and hopelessly lost!

Out of the box, the MessageClient API is a one-way communication mechanism, but you can implement bidirectional messaging by creating a sender and a receiver in both your project’s handheld and wearable module—which is exactly what we’re going to do.

Creating a Wearable and a Handheld Module

In this article, we’re going to create a wearable app that’ll recognise when its handheld counterpart sends a new message to the Data Layer. This wearable app will then respond by retrieving this message and displaying it as part of its UI.

Then, we’ll rinse and repeat, creating a handheld app that monitors the Data Layer for messages sent from its wearable counterpart.

Information sent via the MessageClient API is only accessible to the application that created it. If the system is going to identify your wearable and handheld as belonging to the same application, then they’ll need to have the same package name, version code, and signing certificate. The easiest way to tick all these boxes is to create a project that consists of both a wearable and a handheld module:

  • Create a new project called DataLayer.
  • On the Target Android Device screen, select Phone and Tablet and Wear. Click Next.
  • For your phone and tablet module, select the Empty Activity template, and then click Next.
  • For your wearable module, select the Blank Wear Activity template, and then click Next, followed by Finish.

Creating Your Handheld App

Since we’re implementing bidirectional communication, both our handheld and our mobile modules need their own listener and sender. Let’s start by implementing this functionality in our handheld application.

I’m going to keep things simple and create a UI consisting of a TextView that’ll display the various messages retrieved from the Data Layer and a button that, when tapped, will send its own message to the Data Layer.  

Open your mobile module’s activity_main.xml file, and add the following:

Since we referenced a few dimens.xml values, we need to provide definitions for these values:

  • Control-click the mobile module’s res/values directory.
  • Select New > Values resource file.
  • Name this file dimens.xml and then click OK.
  • Add the following:

This gives us the following user interface:

Create the user interface for your projects handheld component

Add Your Dependencies

Open the mobile module’s build.gradle file and add the following dependencies:

Displaying and Sending Messages in MainActivity

In MainActivity, we need to perform the following:

  1. Keep the user in the loop!

When the user taps the Talk to the Wearable button, two things need to happen:

  • The handheld sends a message to the wearable. I’m going to use "I received a message from the handheld."
  • The handheld provides visual confirmation that the message has been sent successfully. I’m going to use "I sent a message to the wearable."

When the user taps the handheld’s Talk to the Wearable button, the handheld will attempt to send a message to the Data Layer. The system only considers this message successfully sent once it’s queued for delivery to a specific device, which means at least one paired device needs to be available.

In the best case scenario, the user taps Talk to the Wearable, the message gets queued for delivery, and our handheld triumphantly declares that: "I just sent a message to the wearable."

However, if no wearable devices are available then the message isn’t queued, and by default the user gets no confirmation that our app has even tried to send a message. This could lead the user to wonder whether the app is broken, so I’m also going to display a Sending message…. notification, regardless of whether the message is successfully queued or not.

When testing this app, you may also want to trigger multiple messages in quick succession. To make it clear when each message has been queued for delivery, I’m adding a counter to each message, so our handheld will display I just sent a message to the wearable 2, I just sent a message to the wearable 3, and so on. On the other side of the connection, our wearable will display I just received a message from the handheld 2, I just received a message from the handheld 3, and so on.

2. Display received messages

In the next section, we’ll be creating a MessageService that monitors the Data Layer and retrieves messages. Since our service will be performing its work on a different thread, it’ll broadcast this information to our MainActivity, which will then be responsible for updating the UI.

3. Define the path

Every message you transmit via the MessageClient API must contain a path, which is a string that uniquely identifies the message and allows your app to access it from the other side of the connection.

This path always starts with a forward slash (I’m using /my_path) and can also contain an optional payload, in the form of a byte array.

4. Check your nodes!

In Google Play services 7.3.0 and higher, you can connect multiple wearables to a single handheld device—for example, a user might splash out on multiple wearables that they switch between or use simultaneously. A Wear OS device may also be connected to multiple handheld devices during its lifetime, for example if the user owns an Android smartphone and a tablet, or they replace their old smartphone with a shiny new one. Note that any device that's capable of connecting to the Data Layer is referred to as a node in the application code.

In this article, I’m going to assume there will only ever be a single available wearable. Alternatively, you can get selective about which devices you send messages to, using GetConnectedNodes or getLocalNode.

Let’s implement all this in our MainActivity:

Create a Listening Service

At this point, our handheld is capable of pushing messages to the Data Layer, but since we want to implement bidirectional communication, it also needs to listen for messages arriving on the Data Layer.

In this section, we’re going to create a service that performs the following:

  1. Monitor the Data Layer for events

You can monitor the Data Layer either by implementing the DataClient.OnDataChangedListener interface or by extending WearableListenerService. I’m opting for the latter, as there are a few benefits to extending WearableListenerService. Firstly, WearableListenerService does its work on a background thread, so you don’t have to worry about blocking the main UI thread. Secondly, the system manages the WearableListenerService lifecycle to ensure it doesn’t consume unnecessary resources, binding and unbinding the service as required.

The drawback is that WearableListenerService will listen for events even when your application isn’t running, and it will launch your app if it detects a relevant event. If your app only needs to respond to events when it’s already running, then WearableListenerService can drain the device’s battery unnecessarily.

2. Override the relevant data callbacks

WearableListenerService can listen for a range of Data Layer events, so you’ll need to override the data event callback methods for the events you’re interested in handling. In our service, I’m implementing onMessageReceived, which will be triggered when a message is sent from the remote node.

3. Check the path

Every time a message is sent to the Data Layer, our app needs to check whether it has the correct my_path identifier.

4. Broadcast messages to MainActivity

Since WearableListenerService runs on a different thread, it can’t update the UI directly. To display a message in our application, we need to forward it to MainActivity, using a LocalBroadcastManager.

To create the service:

  • Make sure you have the mobile module selected.
  • Select New > Service from the Android Studio toolbar.
  • Name this service MessageService.
  • Add the following:

Finally, open the Manifest and add some information to the MessageService entry:

As already mentioned, the system only considers a message successfully sent once it’s queued for delivery, which can only occur if one or more wearable devices are available.

You can see this in action by installing the mobile module on a compatible smartphone or tablet, or an Android Virtual Device (AVD). Click the Talk to the Wearable button and the app will display the Sending message… text only. The I just sent the wearable… text won't make an appearance. 

If our message is ever going to be queued for delivery, then we need to implement another set of sender and receiver components in our project’s wearable module.

Creating Your Wearable App

Our wearable app is going to have similar functionality as its handheld counterpart, so I’ll be skipping over all the code that we’ve already covered.

Once again, let’s start by creating the app’s user interface. Open the wear module’s activity_main.xml file and add the following:

At this point, your user interface should look something like this:

Create the UI for your Android projects Wear OS module

Open your build.gradle and add the following dependencies:

Now, we need to send our message to the Data Layer:

Next, we need to create a listener that’ll monitor the Data Layer for incoming messages and notify MainActivity whenever a new message is received:

  • Make sure the wear module is selected.
  • Choose New > Service from the Android Studio toolbar.
  • Name this service MessageService and then add the following:

Open the module’s Manifest, and create an intent filter for the WearableListenerService:

You can download the complete project from GitHub.

Testing Your App

At this point you have two apps that can exchange messages over the Data Layer, but if you're going to put these communication skills to the test, you’ll need to install your project on a handheld and a wearable device.

If you’re an Android developer, then chances are you have at least one Android smartphone or tablet laying around, but wearables still feel like a relatively new and niche product, so you might not have invested in a smartwatch just yet.

If you do decide to pursue Wear OS development, then you should take the plunge and purchase a smartwatch at some point, as there’s no substitute for testing your app on a real Android device. However, if you’re just experimenting with Wear OS, then you can create an AVD that emulates a wearable, in exactly the same way you create an AVD that emulates a smartphone or tablet. You can then get your AVD and your physical Android device talking, using port forwarding.

The first step is to create a wearable AVD and install your wear module on this emulated device:

  • Select Tools > Android > AVD Manager from the Android Studio toolbar.
  • Click Create Virtual Device…
  • Select Wear from the left-hand menu.
  • Choose the wearable that you want to emulate, and then click Next.
  • Select your system image, and then click Next.
  • Give your AVD a name, and then click Finish.
  • Select Run > Run… from the Android Studio toolbar.
  • In the little popup that appears, select Wear…
  • Select the wearable AVD that you just created. After a few moments, the AVD will launch with your wearable component already installed.

Next, install the handheld module on your smartphone or tablet:

  • Connect your physical Android device to your development machine.
  • Select Run > Run… from the Android Studio toolbar.
  • Choose mobile when prompted.

Finally, we need to get our physical Android device and our AVD talking:

  • Make sure Bluetooth is enabled on your handheld (Settings > Bluetooth) and that it’s connected to your development machine via USB cable.
  • On your handheld device, open the Play Store and download the Wear OS by Google app (formerly Android Wear).
  • Launch the Wear OS application.
  • On your emulated wearable, click the Home button in the accompanying strip of buttons (where the cursor is positioned in the following screenshot) and then open the Settings app.

Testing your project by connecting your emulator and your Android smartphone or tablet

  • Select System > About and click the Build number repeatedly, until you see a You are now a developer message.
  • Return to the main Settings menu by clicking the Back button twice. You should notice a new Developer Options item; give it a click.
  • Select ADB Debugging.
  • On your development machine, open a new Command Prompt (Windows) or Terminal (Mac) and then change directory (cd) so it’s pointing at the Android SDK’s platform-tools folder. For example, my command looks like this:
  • Make sure ADB (Android Debug Bridge) is recognizing both the emulator and your attached smartphone or tablet, by running the /.adb devices command. It should return the codes for two separate devices.
  • Forward your AVD’s communication port to the attached smartphone or tablet, by running the following command in the Terminal/Command Prompt window:
  • On your handheld, launch the Wear OS app. Navigate through any introductory dialogues, until you reach the main Wear OS screen.
  • Open the dropdown in the upper-left corner and select Add a new watch.
  • Tap the dotted icon in the upper-right corner, and select Pair with emulator. After a few moments, the handheld should connect to your emulator.
Use the Wear OS app to pair your emulator with your Android smartphone or tablet

You’re now ready to test your app! Launch the Wear component on your emulator and the mobile component on your handheld, and experiment by tapping the different Talk... buttons.

When you tap Talk to the wearable on the handheld, the following messages should appear:

  • Handheld:“I just sent the handheld a message." 
  • Wearable: “I just received a message from the handheld.”
You can now exchange messages over the Data Layer using the MessageClient API

When you tap Talk to the handheld on the wearable, the following messages should appear:

  • Wearable:“I just sent the handheld a message."
  • Handheld:‘I just received a message from the wearable.”

Conclusion

In this article, we looked at how to exchange messages between your handheld and your wearable app, over the Wearable Data Layer. 

In production, you’d probably use this technique to do something more interesting than simply exchanging the same few lines of text! For example, if you developed an app that plays music on the user’s smartphone, you could give them the ability to play, pause, and skip songs directly from their wearable, by sending these instructions from the wearable to the handheld, over the Data Layer.

You can learn more about the Wearable Data Layer, including how to sync more complex data, over at the official Android docs.

2018-04-27T12:00:00.000Z2018-04-27T12:00:00.000ZJessica Thornsby

How to Use TensorFlow Mobile in Android Apps

$
0
0

With TensorFlow, one of the most popular machine learning frameworks available today, you can easily create and train deep models—also commonly referred to as deep feed-forward neural networks—that can solve a variety of complex problems, such as image classification, object detection, and natural language comprehension. TensorFlow Mobile is a library designed to help you leverage those models in your mobile apps.

In this tutorial, I'll show you how to use TensorFlow Mobile in Android Studio projects.

Prerequisites

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

  • Android Studio 3.0 or higher
  • TensorFlow 1.5.0 or higher
  • an Android device running API level 21 or higher
  • and a basic understanding of the TensorFlow framework

1. Creating a Model

Before we start using TensorFlow Mobile, we'll need a trained TensorFlow model. Let's create one now.

Our model is going to be very basic. It will behave like an XOR gate, taking two inputs, both of which can be either zero or one, and producing one output, which will be zero if both the inputs are identical and one otherwise. Additionally, because it's going to be a deep model, it will have two hidden layers, one with four neurons, and another with three neurons. You are free to change the number of hidden layers and the numbers of neurons they contain.

In order to keep this tutorial short, instead of using the low-level TensorFlow APIs directly, we'll be using TFLearn, a popular wrapper framework for TensorFlow offering more intuitive and concise APIs. If you don't have it already, use the following command to install it inside your TensorFlow virtual environment:

To start creating the model, create a Python script named create_model.py, preferably in an empty directory, and open it with your favorite text editor.

Inside the file, the first thing we need to do is import the TFLearn APIs.

Next, we must create the training data. For our simple model, there will be only four possible inputs and outputs, which will resemble the contents of the XOR gate's truth table.

It is usually a good idea to use random values picked from a uniform distribution while assigning initial weights to all the neurons in the hidden layers. To generate the values, use the uniform() method.

At this point, we can start creating the layers of our neural network. To create the input layer, we must use the input_data() method, which allows us to specify the number of inputs the network can accept. Once the input layer is ready, we can call the fully_connected() method multiple times to add more layers to the network.

Note that in the above code, we have given meaningful names to the input and output layers. Doing so is important because we'll need them while using the network from our Android app. Also note that the hidden and output layers are using the sigmoid activation function. You are free to experiment with other activation functions, such as softmaxtanh, and relu.

As the last layer of our network, we must create a regression layer using the regression() function, which expects a few hyper-parameters as its arguments, such as the network's learning rate and the optimizer and loss functions it should use. The following code shows you how to use stochastic gradient descent, SGD for short, as the optimizer function and mean square as the loss function:

Next, in order to let the TFLearn framework know that our network model is actually a deep neural network model, we must call the DNN() function.

The model is now ready. All we need to do now is train it using the training data we created earlier. So call the fit() method of the model and, along with the training data, specify the number of training epochs to run. Because the training data is very small, our model will need thousands of epochs to attain reasonable accuracy.

Once the training is complete, we can call the predict() method of the model to check if it is generating the desired outputs. The following code shows you how to check the outputs for all valid inputs:

If you run the Python script now, you should see output that looks like this:

Predictions after training

Note that the outputs are never exactly 0 or 1. Instead, they are floating-point numbers that are either close to zero or close to one. Therefore, while using the outputs, you might want to use Python's round() function.

Unless we explicitly save the model after training it, we will lose it as soon as the script ends. Fortunately, with TFLearn, a simple call to the save() method saves the model. However, to be able to use the saved model with TensorFlow Mobile, before saving it, we must make sure we remove all the training-related operations, which are present in the tf.GraphKeys.TRAIN_OPS collection, associated with it. The following code shows you how to do so:

If you run the script again, you'll see that it generates a checkpoint file, a metadata file, an index file, and a data file, all of which when used together can quickly recreate our trained model.

2. Freezing the Model

In addition to saving the model, we must freeze it before we can use it with TensorFlow Mobile. The process of freezing a model, as you might have guessed, involves converting all its variables into constants. Additionally, a frozen model must be a single binary file that conforms to the Google Protocol Buffers serialization format.

Create a new Python script named freeze_model.py and open it using a text editor. We'll be writing all the code to freeze our model inside this file.

Because TFLearn doesn't have any functions for freezing models, we'll have to use the TensorFlow APIs directly now. Import them by adding the following line to the file:

Throughout the script, we'll be using a single TensorFlow session. To create the session, use the constructor of the Session class.

At this point, we must create a Saver object by calling the import_meta_graph() function and passing the name of the model's metadata file to it. In addition to returning a Saver object, the import_meta_graph() function also automatically adds the graph definition of the model to the graph definition of the session.

Once the saver is created, we can initialize all the variables that are present in the graph definition by calling the restore() method, which expects the path of the directory containing the model's latest checkpoint file.

At this point, we can call the convert_variables_to_constants() function to create a frozen graph definition where all the variables of the model are replaced with constants. As its inputs, the function expects the current session, the current session's graph definition, and a list containing the names of the model's output layers.

Calling the SerializeToString() method of the frozen graph definition gives us a binary protobuf representation of the model. By using Python's basic file I/O facilities, I suggest you save it as a file named frozen_model.pb.

You can run the script now to generate the frozen model.

We now have everything we need to start using TensorFlow Mobile.

3. Android Studio Project Setup

The TensorFlow Mobile library is available on JCenter, so we can directly add it as an implementation dependency in the app module's build.gradle file.

To add the frozen model to the project, place the frozen_model.pb file in the project's assets folder.

4. Initializing the TensorFlow Interface

TensorFlow Mobile offers a simple interface we can use to interact with our frozen model. To create the interface, use the constructor of the TensorFlowInferenceInterface class, which expects an AssetManager instance and the filename of the frozen model.

In the above code, you can see that we're spawning a new thread. Doing so, although not always necessary, is recommended in order to make sure that the app's UI stays responsive.

To be sure that TensorFlow Mobile has managed to read our model's file correctly, let's now try printing the names of all the operations that are present in the model's graph. To get a reference to the graph, we can use the graph() method of the interface, and to get all the operations, the operations() method of the graph. The following code shows you how:

If you run the app now, you should be able to see over a dozen operation names printed in Android Studio's Logcat window. Among all those names, if there were no errors while freezing the model, you'll be able to find the names of the input and output layers: my_input/X and my_output/Sigmoid.

Logcat window showing list of operations

5. Using the Model

To make predictions with the model, we must put data into its input layer and retrieve data from its output layer. To put data into the input layer, use the feed() method of the interface, which expects the name of the layer, an array containing the inputs, and the dimensions of the array. The following code shows you how to send the numbers 0 and 1 to the input layer:

After loading data into the input layer, we must run an inference operation using the run() method, which expects the name of the output layer. Once the operation is complete, the output layer will contain the prediction of the model. To load the prediction into a Kotlin array, we can use the fetch() method. The following code shows you how to do so:

How you use the prediction is of course up to you. For now, I suggest you simply print it.

You can run the app now to see that the model's prediction is correct.

Logcat window displaying the prediction

Feel free to change the numbers you feed to the input layer to confirm that the model's predictions are always correct.

Conclusion

You now know how to create a simple TensorFlow model and use it with TensorFlow Mobile in Android apps. You don't always have to limit yourself to your own models, though. With the skills you learned today, you should have no problems using larger models, such as MobileNet and Inception, available in the TensorFlow model zoo. Note, however, that such models will lead to larger APKs, which may create issues for users with low-end devices.

To learn more about TensorFlow Mobile, do refer to the official documentation.

2018-04-30T17:00:00.000Z2018-04-30T17:00:00.000ZAshraff Hathibelagal

How to Use TensorFlow Mobile in Android Apps

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-30957

With TensorFlow, one of the most popular machine learning frameworks available today, you can easily create and train deep models—also commonly referred to as deep feed-forward neural networks—that can solve a variety of complex problems, such as image classification, object detection, and natural language comprehension. TensorFlow Mobile is a library designed to help you leverage those models in your mobile apps.

In this tutorial, I'll show you how to use TensorFlow Mobile in Android Studio projects.

Prerequisites

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

  • Android Studio 3.0 or higher
  • TensorFlow 1.5.0 or higher
  • an Android device running API level 21 or higher
  • and a basic understanding of the TensorFlow framework

1. Creating a Model

Before we start using TensorFlow Mobile, we'll need a trained TensorFlow model. Let's create one now.

Our model is going to be very basic. It will behave like an XOR gate, taking two inputs, both of which can be either zero or one, and producing one output, which will be zero if both the inputs are identical and one otherwise. Additionally, because it's going to be a deep model, it will have two hidden layers, one with four neurons, and another with three neurons. You are free to change the number of hidden layers and the numbers of neurons they contain.

In order to keep this tutorial short, instead of using the low-level TensorFlow APIs directly, we'll be using TFLearn, a popular wrapper framework for TensorFlow offering more intuitive and concise APIs. If you don't have it already, use the following command to install it inside your TensorFlow virtual environment:

To start creating the model, create a Python script named create_model.py, preferably in an empty directory, and open it with your favorite text editor.

Inside the file, the first thing we need to do is import the TFLearn APIs.

Next, we must create the training data. For our simple model, there will be only four possible inputs and outputs, which will resemble the contents of the XOR gate's truth table.

It is usually a good idea to use random values picked from a uniform distribution while assigning initial weights to all the neurons in the hidden layers. To generate the values, use the uniform() method.

At this point, we can start creating the layers of our neural network. To create the input layer, we must use the input_data() method, which allows us to specify the number of inputs the network can accept. Once the input layer is ready, we can call the fully_connected() method multiple times to add more layers to the network.

Note that in the above code, we have given meaningful names to the input and output layers. Doing so is important because we'll need them while using the network from our Android app. Also note that the hidden and output layers are using the sigmoid activation function. You are free to experiment with other activation functions, such as softmaxtanh, and relu.

As the last layer of our network, we must create a regression layer using the regression() function, which expects a few hyper-parameters as its arguments, such as the network's learning rate and the optimizer and loss functions it should use. The following code shows you how to use stochastic gradient descent, SGD for short, as the optimizer function and mean square as the loss function:

Next, in order to let the TFLearn framework know that our network model is actually a deep neural network model, we must call the DNN() function.

The model is now ready. All we need to do now is train it using the training data we created earlier. So call the fit() method of the model and, along with the training data, specify the number of training epochs to run. Because the training data is very small, our model will need thousands of epochs to attain reasonable accuracy.

Once the training is complete, we can call the predict() method of the model to check if it is generating the desired outputs. The following code shows you how to check the outputs for all valid inputs:

If you run the Python script now, you should see output that looks like this:

Predictions after training

Note that the outputs are never exactly 0 or 1. Instead, they are floating-point numbers that are either close to zero or close to one. Therefore, while using the outputs, you might want to use Python's round() function.

Unless we explicitly save the model after training it, we will lose it as soon as the script ends. Fortunately, with TFLearn, a simple call to the save() method saves the model. However, to be able to use the saved model with TensorFlow Mobile, before saving it, we must make sure we remove all the training-related operations, which are present in the tf.GraphKeys.TRAIN_OPS collection, associated with it. The following code shows you how to do so:

If you run the script again, you'll see that it generates a checkpoint file, a metadata file, an index file, and a data file, all of which when used together can quickly recreate our trained model.

2. Freezing the Model

In addition to saving the model, we must freeze it before we can use it with TensorFlow Mobile. The process of freezing a model, as you might have guessed, involves converting all its variables into constants. Additionally, a frozen model must be a single binary file that conforms to the Google Protocol Buffers serialization format.

Create a new Python script named freeze_model.py and open it using a text editor. We'll be writing all the code to freeze our model inside this file.

Because TFLearn doesn't have any functions for freezing models, we'll have to use the TensorFlow APIs directly now. Import them by adding the following line to the file:

Throughout the script, we'll be using a single TensorFlow session. To create the session, use the constructor of the Session class.

At this point, we must create a Saver object by calling the import_meta_graph() function and passing the name of the model's metadata file to it. In addition to returning a Saver object, the import_meta_graph() function also automatically adds the graph definition of the model to the graph definition of the session.

Once the saver is created, we can initialize all the variables that are present in the graph definition by calling the restore() method, which expects the path of the directory containing the model's latest checkpoint file.

At this point, we can call the convert_variables_to_constants() function to create a frozen graph definition where all the variables of the model are replaced with constants. As its inputs, the function expects the current session, the current session's graph definition, and a list containing the names of the model's output layers.

Calling the SerializeToString() method of the frozen graph definition gives us a binary protobuf representation of the model. By using Python's basic file I/O facilities, I suggest you save it as a file named frozen_model.pb.

You can run the script now to generate the frozen model.

We now have everything we need to start using TensorFlow Mobile.

3. Android Studio Project Setup

The TensorFlow Mobile library is available on JCenter, so we can directly add it as an implementation dependency in the app module's build.gradle file.

To add the frozen model to the project, place the frozen_model.pb file in the project's assets folder.

4. Initializing the TensorFlow Interface

TensorFlow Mobile offers a simple interface we can use to interact with our frozen model. To create the interface, use the constructor of the TensorFlowInferenceInterface class, which expects an AssetManager instance and the filename of the frozen model.

In the above code, you can see that we're spawning a new thread. Doing so, although not always necessary, is recommended in order to make sure that the app's UI stays responsive.

To be sure that TensorFlow Mobile has managed to read our model's file correctly, let's now try printing the names of all the operations that are present in the model's graph. To get a reference to the graph, we can use the graph() method of the interface, and to get all the operations, the operations() method of the graph. The following code shows you how:

If you run the app now, you should be able to see over a dozen operation names printed in Android Studio's Logcat window. Among all those names, if there were no errors while freezing the model, you'll be able to find the names of the input and output layers: my_input/X and my_output/Sigmoid.

Logcat window showing list of operations

5. Using the Model

To make predictions with the model, we must put data into its input layer and retrieve data from its output layer. To put data into the input layer, use the feed() method of the interface, which expects the name of the layer, an array containing the inputs, and the dimensions of the array. The following code shows you how to send the numbers 0 and 1 to the input layer:

After loading data into the input layer, we must run an inference operation using the run() method, which expects the name of the output layer. Once the operation is complete, the output layer will contain the prediction of the model. To load the prediction into a Kotlin array, we can use the fetch() method. The following code shows you how to do so:

How you use the prediction is of course up to you. For now, I suggest you simply print it.

You can run the app now to see that the model's prediction is correct.

Logcat window displaying the prediction

Feel free to change the numbers you feed to the input layer to confirm that the model's predictions are always correct.

Conclusion

You now know how to create a simple TensorFlow model and use it with TensorFlow Mobile in Android apps. You don't always have to limit yourself to your own models, though. With the skills you learned today, you should have no problems using larger models, such as MobileNet and Inception, available in the TensorFlow model zoo. Note, however, that such models will lead to larger APKs, which may create issues for users with low-end devices.

To learn more about TensorFlow Mobile, do refer to the official documentation.

2018-04-30T17:00:00.000Z2018-04-30T17:00:00.000ZAshraff Hathibelagal

Building a Shopping List Application With CloudKit: Introduction

$
0
0

Back in 2012, Apple introduced iCloud alongside iOS 5. At the same time, the company announced that developers would have access to iCloud through a number of APIs. Up until now, developers have had three options:

These APIs aren't perfect though. A major shortcoming is their lack of transparency. Core Data integration in particular has led to frustration and confusion among even the most experienced developers. When something went wrong, developers had no idea what or who the culprit was. It could be a problem in their code or in Apple's.

CloudKit

At WWDC 2014, Apple introduced CloudKit, a brand new framework that directly interacts with Apple's iCloud servers. The framework is comparable to a number of PaaS (Platform as a Service) solutions, such as Firebase. Like Firebase  Apple provides a flexible API and a dashboard that offers developers a peek into the data stored on Apple's iCloud servers.

What I like most about CloudKit is Apple's own commitment to the framework. According to the company, iCloud Drive and iCloud Photo Library are built on top of CloudKit. This shows that the CloudKit framework and infrastructure is robust and reliable.

As a developer, this sign of trust and commitment is important. In the past, Apple occasionally released APIs that were plagued by bugs or lacking key features simply because the company wasn't eating its own dog food. This isn't true for CloudKit. And that is promising.

Should You Use CloudKit

Key-value storage and document storage have their use and Apple emphasizes that CloudKit doesn't replace or deprecate existing iCloud APIs. The same is true for Core Data. CloudKit doesn't offer local storage, for example. This means that an application running on a device without a network connection is pretty much useless if it solely relies on CloudKit.

Apple also emphasizes that error handling is critical when working with CloudKit. If a save operation fails, for example, and the user isn't notified, then she may not even know that her data wasn't saved—and lost.

CloudKit is a great solution for storing structured as well as non-structured data in the cloud. If you need a solution to access data on multiple devices, then CloudKit is certainly an option to consider.

During this year's WWDC, Apple did what few developers had expected or hoped for. It announced a web service for CloudKit. This means that CloudKit can be used on virtually any platform, including Android and Windows Phone.

Apple's pricing is pretty competitive too. Getting started with CloudKit is free and it remains free for most applications. Again, CloudKit is certainly worth considering if you plan to store data in the cloud.

CloudKit Concepts

Developers struggling with Core Data are often unfamiliar with the building blocks of the framework. If you don't take the time to learn about and understand the Core Data stack, then you will inevitably run into problems. The same is true for CloudKit.

Before we start working on a sample application that uses CloudKit, I want to spend a few minutes introducing you to a number of key concepts of the CloudKit framework and infrastructure. Let's start with containers, databases, and sandboxing.

Privacy and Containment

Apple makes it very clear that privacy is an important aspect of CloudKit. The first thing to know is that each application has its own container in iCloud. This concept is very similar to how iOS applications each have their own sandbox. However, it is possible to share a container with other applications as long as those applications are associated with the same developer account. As you can imagine, this opens up a number of interesting possibilities for developers.

A CloudKit container contains several databases. Each container has one public database that can be used to store data that is accessible to every user of your application. In addition to the public database, a container also contains a private database for each user of your application. The user's private database is used to store data that is specific to that particular user. Data segregation and encapsulation is a key component of the CloudKit and iCloud infrastructure.

Even though an application's container can hold many databases, from a developer's perspective a container holds only two databases, the public database and the private database of the user that is currently signed in to their iCloud account. As of 2017, Apple introduced a third database, shared database, providing apps with the ability to share a subset of records that is shared and  on other user's private database, inviting them to contribute to those exposed records. 


I'll talk more about iCloud accounts a bit later.

Records and Record Zones

The databases of an application's container store records. This isn't very different from a traditional database. At first glance, the records stored in a CloudKit database seem to be nothing more than wrappers for a dictionary of key-value pairs. They may look like glorified dictionaries, but that's only part of the story.

Each record also has a record type and a number of metadata fields. A record's metadata keeps track of when the record was created, which user created the record, when the record was last updated, and who updated the record.

The CKRecord class represents such a record and it's a pretty powerful class. The values you can store in a record aren't limited to property list types. You can store strings, numbers, dates, and blobs of data in a record, but the CKRecord class also treats location data, CLLocation, as a first-class data type.

You can even store arrays of the supported data types in a record. In other words, arrays of strings or numbers are no problem for a CKRecord instance.

Records are organized in record zones. A record zone groups related records. The public and private database each have a default record zone, but it is possible to create custom record zones if needed. Record zones are an advanced topic that we won't discuss in much detail in this series.

Relationships

Relationships between records are managed by instances of the CKReference class. Let's look at an example to better understand how exactly relationships work. The application we will create in this series will manage a number of shopping lists. Each list can have zero or more items in it. This means that each item needs to have a reference to the list it belongs to.

It's important to understand that the item keeps a reference to the list. While it is possible to create an array of CKReference instances for the items of a list, it is more convenient—and recommended—to keep the foreign key with the item, not the list. This is also what Apple recommends.

The way CloudKit manages relationships is fairly basic, but it does provide an option to automatically delete a record's children when the parent record is deleted. We'll take a closer look at relationships a bit later in this series.

Assets

I also would like to mention the CKAsset class. While it's possible to store blobs of data in a record, unstructured data, such as images, audio, and video, should be stored as CKAsset instances. A CKAsset instance is always associated with a record and it corresponds with a file on disk. We won't be working with the CKAsset class in this series.

Authentication

I'm sure you agree that CloudKit looks quite appealing. There is, however, an important detail that we haven't discussed yet, authentication. A user authenticates itself through its iCloud account. If a user isn't signed in to their iCloud account, then they're unable to write data to iCloud.

While this is true for any of the iCloud APIs, keep in mind that applications that solely rely on CloudKit won't be very functional in that case. All the user can do is access the data in the public database, if permitted by the developer.

Reading Data

If a user isn't signed in to their iCloud account, they can still read data from the public database. It goes without saying that the private database is not accessible since iCloud doesn't know who is using the application.

Reading and Writing

When signed in, the user can read and write to the public and their private database. I already mentioned that Apple takes privacy very seriously. As a result, the records stored in the private database are only accessible by the user. Even you, the developer, cannot see the data the user has stored in its private database. This is the downside of Apple managing your application's backend, but it's a definite win for the user.

Shopping List

The application we're about to build will manage your shopping lists. Each shopping list will have a name and zero or more items. After building the shopping list application, you should feel pretty comfortable using the CloudKit framework in a project of your own.

Prerequisites

For this tutorial, I will be using Xcode 9 and Swift 4. 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. This means that you will need to update the project's source code to satisfy the compiler. The changes are mostly minor, but it's important to be aware of this.

Because CloudKit is an advanced topic, I am going to assume that you are familiar with both Xcode and the Swift programming language. If you are new to iOS development, then I recommend reading an introductory tutorial first or take one of our courses on Swift development. Derek Jensen has created a course on the Swift programming language as well as a course on iOS development with Swift. Be sure to check those out if you are new to iOS development or the Swift language.

Project Setup

It's time to start writing some code. Launch Xcode and create a new project based on the Single View Application template.

Choose the Single View Application template
Give your project a name and an organization identifier. The resulting bundle identifier will be used to create the identifier of your application's default container. That identifier needs to be unique across developer accounts as they share one global namespace. It's therefore important to follow Apple's advise and use reverse domain name notation.
Configure the project

Enabling iCloud

The next step is enabling iCloud and CloudKit. Select the project in the Project Navigator on the left and select the target for your application from the list of targets. Open the General tab and set Team to the correct team. To avoid any problems in the next step, verify that your developer account has the required permissions to create an App ID.

Select the correct team
Next, open the Capabilities tab at the top and set the switch for iCloud to on. Xcode will need a moment to create an App ID on your behalf. It will also add the necessary entitlements to the App ID. If this doesn't work, then make sure the team is correctly set and you have the required permissions to create an App ID.
Enable iCloud

Enabling CloudKit is as simple as checking the checkbox labeled CloudKit. By default, your application will use the default container for your application. This container is automatically created for you when you enable CloudKit.

If your application needs access to a different container or it needs access to multiple containers, then check the checkbox labeled Specify custom containers and check the containers your application requires access to.

Enable custom containers
You may have noticed that Xcode has automatically linked your target against the CloudKit framework. This means that you're ready to start using CloudKit in your application.

Getting Your Feet Wet

In the next tutorial of this series, we will add the ability to add, edit, and remove shopping lists. To finish this tutorial, however, I'd like to get your feet wet by showing you how to interact with the CloudKit API. All we're going to do is fetch the record of the currently signed in user.

Open ViewController.swift and add an import statement at the top to import the CloudKit framework.

To fetch the user record, we first need to fetch the record's identifier. Let's see how this works. I've created a helper method, fetchUserRecordID, to contain the logic for fetching the user's record identifier. We invoke this method in the view controller's viewDidLoad method.

The implementation of fetchUserRecordID is a bit more interesting than viewDidLoad. We first fetch a reference to the application's default container by invoking defaultContainer on the CKContainer class. We then call fetchUserRecordIDWithCompletionHandler(_:) on defaultContainer. This method accepts a closure as its only argument.

The closure accepts two arguments, an optional CKRecordID instance and an optional NSError instance. If error is nil, we safely unwrap recordID.

It's important to emphasize that the closure will be called on a background thread. This means that you need to be careful when updating the user interface of your application from within a closure invoked by CloudKit. In fetchUserRecordID, for example, I explicitly call fetchUserRecord(_:) on the main thread.

In fetchUserRecord(_:), we fetch the user record by telling CloudKit which record we're interested in. Notice that we call fetchRecordWithID(_:completionHandler:) on the privateDatabase object, a property of the defaultContainer object.

The method accepts a CKRecordID instance and a completion handler. The latter accepts an optional CKRecord instance and an NSError instance. If we successfully fetched the user record, we print it to Xcode's Console.

When you run the app in Xcode, you will see in the console something similar to:

This should have given you a taste of the CloudKit framework. It's modern API is intuitive and easy to use. In the next tutorial, we will dig deeper in the possibilities of the CloudKit API.

You can clone the complete sample project, at Github (tag #introduction)

Conclusion

You should now have a proper understanding of the basics of the CloudKit framework. The remainder of this series will be focused on building the shopping list application. In the next tutorial, we will start by adding the ability to add, edit, and remove shopping lists.

2018-05-07T18:10:21.480Z2018-05-07T18:10:21.480ZBart Jacobs

Building a Shopping List Application With CloudKit: Introduction

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24674

Back in 2012, Apple introduced iCloud alongside iOS 5. At the same time, the company announced that developers would have access to iCloud through a number of APIs. At first, developers had three options:

These APIs aren't perfect, though. A major shortcoming is their lack of transparency. Core Data integration, in particular, has led to frustration and confusion among even the most experienced developers. When something goes wrong, developers have no idea what or who the culprit is. It could be a problem in their code or in Apple's.

CloudKit

At WWDC 2014, Apple introduced CloudKit, a brand new framework that directly interacts with Apple's iCloud servers. The framework is comparable to a number of PaaS (Platform as a Service) solutions, such as Firebase. Like Firebase, Apple provides a flexible API and a dashboard that offers developers a peek into the data stored on Apple's iCloud servers.

What I like most about CloudKit is Apple's own commitment to the framework. According to the company, iCloud Drive and iCloud Photo Library are built on top of CloudKit. This shows that the CloudKit framework and its infrastructure are robust and reliable.

As a developer, this sign of trust and commitment is important. In the past, Apple occasionally released APIs that were plagued by bugs or lacking key features simply because the company wasn't eating its own dog food. This isn't true for CloudKit. And that is promising.

Should You Use CloudKit?

Key-value storage and document storage have their uses, and Apple emphasizes that CloudKit doesn't replace or deprecate existing iCloud APIs. The same is true for Core Data. CloudKit doesn't offer local storage, for example. This means that an application running on a device without a network connection is pretty much useless if it solely relies on CloudKit.

Apple also emphasizes that error handling is critical when working with CloudKit. If a save operation fails, for example, and the user isn't notified, then she may not even know that her data wasn't saved—and lost.

CloudKit is a great solution for storing structured as well as non-structured data in the cloud. If you need a solution to access data on multiple devices, then CloudKit is certainly an option to consider.

At the 2015 WWDC, Apple did what few developers had expected or hoped for. It announced a web service for CloudKit. This means that CloudKit can be used on virtually any platform, including Android and Windows Phone.

Apple's pricing is pretty competitive too. Getting started with CloudKit is free, and it remains free for most applications. Again, CloudKit is certainly worth considering if you plan to store data in the cloud.

CloudKit Concepts

Developers struggling with Core Data are often unfamiliar with the building blocks of the framework. If you don't take the time to learn about and understand the Core Data stack, then you will inevitably run into problems. The same is true for CloudKit.

Before we start working on a sample application that uses CloudKit, I want to spend a few minutes introducing you to a number of key concepts of the CloudKit framework and infrastructure. Let's start with containers, databases, and sandboxing.

Privacy and Containment

Apple makes it very clear that privacy is an important aspect of CloudKit. The first thing to know is that each application has its own container in iCloud. This concept is very similar to how iOS applications each have their own sandbox. However, it is possible to share a container with other applications as long as those applications are associated with the same developer account. As you can imagine, this opens up a number of interesting possibilities for developers.

A CloudKit container contains several databases. Each container has one public database that can be used to store data that is accessible to every user of your application. In addition to the public database, a container also contains a private database for each user of your application. The user's private database is used to store data that is specific to that particular user. Data segregation and encapsulation is a key component of the CloudKit and iCloud infrastructure.

Even though an application's container can hold many databases, from a developer's perspective a container holds only two databases: the public database and the private database of the user that is currently signed in to their iCloud account. As of 2017, Apple introduced a third database, shared database, providing apps with the ability to share a subset of records that is shared on another user's private database, inviting them to contribute to those exposed records. 

diagram of public private and shared databases

I'll talk more about iCloud accounts a bit later.

Records and Record Zones

The databases of an application's container store records. This isn't very different from a traditional database. At first glance, the records stored in a CloudKit database seem to be nothing more than wrappers for a dictionary of key-value pairs. They may look like glorified dictionaries, but that's only part of the story.

Each record also has a record type and a number of metadata fields. A record's metadata keeps track of when the record was created, which user created the record, when the record was last updated, and who updated the record.

The CKRecord class represents such a record, and it's a pretty powerful class. The values you can store in a record aren't limited to property list types. You can store strings, numbers, dates, and blobs of data in a record, but the CKRecord class also treats location data, CLLocation, as a first-class data type.

You can even store arrays of the supported data types in a record. In other words, arrays of strings or numbers are no problem for a CKRecord instance.

Records are organized in record zones. A record zone groups related records. The public and private database each have a default record zone, but it is possible to create custom record zones if needed. Record zones are an advanced topic that we won't discuss in much detail in this series.

Relationships

Relationships between records are managed by instances of the CKReference class. Let's look at an example to better understand how exactly relationships work. The application we will create in this series will manage a number of shopping lists. Each list can have zero or more items in it. This means that each item needs to have a reference to the list it belongs to.

diagram of shopping list and items

It's important to understand that the item keeps a reference to the list. While it is possible to create an array of CKReference instances for the items of a list, it is more convenient—and recommended—to keep the foreign key with the item, not the list. This is also what Apple recommends.

The way CloudKit manages relationships is fairly basic, but it does provide an option to automatically delete a record's children when the parent record is deleted. We'll take a closer look at relationships a bit later in this series.

Assets

I also would like to mention the CKAsset class. While it's possible to store blobs of data in a record, unstructured data (such as images, audio, and video) should be stored as CKAsset instances. A CKAsset instance is always associated with a record, and it corresponds to a file on disk. We won't be working with the CKAsset class in this series.

Authentication

I'm sure you agree that CloudKit looks quite appealing. There is, however, an important detail that we haven't discussed yet: authentication. Users authenticate themselves through their iCloud accounts. Users who aren't signed in to an iCloud account are unable to write data to iCloud.

While this is true for any of the iCloud APIs, keep in mind that applications that solely rely on CloudKit won't be very functional in that case. All the user can do is access the data in the public database, if permitted by the developer.

Reading Data

Users who aren't signed in to their iCloud accounts can still read data from the public database. It goes without saying that the private database is not accessible since iCloud doesn't know who is using the application.

Reading and Writing

When signed in, users can read and write to the public and their private database. I already mentioned that Apple takes privacy very seriously. As a result, the records stored in the private database are only accessible by the user. Even you, the developer, cannot see the data users have stored in their private databases. This is the downside of Apple managing your application's back end, but it's a definite win for the user.

Shopping List

The application we're about to build will manage your shopping lists. Each shopping list will have a name and zero or more items. After building the shopping list application, you should feel pretty comfortable using the CloudKit framework in a project of your own.

Prerequisites

For this tutorial, I will be using Xcode 9 and Swift 4. 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. This means that you will need to update the project's source code to satisfy the compiler. The changes are mostly minor, but it's important to be aware of this.

Because CloudKit is an advanced topic, I am going to assume that you are familiar with both Xcode and the Swift programming language. If you are new to iOS development, then I recommend reading an introductory tutorial first or taking one of our courses on Swift development:

Be sure to check those out if you are new to iOS development or the Swift language.

Project Setup

It's time to start writing some code. Launch Xcode and create a new project based on the Single View Application template.

Choose the Single View Application template

Give your project a name and an organization identifier. The resulting bundle identifier will be used to create the identifier of your application's default container. That identifier needs to be unique across developer accounts as they share one global namespace. It's therefore important to follow Apple's advice and use reverse domain name notation.

Configure the project

Enabling iCloud

The next step is enabling iCloud and CloudKit. Select the project in the Project Navigator on the left and select the target for your application from the list of targets. Open the General tab and set Team to the correct team. To avoid any problems in the next step, verify that your developer account has the required permissions to create an App ID.

Select the correct team

Next, open the Capabilities tab at the top and set the switch for iCloud to on. Xcode will need a moment to create an App ID on your behalf. It will also add the necessary entitlements to the App ID. If this doesn't work, then make sure the team is correctly set and you have the required permissions to create an App ID.

Enable iCloud

Enabling CloudKit is as simple as checking the checkbox labeled CloudKit. By default, your application will use the default container for your application. This container is automatically created for you when you enable CloudKit.

If your application needs access to a different container or to multiple containers, then check the checkbox labeled Specify custom containers and check the containers your application requires access to.

Enable custom containers

You may have noticed that Xcode has automatically linked your target to the CloudKit framework. This means that you're ready to start using CloudKit in your application.

Getting Your Feet Wet

In the next tutorial of this series, we will add the ability to add, edit, and remove shopping lists. To finish this tutorial, however, I'd like to get your feet wet by showing you how to interact with the CloudKit API. All we're going to do is fetch the record of the currently signed-in user.

Open ViewController.swift and add an import statement at the top to import the CloudKit framework.

To fetch the user record, we first need to fetch the record's identifier. Let's see how this works. I've created a helper method, fetchUserRecordID, to contain the logic for fetching the user's record identifier. We invoke this method in the view controller's viewDidLoad method.

The implementation of fetchUserRecordID is a bit more interesting than viewDidLoad. We first fetch a reference to the application's default container by invoking defaultContainer on the CKContainer class. We then call fetchUserRecordIDWithCompletionHandler(_:) on defaultContainer. This method accepts a closure as its only argument.

The closure accepts two arguments: an optional CKRecordID instance and an optional NSError instance. If error is nil, we safely unwrap recordID.

It's important to emphasize that the closure will be called on a background thread. This means that you need to be careful when updating the user interface of your application from within a closure invoked by CloudKit. In fetchUserRecordID, for example, I explicitly call fetchUserRecord(_:) on the main thread.

In fetchUserRecord(_:), we fetch the user record by telling CloudKit which record we're interested in. Notice that we call fetchRecordWithID(_:completionHandler:) on the privateDatabase object, a property of the defaultContainer object.

The method accepts a CKRecordID instance and a completion handler. The latter accepts an optional CKRecord instance and an NSError instance. If we successfully fetched the user record, we print it to Xcode's Console.

When you run the app in Xcode, you will see in the console something similar to:

Code output in console

This should have given you a taste of the CloudKit framework. Its modern API is intuitive and easy to use. In the next tutorial, we will dig deeper into the possibilities of the CloudKit API.

You can clone the complete sample project, at GitHub (tag #introduction).

Conclusion

You should now have a proper understanding of the basics of the CloudKit framework. The remainder of this series will be focused on building the shopping list application. In the next tutorial, we will start by adding the ability to add, edit, and remove shopping lists.

2018-05-07T18:10:21.480Z2018-05-07T18:10:21.480ZDoron Katz

Getting Started With Cloud Firestore for iOS

$
0
0

Mobile coders have been taking advantage of Google’s Mobile Backend as a Service (MBaaS) platform Firebase Realtime Database for many years, helping them focus on building features for their apps without having to worry about the back-end infrastructure and database. By making it easy to store and persist data in the cloud and take care of authentication and security, Firebase allows coders to focus on the client side. 

Last year, Google announced yet another back-end database solution, Cloud Firestore, built from the ground up with the promise of greater scalability and intuitiveness. However, this introduced some confusion as to its place in relation to Google’s already existing flagship product, Firebase Realtime Database. This tutorial will outline the differences between the two platforms and the distinct advantages of each. You will learn how to work with Firestore document references, as well as reading, writing, updating and deleting data in real time, by building a simple reminders app.

Objectives of This Tutorial

This tutorial will expose you to Cloud Firestore. You'll learn how to leverage the platform for real-time database persistence and synchronization. We'll cover the following topics:

  • what Cloud Firestore is
  • the Firestore data model
  • setting up Cloud Firestore
  • creating and working with Cloud Firestore references
  • reading data in real time from Cloud Firestore
  • creating, updating and deleting data
  • filtering and compound queries

Assumed Knowledge

This tutorial assumes you have had some exposure to Firebase and a background developing with Swift and Xcode.

What Is Cloud Firestore?

Like Firebase Realtime Database, Firestore provides mobile and web developers with a cross-platform cloud solution to persist data in real time, regardless of network latency or internet connectivity, as well as seamless integration with the Google Cloud Platform suite of products. Along with these similarities, there are distinct advantages and disadvantages that differentiate one from the other. 

Data Model

On a fundamental level, Realtime Database stores data as one large, monolithic, hierarchical JSON tree, whereas Firestore organizes data in documents and collections, as well as sub-collections. This requires less denormalization. Storing data in one JSON tree has the benefits of simplicity when it comes to working with simple data requirements; however, it becomes more cumbersome at scale when working with more complex hierarchical data. 

Offline Support

Both products offer offline support, actively caching data in queues when there is latent or no network connectivity—synchronising local changes back to the back end when possible. Firestore supports offline synchronisation for web apps in addition to mobile apps, whereas the Realtime Database only enables mobile synchronization.

Queries and Transactions 

Realtime Database only supports limited sorting and filtering capabilities—you can only sort or filter on a property level, but not both, in a single query. Queries are also deep, meaning they return a large sub-tree of results back. The product only supports simple write and transaction operations which require a completion callback. 

Firestore, on the other hand, introduces index queries with compound sorting and filtering, allowing you to combine actions to create chain filters and sorting. You can also execute shallow queries returning sub-collections in lieu of the entire collection you would get with Realtime Database. Transactions are atomic in nature, whether you send a batch operation or single, with transactions repeating automatically until concluded. Additionally, Realtime Database only supports individual write transactions, whereas Firestore affords batch operations atomically.

Performance and Scalability

The Realtime Database, as you would expect, is quite robust and has low latency. However, databases are restricted to single regions, subject to zonal availability. Firestore, on the other hand, houses data horizontally across multiple zones and regions to ensure true global availability, scalability, and reliability. In fact, Google has promised that Firestore will be more reliable than Realtime Database. 

Another shortcoming of the Realtime Database is the limitation to 100,000 concurrent users (100,000 concurrent connections and 1,000 writes/second in a single database) after which you would have to shard your database (split your database into multiple databases) in order to support more users. Firestore automatically scales across multiple instances without you having to intervene. 

Designed from the ground up with scalability in mind, Firestore has a new schematic architecture that replicates data across multiple regions, takes care of authentication, and handles other security-related matters all within its client-side SDK. Its new data model is more intuitive than Firebase's, more closely resembling other comparable NoSQL database solutions like MongoDB, while providing a more robust querying engine. 

Security 

Finally, Realtime Database, as you know from our previous tutorials, manages security through cascading rules with separate validation triggers. This works with Firebase Database Rules, validating your data separately. Firestore, on the other hand, provides a simpler yet more powerful security model taking advantage of Cloud Firestore Security Rules and Identity and Access Management (IAM), with data validation excepted automatically.

The Firestore Data Model

Firestore is a NoSQL document-based database, consisting of collections of documents, each of which contains data. As it's a NoSQL database, you won’t get tables, rows, and other elements you would find in a relational database, but instead sets of key/value pairs that you would find within documents. 

You create documents and collections implicitly by assigning data to a document, and if the document or collection doesn’t exist, it will automatically be created for you, as the collection always has to be the root (first) node. Here is a simple Tasks example schema of the project you will be working on shortly, consisting of the Tasks collection, as well as numerous documents containing two fields, the name (string), and a flag for whether the task is done (boolean).

simple Tasks example schema of the project

Let’s decompose each of the elements so you can understand them better. 

Collections

Synonymous with database tables in the SQL world, collections contain one or more documents. Collections have to be the root elements in your schema and can only contain documents, not other collections. However, you can refer to a document which in turn refers to collections (sub-collections).

Diagram of document and collections

In the diagram above, a task consists of two primitive fields (name and done) as well as a sub-collection (sub-task) which consists of two primitive fields of its own. 

Documents

Documents consist of key/value pairs, with the values having one of the following types: 

  • primitive fields (such as strings, numbers, boolean)
  • complex nested objects (lists or arrays of primitives)
  • sub-collections

Nested objects are also called maps and can be represented as follows, within the document. The following is an example of a nested object and array, respectively:

For more information on the supported data types, refer to Google’s Data Types documentation. Next, you will set up a project to work with Cloud Firestore.

Setting Up the Project

If you have worked with Firebase before, a lot of this should be familiar to you. Otherwise, you will need to create an account in Firebase and follow the instructions in the ‘Set Up the Project’ section of our previous tutorial, Get Started With Firebase Authentication for iOS . 

To follow along with this tutorial, clone the tutorial project repo. Next, include the Firestore library byadding the following to your Podfile:

Enter the following in your terminal to build your library:

Next, switch to Xcode and open up the .xcworkspace file. Navigate to the AppDelegate.swift file and enter the following within the application:didFinishLaunchingWithOptions: method:

In your browser, go to the Firebase console and select the Database tab on the left. 

Database tab in the Firebase console

Make sure you select the option to Start in Test Mode so that you don’t have any security issues while we experiment, and heed the security notice when you do move your app into production. You are now ready to create a collection and some sample documents.

Adding a Collection and Sample Document

To start off, create an initial collection, Tasks, by selecting the Add Collection button and naming the collection, as illustrated below:

naming the collection

For the first document, you are going to leave the Document ID blank, which will auto-generate an ID for you. The document will simply consist of two fields: name and done.

Document with two fields

Save the document, and you should be able to confirm the collection and document along with the auto-generated ID:

collection and document with the auto-generated ID

With the database set up with a sample document in the cloud, you are ready to start implementing the Firestore SDK in Xcode.

Creating & Working With Database References

Open up the MasterViewController.swift file in Xcode and add the following lines to import the library:

Here you are simply creating a listener variable that will allow you to trigger a connection to the database in real time when there is a change. You are also creating a DocumentSnapshot reference that will hold the temporary data snapshot.

Before continuing with the view controller, create another swift file, Task.swift, which will represent your data model:

The code snippet above includes a convenience property (dictionary) and method (init) that will make populating the model object easier. Switch back to the view controller, and declare a global setter variable which will constrain the base query to the top 50 entries in the tasks list. You will also be removing the listener once you set the query variable, as denoted in the didSet property below:

Reading Data in Real Time From Cloud Firestore

With the document reference in place, in viewWillAppear(_animated: Bool), associate the listener you created earlier with the results of the query snapshot, and retrieve a list of documents. This is done by calling the Firestore method query?.addSnapshotListener:

The closure above assigns the snapshot.documents by mapping the array iteratively and wrapping it to a new Task model instance object for each data item in the snapshot. So with just a few lines, you have successfully read in all the tasks from the cloud and assigned them to the global tasks array. 

To display the results, populate the followingTableViewdelegate methods:

At this stage, build and run the project and in the Simulator you should be able to observe data appearing in real time. Add data via the Firebase console and you should see it appear instantaneously in the app simulator. 

Data appearing in the app simulator

Creating, Updating and Deleting Data

After successfully reading content from the back-end, next you will create, update and delete data. The next example will illustrate how to update data, using a contrived example where the app will only let you mark an item as done by tapping on the cell. Note the collection.document(item.id).updateData(["done": !item.done]) closure property, which simply references a specific document ID, updating each of the fields in the dictionary:

To delete an item, call the document(item.id).delete() method:

Creating a new task will involve adding a new button in your Storyboard and connecting its IBAction to the view controller, creating an addTask(_ sender:) method. When a user presses the button, it will bring up an alert sheet where the user can add a new task name:

Complete the final part of the app by entering the following:

Build and run the app once more and, when the simulator appears, try adding in a few tasks, as well as marking a few as done, and finally test the delete function by removing some tasks. You can confirm that the stored data has been updated in real time by switching over to your Firebase database console and observing the collection and documents.

collection and documents in the console

Filtering and Compound Queries

So far, you've only worked with a simple query, without any specific filtering capabilities. To create slightly more robust queries, you can filter by specific values by making use of a whereField clause:

You can order and limit your query data, by making use of the order(by: ) and limit(to: ) methods as follows:

In the FirebaseDo app, you already made use of limit with the base query. In the above snippet, you also made use of another feature, compound queries, where both the order and limit are chained together. You can chain as many queries as you want, such as in the following example:

Conclusion

In this tutorial, you explored Google’s new MBaaS product, Cloud Firestore, and in the process created a simple task reminder app that demonstrates how easy it is for you to persist, synchronize, and query your data in the cloud. You learned about Firestore’s data schema structure in comparison to Firebase Realtime Database, and how to read and write data in real time, as well as updating and deleting data. You also learned how to perform simple as well as compound queries, and how to filter data. 

Cloud Firestore was created with the aim of providing the robustness of Firebase Realtime Database without many of the limitations mobile developers had to endure, especially as pertains to scalability and querying. We only scratched the surface of what you can accomplish with Firestore, and it's certainly worth exploring some of the more advanced concepts, such as Paginating Data with Query CursorsManaging Indexes, and Securing Your Data.

2018-05-11T15:00:00.000Z2018-05-11T15:00:00.000ZDoron Katz

Getting Started With Cloud Firestore for iOS

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-30910

Mobile coders have been taking advantage of Google’s Mobile Backend as a Service (MBaaS) platform Firebase Realtime Database for many years, helping them focus on building features for their apps without having to worry about the back-end infrastructure and database. By making it easy to store and persist data in the cloud and take care of authentication and security, Firebase allows coders to focus on the client side. 

Last year, Google announced yet another back-end database solution, Cloud Firestore, built from the ground up with the promise of greater scalability and intuitiveness. However, this introduced some confusion as to its place in relation to Google’s already existing flagship product, Firebase Realtime Database. This tutorial will outline the differences between the two platforms and the distinct advantages of each. You will learn how to work with Firestore document references, as well as reading, writing, updating and deleting data in real time, by building a simple reminders app.

Objectives of This Tutorial

This tutorial will expose you to Cloud Firestore. You'll learn how to leverage the platform for real-time database persistence and synchronization. We'll cover the following topics:

  • what Cloud Firestore is
  • the Firestore data model
  • setting up Cloud Firestore
  • creating and working with Cloud Firestore references
  • reading data in real time from Cloud Firestore
  • creating, updating and deleting data
  • filtering and compound queries

Assumed Knowledge

This tutorial assumes you have had some exposure to Firebase and a background developing with Swift and Xcode.

What Is Cloud Firestore?

Like Firebase Realtime Database, Firestore provides mobile and web developers with a cross-platform cloud solution to persist data in real time, regardless of network latency or internet connectivity, as well as seamless integration with the Google Cloud Platform suite of products. Along with these similarities, there are distinct advantages and disadvantages that differentiate one from the other. 

Data Model

On a fundamental level, Realtime Database stores data as one large, monolithic, hierarchical JSON tree, whereas Firestore organizes data in documents and collections, as well as sub-collections. This requires less denormalization. Storing data in one JSON tree has the benefits of simplicity when it comes to working with simple data requirements; however, it becomes more cumbersome at scale when working with more complex hierarchical data. 

Offline Support

Both products offer offline support, actively caching data in queues when there is latent or no network connectivity—synchronising local changes back to the back end when possible. Firestore supports offline synchronisation for web apps in addition to mobile apps, whereas the Realtime Database only enables mobile synchronization.

Queries and Transactions 

Realtime Database only supports limited sorting and filtering capabilities—you can only sort or filter on a property level, but not both, in a single query. Queries are also deep, meaning they return a large sub-tree of results back. The product only supports simple write and transaction operations which require a completion callback. 

Firestore, on the other hand, introduces index queries with compound sorting and filtering, allowing you to combine actions to create chain filters and sorting. You can also execute shallow queries returning sub-collections in lieu of the entire collection you would get with Realtime Database. Transactions are atomic in nature, whether you send a batch operation or single, with transactions repeating automatically until concluded. Additionally, Realtime Database only supports individual write transactions, whereas Firestore affords batch operations atomically.

Performance and Scalability

The Realtime Database, as you would expect, is quite robust and has low latency. However, databases are restricted to single regions, subject to zonal availability. Firestore, on the other hand, houses data horizontally across multiple zones and regions to ensure true global availability, scalability, and reliability. In fact, Google has promised that Firestore will be more reliable than Realtime Database. 

Another shortcoming of the Realtime Database is the limitation to 100,000 concurrent users (100,000 concurrent connections and 1,000 writes/second in a single database) after which you would have to shard your database (split your database into multiple databases) in order to support more users. Firestore automatically scales across multiple instances without you having to intervene. 

Designed from the ground up with scalability in mind, Firestore has a new schematic architecture that replicates data across multiple regions, takes care of authentication, and handles other security-related matters all within its client-side SDK. Its new data model is more intuitive than Firebase's, more closely resembling other comparable NoSQL database solutions like MongoDB, while providing a more robust querying engine. 

Security 

Finally, Realtime Database, as you know from our previous tutorials, manages security through cascading rules with separate validation triggers. This works with Firebase Database Rules, validating your data separately. Firestore, on the other hand, provides a simpler yet more powerful security model taking advantage of Cloud Firestore Security Rules and Identity and Access Management (IAM), with data validation excepted automatically.

The Firestore Data Model

Firestore is a NoSQL document-based database, consisting of collections of documents, each of which contains data. As it's a NoSQL database, you won’t get tables, rows, and other elements you would find in a relational database, but instead sets of key/value pairs that you would find within documents. 

You create documents and collections implicitly by assigning data to a document, and if the document or collection doesn’t exist, it will automatically be created for you, as the collection always has to be the root (first) node. Here is a simple Tasks example schema of the project you will be working on shortly, consisting of the Tasks collection, as well as numerous documents containing two fields, the name (string), and a flag for whether the task is done (boolean).

simple Tasks example schema of the project

Let’s decompose each of the elements so you can understand them better. 

Collections

Synonymous with database tables in the SQL world, collections contain one or more documents. Collections have to be the root elements in your schema and can only contain documents, not other collections. However, you can refer to a document which in turn refers to collections (sub-collections).

Diagram of document and collections

In the diagram above, a task consists of two primitive fields (name and done) as well as a sub-collection (sub-task) which consists of two primitive fields of its own. 

Documents

Documents consist of key/value pairs, with the values having one of the following types: 

  • primitive fields (such as strings, numbers, boolean)
  • complex nested objects (lists or arrays of primitives)
  • sub-collections

Nested objects are also called maps and can be represented as follows, within the document. The following is an example of a nested object and array, respectively:

For more information on the supported data types, refer to Google’s Data Types documentation. Next, you will set up a project to work with Cloud Firestore.

Setting Up the Project

If you have worked with Firebase before, a lot of this should be familiar to you. Otherwise, you will need to create an account in Firebase and follow the instructions in the ‘Set Up the Project’ section of our previous tutorial, Get Started With Firebase Authentication for iOS . 

To follow along with this tutorial, clone the tutorial project repo. Next, include the Firestore library byadding the following to your Podfile:

Enter the following in your terminal to build your library:

Next, switch to Xcode and open up the .xcworkspace file. Navigate to the AppDelegate.swift file and enter the following within the application:didFinishLaunchingWithOptions: method:

In your browser, go to the Firebase console and select the Database tab on the left. 

Database tab in the Firebase console

Make sure you select the option to Start in Test Mode so that you don’t have any security issues while we experiment, and heed the security notice when you do move your app into production. You are now ready to create a collection and some sample documents.

Adding a Collection and Sample Document

To start off, create an initial collection, Tasks, by selecting the Add Collection button and naming the collection, as illustrated below:

naming the collection

For the first document, you are going to leave the Document ID blank, which will auto-generate an ID for you. The document will simply consist of two fields: name and done.

Document with two fields

Save the document, and you should be able to confirm the collection and document along with the auto-generated ID:

collection and document with the auto-generated ID

With the database set up with a sample document in the cloud, you are ready to start implementing the Firestore SDK in Xcode.

Creating & Working With Database References

Open up the MasterViewController.swift file in Xcode and add the following lines to import the library:

Here you are simply creating a listener variable that will allow you to trigger a connection to the database in real time when there is a change. You are also creating a DocumentSnapshot reference that will hold the temporary data snapshot.

Before continuing with the view controller, create another swift file, Task.swift, which will represent your data model:

The code snippet above includes a convenience property (dictionary) and method (init) that will make populating the model object easier. Switch back to the view controller, and declare a global setter variable which will constrain the base query to the top 50 entries in the tasks list. You will also be removing the listener once you set the query variable, as denoted in the didSet property below:

Reading Data in Real Time From Cloud Firestore

With the document reference in place, in viewWillAppear(_animated: Bool), associate the listener you created earlier with the results of the query snapshot, and retrieve a list of documents. This is done by calling the Firestore method query?.addSnapshotListener:

The closure above assigns the snapshot.documents by mapping the array iteratively and wrapping it to a new Task model instance object for each data item in the snapshot. So with just a few lines, you have successfully read in all the tasks from the cloud and assigned them to the global tasks array. 

To display the results, populate the followingTableViewdelegate methods:

At this stage, build and run the project and in the Simulator you should be able to observe data appearing in real time. Add data via the Firebase console and you should see it appear instantaneously in the app simulator. 

Data appearing in the app simulator

Creating, Updating and Deleting Data

After successfully reading content from the back-end, next you will create, update and delete data. The next example will illustrate how to update data, using a contrived example where the app will only let you mark an item as done by tapping on the cell. Note the collection.document(item.id).updateData(["done": !item.done]) closure property, which simply references a specific document ID, updating each of the fields in the dictionary:

To delete an item, call the document(item.id).delete() method:

Creating a new task will involve adding a new button in your Storyboard and connecting its IBAction to the view controller, creating an addTask(_ sender:) method. When a user presses the button, it will bring up an alert sheet where the user can add a new task name:

Complete the final part of the app by entering the following:

Build and run the app once more and, when the simulator appears, try adding in a few tasks, as well as marking a few as done, and finally test the delete function by removing some tasks. You can confirm that the stored data has been updated in real time by switching over to your Firebase database console and observing the collection and documents.

collection and documents in the console

Filtering and Compound Queries

So far, you've only worked with a simple query, without any specific filtering capabilities. To create slightly more robust queries, you can filter by specific values by making use of a whereField clause:

You can order and limit your query data, by making use of the order(by: ) and limit(to: ) methods as follows:

In the FirebaseDo app, you already made use of limit with the base query. In the above snippet, you also made use of another feature, compound queries, where both the order and limit are chained together. You can chain as many queries as you want, such as in the following example:

Conclusion

In this tutorial, you explored Google’s new MBaaS product, Cloud Firestore, and in the process created a simple task reminder app that demonstrates how easy it is for you to persist, synchronize, and query your data in the cloud. You learned about Firestore’s data schema structure in comparison to Firebase Realtime Database, and how to read and write data in real time, as well as updating and deleting data. You also learned how to perform simple as well as compound queries, and how to filter data. 

Cloud Firestore was created with the aim of providing the robustness of Firebase Realtime Database without many of the limitations mobile developers had to endure, especially as pertains to scalability and querying. We only scratched the surface of what you can accomplish with Firestore, and it's certainly worth exploring some of the more advanced concepts, such as Paginating Data with Query CursorsManaging Indexes, and Securing Your Data.

2018-05-11T15:00:00.000Z2018-05-11T15:00:00.000ZDoron Katz

Introducing Fuse for Cross-Platform App Development

$
0
0

There's no shortage of tools when it comes to developing apps that work cross-platform. It originally started with PhoneGap, which then became Cordova. Then came the hybrid frameworks with near-native performance, like React Native and NativeScript. And more recently came Google's Flutter. 

My point is that there are a lot of those frameworks out there. You'll believe me if you just do a quick Google search of "cross-platform mobile development frameworks". If you're just beginning to develop mobile apps, it can be paralyzing. That's why it's important to get to know your options.

So today I'll be introducing you to Fuse, yet another platform for developing mobile apps that work cross-platform.

In this article, I'll be aiming to answer the following questions:

  • What is Fuse?
  • What are its pros and cons?
  • How does it work?
  • How does it compare to more popular alternatives such as React Native?

What Is Fuse?

Fuse is a platform for developing cross-platform apps with UX Markup and JavaScript. It's in the same category as React Native and NativeScript, but its main selling point is in the provision of tools that enable developers and designers collaborate in real time.

Fuse uses UX Markup, an XML-based language which provides the building blocks for the UI. It also allows you to specify how the different components would behave when users interact with them, thus the name "UX".

Another important thing to understand when you're getting started with Fuse is that it's not a browser-based platform like Cordova. So even though it allows you to use JavaScript code, not all JavaScript features that are available in a browser environment work. 

Fuse provides a decent collection of polyfills which allow you to do things like performing AJAX requests or setting an interval for executing a piece of code. Other than that, you're limited to the core JavaScript features.

Pros

  • Cross-platform: enables you to build apps that run on both Android and iOS devices.
  • Native performance: UX Markup is compiled to native code, which is why the performance is comparable to native (if not the same). The different effects and animations are OpenGL-accelerated, which makes for a top-notch user experience.
  • Declarative code: animations, effects, and transitions are declared via UX Markup. So things like scaling a button when it's clicked are managed purely via the UX Markup. This lets you focus your JavaScript code on things like making requests to APIs, performing calculations, and writing business logic.
  • Developer- and designer-friendly: Fuse uses technologies that web developers know and love: JavaScript for processing tasks and an XML-like language for the UX. The UX Markup they use for building the UI is very simple, which makes it easy to use, even for designers.
  • Good documentation: the different features and APIs are well documented. They also have a collection of examples, though it mostly showcases their UX. 
  • Extendable: Fuse uses a language called Uno to extend native functionality. This means that you can implement custom functionality yourself if you need native functionality that isn't exposed via Fuse's JavaScript APIs.

Cons

  • Young community: compared to React Native, Fuse's community is still young, and it's not really that active. They have a Slack channel and a forum. They also have a page for community packages, but when you look at the GitHub repos, there's not really much activity. There's also a lack of blog posts and tutorials about Fuse.
  • No support for existing JavaScript frameworks: Fuse only supports vanilla JavaScript. So if you're coming from Vue, React, or Angular and you want to use your skills on the Fuse platform, sadly that isn't possible.
  • No Linux support: You can't develop apps with Fuse if you're not on either Windows or macOS. 
  • No NPM support and package system: you can't use NPM to install and use existing JavaScript libraries. Though there are a few JavaScript libraries that are known to work, a platform isn't really complete without a package system that allows developers to install existing libraries which implement a specific functionality! 
  • No Native ES6 support: Fuse only supports ECMAScript 5.1 for writing JavaScript code. However, you can use a transpiler such as Babel to transpile your ES6 code to ES5.

How Does Fuse Work?

Under the hood, Fuse translates the UX Markup into native C++ code via the Uno compiler. Uno is the C#-like language which was used to write all of Fuse's core classes. So the UX Markup that you've written, together with the Fuse framework, is compiled to C++. After that, the native platform tools (Android Studio or Xcode) take that C++ code and compile the native app.

As for the JavaScript code, it's interpreted by a JavaScript VM at runtime. This means that the UI and the business logic are independent of each other. 

How Does Fuse Compare to React Native?

No introductory article about a new platform would be complete without comparing it to an existing platform. One platform which is comparable to Fuse is React Native. So we'll be comparing those two platforms based on the following criteria:

  • platform features
  • performance
  • code
  • extendability

Note that I'll only be comparing the free features of Fuse because React Native is a free platform.

Platform Features

Both Fuse and React Native come with the following features:

  • Hot reloading: changes to the code are automatically reflected in the app preview. However, if you compare how fast the UI updates happen, Fuse is clearly the winner. Their hot reload is almost instant.
  • JavaScript APIs for using native functionality: both Fuse and React Native allow you to access native device functionality such as the camera, geolocation, and push notifications through a JavaScript API. However, if you compare the documentation, it's clear that React Native has more APIs available.

Here are the features that are only available to Fuse:

  • Previewing on multiple devices: this lets the developers and designers preview the app on multiple devices with different form factors. The only requirement is that the development machine should be on the same wireless network as the devices. This is very useful because they'll immediately see if something doesn't look nice on a specific viewport.
  • Desktop preview: this allows the apps to be previewed on the desktop. Note that this will have very little impact on the performance of your computer. This is because it's not actually a device emulator. The desktop preview also lets you preview the app on multiple viewports. 
  • Preview App: if you want a quick way to preview your app, a client app for Android and iOS is also available. This lets you scan a QR code, which then opens the app on the device. You can do this for as many devices as you want. Changes to the source code are automatically reflected on every single one of these devices. 
Fuse App Preview

The only downside of the preview app, as opposed to the custom preview (the default way of previewing apps on a device), is that custom Uno code and third-party packages won't work. Geolocation, push notifications, and local notifications also won't work. You're better off using the custom preview in those cases. 

Performance

Fuse's performance is comparable to native because the UX Markup is compiled to native UI for the specific platform. And because all of the animations, effects, and transitions are defined in the markup itself, it already knows what to do when, for example, a button is pressed. As mentioned earlier, JavaScript runs on a separate thread, and it won't affect the UI performance at all. On top of that, Fuse uses OpenGL ES, which provides hardware-accelerated graphics performance. This means that different animations and effects can be used at the same time with no considerable effect on the UI performance. This makes Fuse a very suitable platform for developing mobile games.

On the other hand, React Native uses a bridge module for each platform. This module acts as a connection between the JavaScript APIs (including the UI components) and native functionality so they can communicate with each other. This makes React Native less performant than Fuse because of the communication cost between the native components and React Native's corresponding UI components. 

Code

Both Fuse and React Native offer a markup language as a building block for the UI. However, just by comparing the docs of Fuse and React Native, you can see that React Native has more components which represent their native counterparts.

Fuse's UX Markup allows you to describe the animations of a component whenever a user interacts with it. For example, here's how you might create a button which becomes three times as big as its original size while it's being pressed. Fuse takes care of how long the transition will be if you don't specify it:

On the other hand, React Native relies on JavaScript for almost everything. In the code below, the TextInput component relies on text to be initialized in the state. It then updates it every time the text inputted by the user changes: 

Here's how the default text for a text field is supplied:

Between the two, the way Fuse separates business logic from managing the UI is favorable in terms of collaboration between a developer and designer. UX Markup is simple enough for the designer to understand, so they can work on it while the developer handles the business logic. 

Extendability

Fuse allows you to use the same language that they use for all of their core classes as a way to extend native functionality. However, this does require you to have knowledge of how to use the native APIs in Android and iOS. From Fuse's Uno, you can use foreign code to implement native functionality. Currently, Uno only supports Objective-C for iOS and Java for Android. The resulting class is then exposed so that you can call it from JavaScript.

Similarly, React Native has a corresponding bridge module for both iOS and Android. This bridge module serves as the bridge between native functionality and JavaScript. Just like Fuse, this requires you to have a working knowledge of Objective-C or Java.

Both platforms also allow you to extend native UI components for each of your target platforms. So what if, for example, you want to implement a corresponding UI component for the native tooltip control on Android? You can do that on both Fuse and React Native.

Is Fuse Worth It?

If you ask my opinion, I'd say it depends on your specific use case. Fuse is definitely production-ready. Its main advantage is its performance and how fast you can go from an idea to a working prototype. Apps created with Fuse are highly performant, and it also makes collaboration between developers and designers really easy.

Its main disadvantage is its community. Fuse is clearly committed to open source with their release of the libraries which make Fuse work under the hood. However, they're still a small company (when compared to Facebook, at least). This means that they have to make money in one way or another. That's why they have professional paid plans which are more geared towards teams and the enterprise. So one can assume that most of their efforts will be put towards developing these paid tools. This leaves the open-source effort a second-class citizen. 

If you're working for a company that develops apps on a daily basis, then Fuse is a good option. But if you're an independent developer like me, we're mostly stuck with using the free plan. It's good enough for most use cases, but if you need custom native functionality, then you'll have to implement it yourself.

At the end of the day, it all depends on your use case. If you see your app not needing to work with a whole bunch of services, tools, and native APIs, then go for Fuse. Otherwise, don't. Not unless you have a lot of time to spare in developing custom native modules!

Conclusion

You should now have a good understanding of what Fuse is, how it works, its pros and cons, and if it's worth trying out as an alternative to more popular mobile development frameworks. In the second part of this series, we'll take a look at how to develop an app with Fuse.

2018-05-16T12:00:00.000Z2018-05-16T12:00:00.000ZWern Ancheta

Introducing Fuse for Cross-Platform App Development

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-30793

There's no shortage of tools when it comes to developing apps that work cross-platform. It originally started with PhoneGap, which then became Cordova. Then came the hybrid frameworks with near-native performance, like React Native and NativeScript. And more recently came Google's Flutter. 

My point is that there are a lot of those frameworks out there. You'll believe me if you just do a quick Google search of "cross-platform mobile development frameworks". If you're just beginning to develop mobile apps, it can be paralyzing. That's why it's important to get to know your options.

So today I'll be introducing you to Fuse, yet another platform for developing mobile apps that work cross-platform.

In this article, I'll be aiming to answer the following questions:

  • What is Fuse?
  • What are its pros and cons?
  • How does it work?
  • How does it compare to more popular alternatives such as React Native?

What Is Fuse?

Fuse is a platform for developing cross-platform apps with UX Markup and JavaScript. It's in the same category as React Native and NativeScript, but its main selling point is in the provision of tools that enable developers and designers collaborate in real time.

Fuse uses UX Markup, an XML-based language which provides the building blocks for the UI. It also allows you to specify how the different components would behave when users interact with them, thus the name "UX".

Another important thing to understand when you're getting started with Fuse is that it's not a browser-based platform like Cordova. So even though it allows you to use JavaScript code, not all JavaScript features that are available in a browser environment work. 

Fuse provides a decent collection of polyfills which allow you to do things like performing AJAX requests or setting an interval for executing a piece of code. Other than that, you're limited to the core JavaScript features.

Pros

  • Cross-platform: enables you to build apps that run on both Android and iOS devices.
  • Native performance: UX Markup is compiled to native code, which is why the performance is comparable to native (if not the same). The different effects and animations are OpenGL-accelerated, which makes for a top-notch user experience.
  • Declarative code: animations, effects, and transitions are declared via UX Markup. So things like scaling a button when it's clicked are managed purely via the UX Markup. This lets you focus your JavaScript code on things like making requests to APIs, performing calculations, and writing business logic.
  • Developer- and designer-friendly: Fuse uses technologies that web developers know and love: JavaScript for processing tasks and an XML-like language for the UX. The UX Markup they use for building the UI is very simple, which makes it easy to use, even for designers.
  • Good documentation: the different features and APIs are well documented. They also have a collection of examples, though it mostly showcases their UX. 
  • Extendable: Fuse uses a language called Uno to extend native functionality. This means that you can implement custom functionality yourself if you need native functionality that isn't exposed via Fuse's JavaScript APIs.

Cons

  • Young community: compared to React Native, Fuse's community is still young, and it's not really that active. They have a Slack channel and a forum. They also have a page for community packages, but when you look at the GitHub repos, there's not really much activity. There's also a lack of blog posts and tutorials about Fuse.
  • No support for existing JavaScript frameworks: Fuse only supports vanilla JavaScript. So if you're coming from Vue, React, or Angular and you want to use your skills on the Fuse platform, sadly that isn't possible.
  • No Linux support: You can't develop apps with Fuse if you're not on either Windows or macOS. 
  • No NPM support and package system: you can't use NPM to install and use existing JavaScript libraries. Though there are a few JavaScript libraries that are known to work, a platform isn't really complete without a package system that allows developers to install existing libraries which implement a specific functionality! 
  • No Native ES6 support: Fuse only supports ECMAScript 5.1 for writing JavaScript code. However, you can use a transpiler such as Babel to transpile your ES6 code to ES5.

How Does Fuse Work?

Under the hood, Fuse translates the UX Markup into native C++ code via the Uno compiler. Uno is the C#-like language which was used to write all of Fuse's core classes. So the UX Markup that you've written, together with the Fuse framework, is compiled to C++. After that, the native platform tools (Android Studio or Xcode) take that C++ code and compile the native app.

As for the JavaScript code, it's interpreted by a JavaScript VM at runtime. This means that the UI and the business logic are independent of each other. 

How Does Fuse Compare to React Native?

No introductory article about a new platform would be complete without comparing it to an existing platform. One platform which is comparable to Fuse is React Native. So we'll be comparing those two platforms based on the following criteria:

  • platform features
  • performance
  • code
  • extendability

Note that I'll only be comparing the free features of Fuse because React Native is a free platform.

Platform Features

Both Fuse and React Native come with the following features:

  • Hot reloading: changes to the code are automatically reflected in the app preview. However, if you compare how fast the UI updates happen, Fuse is clearly the winner. Their hot reload is almost instant.
  • JavaScript APIs for using native functionality: both Fuse and React Native allow you to access native device functionality such as the camera, geolocation, and push notifications through a JavaScript API. However, if you compare the documentation, it's clear that React Native has more APIs available.

Here are the features that are only available to Fuse:

  • Previewing on multiple devices: this lets the developers and designers preview the app on multiple devices with different form factors. The only requirement is that the development machine should be on the same wireless network as the devices. This is very useful because they'll immediately see if something doesn't look nice on a specific viewport.
  • Desktop preview: this allows the apps to be previewed on the desktop. Note that this will have very little impact on the performance of your computer. This is because it's not actually a device emulator. The desktop preview also lets you preview the app on multiple viewports. 
  • Preview App: if you want a quick way to preview your app, a client app for Android and iOS is also available. This lets you scan a QR code, which then opens the app on the device. You can do this for as many devices as you want. Changes to the source code are automatically reflected on every single one of these devices. 
Fuse App Preview

The only downside of the preview app, as opposed to the custom preview (the default way of previewing apps on a device), is that custom Uno code and third-party packages won't work. Geolocation, push notifications, and local notifications also won't work. You're better off using the custom preview in those cases. 

Performance

Fuse's performance is comparable to native because the UX Markup is compiled to native UI for the specific platform. And because all of the animations, effects, and transitions are defined in the markup itself, it already knows what to do when, for example, a button is pressed. As mentioned earlier, JavaScript runs on a separate thread, and it won't affect the UI performance at all. On top of that, Fuse uses OpenGL ES, which provides hardware-accelerated graphics performance. This means that different animations and effects can be used at the same time with no considerable effect on the UI performance. This makes Fuse a very suitable platform for developing mobile games.

On the other hand, React Native uses a bridge module for each platform. This module acts as a connection between the JavaScript APIs (including the UI components) and native functionality so they can communicate with each other. This makes React Native less performant than Fuse because of the communication cost between the native components and React Native's corresponding UI components. 

Code

Both Fuse and React Native offer a markup language as a building block for the UI. However, just by comparing the docs of Fuse and React Native, you can see that React Native has more components which represent their native counterparts.

Fuse's UX Markup allows you to describe the animations of a component whenever a user interacts with it. For example, here's how you might create a button which becomes three times as big as its original size while it's being pressed. Fuse takes care of how long the transition will be if you don't specify it:

On the other hand, React Native relies on JavaScript for almost everything. In the code below, the TextInput component relies on text to be initialized in the state. It then updates it every time the text inputted by the user changes: 

Here's how the default text for a text field is supplied:

Between the two, the way Fuse separates business logic from managing the UI is favorable in terms of collaboration between a developer and designer. UX Markup is simple enough for the designer to understand, so they can work on it while the developer handles the business logic. 

Extendability

Fuse allows you to use the same language that they use for all of their core classes as a way to extend native functionality. However, this does require you to have knowledge of how to use the native APIs in Android and iOS. From Fuse's Uno, you can use foreign code to implement native functionality. Currently, Uno only supports Objective-C for iOS and Java for Android. The resulting class is then exposed so that you can call it from JavaScript.

Similarly, React Native has a corresponding bridge module for both iOS and Android. This bridge module serves as the bridge between native functionality and JavaScript. Just like Fuse, this requires you to have a working knowledge of Objective-C or Java.

Both platforms also allow you to extend native UI components for each of your target platforms. So what if, for example, you want to implement a corresponding UI component for the native tooltip control on Android? You can do that on both Fuse and React Native.

Is Fuse Worth It?

If you ask my opinion, I'd say it depends on your specific use case. Fuse is definitely production-ready. Its main advantage is its performance and how fast you can go from an idea to a working prototype. Apps created with Fuse are highly performant, and it also makes collaboration between developers and designers really easy.

Its main disadvantage is its community. Fuse is clearly committed to open source with their release of the libraries which make Fuse work under the hood. However, they're still a small company (when compared to Facebook, at least). This means that they have to make money in one way or another. That's why they have professional paid plans which are more geared towards teams and the enterprise. So one can assume that most of their efforts will be put towards developing these paid tools. This leaves the open-source effort a second-class citizen. 

If you're working for a company that develops apps on a daily basis, then Fuse is a good option. But if you're an independent developer like me, we're mostly stuck with using the free plan. It's good enough for most use cases, but if you need custom native functionality, then you'll have to implement it yourself.

At the end of the day, it all depends on your use case. If you see your app not needing to work with a whole bunch of services, tools, and native APIs, then go for Fuse. Otherwise, don't. Not unless you have a lot of time to spare in developing custom native modules!

Conclusion

You should now have a good understanding of what Fuse is, how it works, its pros and cons, and if it's worth trying out as an alternative to more popular mobile development frameworks. In the second part of this series, we'll take a look at how to develop an app with Fuse.

2018-05-16T12:00:00.000Z2018-05-16T12:00:00.000ZWern Ancheta

15 Best Android App Templates of 2018

$
0
0

Android app templates have been gaining in popularity over the past few years, and that’s no wonder. They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

App templates are also an indispensable learning tool for novice developers who want to improve their coding skills by studying the building blocks of an app while building their own.

We've combed through the thousands of Android app templates available at CodeCanyon to find the 15 best available.

The templates we’ve chosen reflect the most popular Android app categories. Almost all are made with Android Studio, use Google Material Design, support AdMob, give users the option of removing banners and interstitial ads, and come with step-by-step instructions and/or video tutorials on how to configure the templates from scratch.  

1. Universal Android App

Hands down one of the best and most popular Android app templates is Universal Android App. This awesome app 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 into one customisable app.

Universal Android App

The template supports the most popular web content sources, like WordPress, YouTube, Facebook, RSS, etc.

User valvze says:

“From the minute of buying this product, I have had nothing but fun. It was an absolute joy creating a personalized app from this template and would definitely recommend this to anybody trying to learn programming. The app is built with easy to figure code and the design elements are fantastic as well. Customer service was quick to response to each of my queries. Would recommend.”

2. The City

Cities are complex spaces, and any app that helps locals and visitors alike navigate them is bound to be a hit. The City is a great app template for developers who want to create an app for their city featuring the most interesting sights, the best restaurants, cafés, bars, shops, and more.

The City

All the app data is stored in a local SQLite database, so the app works in offline mode. And the template has some great features like MapView to show place location, a featured category for recommended places, the ability to filter searches, a save history of searches, and much more.

Customers say: 

“The code is very well structured and clean, the documentation is excellent.”

3. Material Design UI 

Material Design UI is a cool and stylish Android UI template with five gorgeous themes that can be used to make any app project you’re working on more aesthetically appealing. The template themes target social, travel, media, and shopping apps, and there is a universal theme that can be used with a wider variety of apps. The template uses hundreds of UI elements that can be recombined endlessly to create a beautiful and unique looking app. 

Material Design UI

User gayuh says:

“The template contains many UI styles that are very useful when developing new UI for an Android app. Documentation is minimal, but design and code quality are fairly good, and customizability and flexibility are very good."

4. Dating App

Finding love in the 21st century often involves the Internet, and the appropriately named template Dating App is just what you need if you want to try your hand at creating your own online dating app.

Dating App

Built with Android Studio, the template's notable features include a beautiful gallery and user profiles. Users have the ability to comment, like, reply and send gifts, see potential dates that are nearby, make in-app purchases, send real-time direct messages with photos, and of course they can block other users.

Users say of the app: 

“My app has been updated to Google Play Store and is running fine” and “Very good documentation, easy to setup, perfect code quality, outstanding design.”

5. Universal Android WebView App

There seem to be no end of amazing content-rich websites on the internet, and though most of them are responsive and show well on mobile phones and tablets, some clients will want to convert their site into beautiful apps that allow their visitors to access key features easily and seamlessly.

Universal Android WebView App

Universal Android WebView App allows developers to do just that. It is compatible with WordPress and other web frameworks, is highly customisable and packed with features, and it supports HTML5, CSS3, JavaScript, jQuery, Bootstrap, and other web technologies.

Users say Universal Android WebView App is a:

“great template”, with “fast support and excellent documentation”.

6. Store Finder

When you’re out and about and you need to find the closest store to you for a particular item, having a store finder app on your mobile app is a godsend. This kind of indispensability has made the Store Finder app template popular among developers.

Store Finder

Made with Android Studio and material design, the app features a long list of must-have features like email and SMS integration, user ratings and reviews, Google directions, and social media logins. Users also have the ability to draw in the map, use map pins, share to Facebook and Twitter, and more.

Customer Seolio says: 

“The app design and code quality is second to none.”

7. Android News App

Android News App template is the go-to template for those looking to create a mobile news app for Android devices. Users can view the latest news in different categories, save articles as favourites, get notified about the latest articles, and more. It comes with an easy-to-use admin dashboard for modifying the news categories and other details.

Android News App

User jadeofheavens says:

“5 Stars: not just for the customer support but definitely for the code quality, features and documentation. A person like me who knows nothing about Android Studio made an app within half hour.”

8. Your Videos Channel

If you are a YouTuber, videographer or developer with clients who are videographers, Your Videos Channel app template may appeal to you because it essentially allows you to create an app dedicated to showing off your videos or a video collection of your choosing. The app, which has YouTube integration, uses PHP MySQL for the admin side and can manage unlimited categories and video uploads.

Your Videos Channel

User androbogor says:

“Outstanding experience! Good seller. Best support!”

9. My Social Network

Built in Android Studio, My Social Network template allows you to create your own personal social network app where you can publish posts, read the posts of friends, have a personal conversation with friends in real time, and more.

My Social Network

User Joespace says: 

"Very good app, well coded and well documented. It's easy to install if you follow the steps."

10. FlappyBot

Games are without a doubt one of the most popular app categories on Android devices, and the FlappyBot game app template is one of our most popular games. It's written in Java with Eclipse, and a narrated video tutorial is included for a quick start. 

The player touches the screen to move the flappy bird up, and the aim is to keep it alive as long as possible. The game saves the top ten high scores on the user’s device, and users can share their scores on Facebook.

FlappyBot

The template allows developers to edit the game by adding more obstacle columns, changing bird speeds or delays, etc.  

User Neogoapp says: 

“Good documentation and tutorial”.

11. Quizix

Keeping with the entertainment category, Quizix is a fabulous Android quiz app template that only came on the market at the beginning of 2018, but is already one of our best rated app templates. The template uses maths, text and/or photo questions, and has space for two to four answer options. 

Developers simply add their categories, sub-categories and questions in the back end, and the app formulates the quiz. Quizix uses the latest features of the Android platform and is AdMob Banner and Interstitials ready.

Quizix

User Alnoah says:

“I usually don't give ratings but decided to give so because I am fully satisfied with this product. Quality code, great backend and amazing job! I truly recommend this."

12. Your Radio App

Hands down the best radio app template to be found at CodeCanyon, Your Radio App is perfect for developers who want to create their own mobile Internet radio-streaming app. With a powerful admin panel, the app can manage unlimited radio stations and categories and supports many formats.

Your Radio App

User Save2011usa says:

“Excellent Radio app and excellent support! Thanks!”

13. Cookbook Recipe App

Create your own recipe application with the Cookbook Recipe App template. This native Android app template gives experienced and novice developers alike an easy way to make their own recipe app, as it doesn’t require programming skills and the code is easy to configure and customise.

Cookbook Recipe App

The app has many great built-in features like a drawer menu with categories, shopping list, favourites, a powerful search, Google Analytics, various animations and effects, and more.

Cookbook Recipe App stores recipes in a local SQLite database so users can run the app without an Internet connection.

User HiimNaru7o says:

“Great customer support. I had some bugs and they helped me to resolve them. Very cool guy. Highly recommended!”

14. HD Wallpaper

If you’ve been searching for the perfect template to create a great wallpaper app, look no further. The HD Wallpaper app template allows developers to create an app which delivers gorgeous wallpapers and backgrounds to the user’s Android device. 

The app features multiple galleries of high-resolution images, easy tap, swipe and scroll functions, and offline caching of wallpapers.

HD Wallpaper

User saidogame says:

“I like this code. It is a very good one and the support helps you and answers your questions. In my case I had a good support via Skype. I recommend purchasing this code and other codes from this developer.”

15. xMusic

xMusic will appeal to Android developers who are looking for a template to help them create an online-offline music player app. This app plays millions of free songs from SoundCloud via the SoundCloud API, but can switch to music from the user’s own library if they prefer. 

xMusic

Some of the great features the template offers are a powerful Equalizer with many preset music styles, support for sleep mode and a number of playlists, a powerful search, and much more.

User dajin says:

“Clean code, flexibility, customizability, design quality! Great! Awesome!”

Conclusion

These 15 best Android app templates of 2018 are just a small selection of hundreds of Android 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 Android apps and templates, then check out some of the ever-so-useful Android tutorials we have on offer.

2018-05-18T05:41:42.811Z2018-05-18T05:41:42.811ZNona Blackman

15 Best Android App Templates of 2018

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29643

Android app templates have been gaining in popularity over the past few years, and that’s no wonder. They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

App templates are also an indispensable learning tool for novice developers who want to improve their coding skills by studying the building blocks of an app while building their own.

We've combed through the thousands of Android app templates available at CodeCanyon to find the 15 best available.

The templates we’ve chosen reflect the most popular Android app categories. Almost all are made with Android Studio, use Google Material Design, support AdMob, give users the option of removing banners and interstitial ads, and come with step-by-step instructions and/or video tutorials on how to configure the templates from scratch.  

1. Universal Android App

Hands down one of the best and most popular Android app templates is Universal Android App. This awesome app 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 into one customisable app.

Universal Android App

The template supports the most popular web content sources, like WordPress, YouTube, Facebook, RSS, etc.

User valvze says:

“From the minute of buying this product, I have had nothing but fun. It was an absolute joy creating a personalized app from this template and would definitely recommend this to anybody trying to learn programming. The app is built with easy to figure code and the design elements are fantastic as well. Customer service was quick to response to each of my queries. Would recommend.”

2. The City

Cities are complex spaces, and any app that helps locals and visitors alike navigate them is bound to be a hit. The City is a great app template for developers who want to create an app for their city featuring the most interesting sights, the best restaurants, cafés, bars, shops, and more.

The City

All the app data is stored in a local SQLite database, so the app works in offline mode. And the template has some great features like MapView to show place location, a featured category for recommended places, the ability to filter searches, a save history of searches, and much more.

Customers say: 

“The code is very well structured and clean, the documentation is excellent.”

3. Material Design UI 

Material Design UI is a cool and stylish Android UI template with five gorgeous themes that can be used to make any app project you’re working on more aesthetically appealing. The template themes target social, travel, media, and shopping apps, and there is a universal theme that can be used with a wider variety of apps. The template uses hundreds of UI elements that can be recombined endlessly to create a beautiful and unique looking app. 

Material Design UI

User gayuh says:

“The template contains many UI styles that are very useful when developing new UI for an Android app. Documentation is minimal, but design and code quality are fairly good, and customizability and flexibility are very good."

4. Dating App

Finding love in the 21st century often involves the Internet, and the appropriately named template Dating App is just what you need if you want to try your hand at creating your own online dating app.

Dating App

Built with Android Studio, the template's notable features include a beautiful gallery and user profiles. Users have the ability to comment, like, reply and send gifts, see potential dates that are nearby, make in-app purchases, send real-time direct messages with photos, and of course they can block other users.

Users say of the app: 

“My app has been updated to Google Play Store and is running fine” and “Very good documentation, easy to setup, perfect code quality, outstanding design.”

5. Universal Android WebView App

There seem to be no end of amazing content-rich websites on the internet, and though most of them are responsive and show well on mobile phones and tablets, some clients will want to convert their site into beautiful apps that allow their visitors to access key features easily and seamlessly.

Universal Android WebView App

Universal Android WebView App allows developers to do just that. It is compatible with WordPress and other web frameworks, is highly customisable and packed with features, and it supports HTML5, CSS3, JavaScript, jQuery, Bootstrap, and other web technologies.

Users say Universal Android WebView App is a:

“great template”, with “fast support and excellent documentation”.

6. Store Finder

When you’re out and about and you need to find the closest store to you for a particular item, having a store finder app on your mobile app is a godsend. This kind of indispensability has made the Store Finder app template popular among developers.

Store Finder

Made with Android Studio and material design, the app features a long list of must-have features like email and SMS integration, user ratings and reviews, Google directions, and social media logins. Users also have the ability to draw in the map, use map pins, share to Facebook and Twitter, and more.

Customer Seolio says: 

“The app design and code quality is second to none.”

7. Android News App

Android News App template is the go-to template for those looking to create a mobile news app for Android devices. Users can view the latest news in different categories, save articles as favourites, get notified about the latest articles, and more. It comes with an easy-to-use admin dashboard for modifying the news categories and other details.

Android News App

User jadeofheavens says:

“5 Stars: not just for the customer support but definitely for the code quality, features and documentation. A person like me who knows nothing about Android Studio made an app within half hour.”

8. Your Videos Channel

If you are a YouTuber, videographer or developer with clients who are videographers, Your Videos Channel app template may appeal to you because it essentially allows you to create an app dedicated to showing off your videos or a video collection of your choosing. The app, which has YouTube integration, uses PHP MySQL for the admin side and can manage unlimited categories and video uploads.

Your Videos Channel

User androbogor says:

“Outstanding experience! Good seller. Best support!”

9. My Social Network

Built in Android Studio, My Social Network template allows you to create your own personal social network app where you can publish posts, read the posts of friends, have a personal conversation with friends in real time, and more.

My Social Network

User Joespace says: 

"Very good app, well coded and well documented. It's easy to install if you follow the steps."

10. FlappyBot

Games are without a doubt one of the most popular app categories on Android devices, and the FlappyBot game app template is one of our most popular games. It's written in Java with Eclipse, and a narrated video tutorial is included for a quick start. 

The player touches the screen to move the flappy bird up, and the aim is to keep it alive as long as possible. The game saves the top ten high scores on the user’s device, and users can share their scores on Facebook.

FlappyBot

The template allows developers to edit the game by adding more obstacle columns, changing bird speeds or delays, etc.  

User Neogoapp says: 

“Good documentation and tutorial”.

11. Quizix

Keeping with the entertainment category, Quizix is a fabulous Android quiz app template that only came on the market at the beginning of 2018, but is already one of our best rated app templates. The template uses maths, text and/or photo questions, and has space for two to four answer options. 

Developers simply add their categories, sub-categories and questions in the back end, and the app formulates the quiz. Quizix uses the latest features of the Android platform and is AdMob Banner and Interstitials ready.

Quizix

User Alnoah says:

“I usually don't give ratings but decided to give so because I am fully satisfied with this product. Quality code, great backend and amazing job! I truly recommend this."

12. Your Radio App

Hands down the best radio app template to be found at CodeCanyon, Your Radio App is perfect for developers who want to create their own mobile Internet radio-streaming app. With a powerful admin panel, the app can manage unlimited radio stations and categories and supports many formats.

Your Radio App

User Save2011usa says:

“Excellent Radio app and excellent support! Thanks!”

13. Cookbook Recipe App

Create your own recipe application with the Cookbook Recipe App template. This native Android app template gives experienced and novice developers alike an easy way to make their own recipe app, as it doesn’t require programming skills and the code is easy to configure and customise.

Cookbook Recipe App

The app has many great built-in features like a drawer menu with categories, shopping list, favourites, a powerful search, Google Analytics, various animations and effects, and more.

Cookbook Recipe App stores recipes in a local SQLite database so users can run the app without an Internet connection.

User HiimNaru7o says:

“Great customer support. I had some bugs and they helped me to resolve them. Very cool guy. Highly recommended!”

14. HD Wallpaper

If you’ve been searching for the perfect template to create a great wallpaper app, look no further. The HD Wallpaper app template allows developers to create an app which delivers gorgeous wallpapers and backgrounds to the user’s Android device. 

The app features multiple galleries of high-resolution images, easy tap, swipe and scroll functions, and offline caching of wallpapers.

HD Wallpaper

User saidogame says:

“I like this code. It is a very good one and the support helps you and answers your questions. In my case I had a good support via Skype. I recommend purchasing this code and other codes from this developer.”

15. xMusic

xMusic will appeal to Android developers who are looking for a template to help them create an online-offline music player app. This app plays millions of free songs from SoundCloud via the SoundCloud API, but can switch to music from the user’s own library if they prefer. 

xMusic

Some of the great features the template offers are a powerful Equalizer with many preset music styles, support for sleep mode and a number of playlists, a powerful search, and much more.

User dajin says:

“Clean code, flexibility, customizability, design quality! Great! Awesome!”

Conclusion

These 15 best Android app templates of 2018 are just a small selection of hundreds of Android 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 Android apps and templates, then check out some of the ever-so-useful Android tutorials we have on offer.

2018-05-18T05:41:42.811Z2018-05-18T05:41:42.811ZNona Blackman

Creating Your First App With Fuse

$
0
0

Now that you've learned the basic concepts of Fuse, it's time to put things into practice and build an app. In this tutorial, you'll learn how to develop an app using the Fuse framework. Specifically, you're going to learn the following:

  • How to code using UX Markup.
  • How to use the Observable, Timer, and Geolocation APIs.
  • How to preview an app using desktop preview and custom preview.

If you need a refresher on Fuse, check out my previous post in this series: Introducing Fuse for Cross-Platform App Development.

Prerequisites

To start working with Fuse, go to the downloads page and sign up for an account. You can also log in to an existing account if you have one. 

Fuse is available for both Windows and macOS. Download and install the correct installer for your platform. On the downloads page, they also point out the Fuse plugins available for various text editors. Install the one for your text editor. The Fuse plugins include code completion, goto definition, and viewing of logs generated from the app, all of which makes developing apps more convenient.

We'll also cover how to preview the app using custom preview. This requires Android Studio or Xcode to be installed on your computer.  

A basic understanding of web technologies such as HTML, CSS, and JavaScript is helpful but not required.

What You'll Be Creating

You'll be creating a stopwatch app which also measures the distance covered. The distance is measured using geolocation. The user can also create laps, and the individual distance and time for each lap will be displayed on the screen.

Here's what the app will look like:

Final Output HIIT Stopwatch

You can view the complete source code in the tutorial GitHub repo.

Creating a New Fuse Project

Once you have installed Fuse Studio, you should now be able to create a new Fuse project. Just open Fuse Studio and click on the New Fuse Project button. Enter the name of the project, and click Create:

Create a new Fuse project

This will create a new folder in the selected directory. Open that folder and open the MainView.ux file. By default, it will only have the <App> markup. Update it to include a <Text>, and then save the file:

The preview should now be updated with the text you specified:

Hello world output

That's the main development workflow in Fuse. Just save the changes to any of the files in the project directory, and they will automatically get reflected in the desktop preview. 

You can also see the logs in the bottom panel. You can trigger your own by using console.log(), like in the browser. The only difference is that you have to JSON.stringify() objects in order to see their value, since the console.log() implementation in Fuse can only output strings. 

UX Markup

Now we're ready to build the app. Open the MainView.ux file and remove the <Text> element from earlier. That way, we can start with a blank slate:

Including Fonts

Just like in an HTML document, the standard is to include the assets—things like fonts, stylesheets, and scripts—before the actual markup of the page. So add the following inside the <App> element:

This imports the font specified in the File attribute and gives it the name Thin. Note that this doesn't make it the default font for the whole page. If you want to use this font, you have to use its name (Thin) on the specific text you want to apply it to. 

You can download the font from the tutorial GitHub repo. After that, create an assets/fonts/robot folder inside the root project directory and put the .ttf file in it.

If you want to use another font, you can download it from dafont.com. That's where I downloaded the font for this app.

Next, we want to use icons inside the app. Fuse doesn't really have built-in elements and icon sets which allow you to do that. What it offers is a way to include existing icon fonts in your app. Since icon fonts are essentially fonts, we can use the same method for including fonts:

You can download the icon font from the GitHub repo or download it directly from fontawesome.com. Note that not all icons on fontawesome are free, so it's best to check the actual icon page before using it. If you see a "pro" label next to the icon, then you can't simply use it in your project without paying. 

Including JavaScript

Next, we need to include the JavaScript file for this page. We can do that using the <JavaScript> element:

Don't forget to create the scripts/MainView.js file at the root of the project directory. 

Creating New Components

To maximize code reuse, Fuse allows us to create custom components from existing ones. In the code below, we're using a <Panel> to create a custom button. Think of it like a div which acts as a container for other elements. In this case, we're using it as a reusable component for creating a button. 

Fuse comes with many elements. There are elements for laying out content such as the <Panel>, elements for showing user controls, pages and navigation, scripting and data, and primitives for building the UI. Each one has its own set of properties, allowing you to modify the data, presentation, and behavior.

To create a reusable component, add a ux:Class property to a presentation element that you'd like to use as a base. In this case, we're using a <Panel> as the base. You can then add some default styling. This is similar to how styling is done in CSS. Margin adds space outside of the container. Here we've only specified a single value, so this margin is applied on all sides of the panel. Color adds a background color to the element:

Inside the <Panel>, we want to show the button text. We want to make this into a reusable component, so we need a way to pass in properties for when we use this component later on. This allows us to achieve different results by only changing the properties. 

Inside the <Panel>, use the data type of the value you want to pass in as the name of the element, and then add the name of the property using ux:Property. You can then show the value supplied to the property by using {ReadProperty PropertyName}, where PropertyName is the value you supplied to ux:Property. This will allow you to supply a Text property whenever you're using the <ToggleBtn> component.

Next, we want to offer the user some sort of feedback while the button is being pressed. We can do that via triggers and animators. Triggers are basically the event listeners—in this case, <WhilePressed>. And animators are the animations or effects you want to perform while the trigger is active. The code below will make the button 10% bigger than its original size and change its color. Duration and DurationBack allow you to specify how long it takes for the animation to reach its peak and reach its end.

Next, we create the <IconBtn> component. As the name suggests, this is a button which only shows an icon as its content. This works the same way as the previous component, though there are a few new things we've done here. 

First is the ux:Name property. This allows us to give a name to a specific element so we can refer to it later. In this case, we're using it to change its Color property while the button is being pressed. 

We've also used a conditional element called <WhileTrue>. This allows us to disable the <WhilePressed> trigger when the value for is_running is a falsy one. We'll supply the value for this variable once we get to the JavaScript part. For now, know that this variable indicates whether the timer is currently running or not.

Main Content

We can now proceed with the main content. First, we wrap everything in a <StackPanel>. As the name suggests, this allows us to "stack" its children either vertically or horizontally. By default, it uses vertical orientation so we don't need to explicitly specify it: 

In the code above, we used four values for the Margin. Unlike CSS, the value distribution is left, top, right, bottom. If only two values are specified, it's left-right, top-bottom. You can use the selection tool in Fuse Studio to visualize the margins applied.

Next, we add a background image for the page. This accepts the file path to the background image you want to use. A StretchMode of Fill makes the background stretch itself to fill the entire screen:

You can download the background image I've used from the tutorial GitHub repo. Or you can find similar patterns on the Toptal website

Next, show the name of the app. Below it is the time-elapsed text field. This text needs to be updated frequently, so we need to turn it into a variable which can be updated via JavaScript. To output some text initialized in this page's JavaScript file, you need to wrap the variable name in curly braces. Later on, you'll see how the value for this variable is supplied from the JavaScript file:

Next, we use the <IconBtn> component that we created earlier—not unlike in a web environment where we use the ID of the font. In Fuse, you have to use the Unicode assigned to the icon font you want to use. You also need to use &#x as a prefix. When this button is pressed (called Clicked), the addLap() function declared in the JavaScript file is executed:

In Font Awesome, you can find the unicode of the icon font on its own page.

Right below the button for adding a new lap is some text which indicates that the button above is for adding new laps:

Next, show the button for starting and stopping the timer. This also executes a function which we will declare later:

Next, we need to output the laps added by the user. This includes the lap number, distance covered, and time spent. The <Each> element allows us to iterate through a collection of objects and display the individual properties for each object:

In the code above, we're using the <DockPanel> to wrap the contents for each item. This type of panel allows us to "dock" its children on different sides (top, left, right, and bottom) of the available space. By default, this positions its children directly on top of each other. To evenly space them out, you need to add the Alignment property. 

JavaScript Code

Now we're ready to add the JavaScript code. In Fuse, JavaScript is mainly used for the business logic and working with the device's native functionality. Effects, transitions, and animations for interacting with the UI are already handled by the UX Markup.

Start by importing all the APIs that we need. This includes Observable, which is mainly used for assigning variables in the UI. These variables can then be updated using JavaScript. Timer is the equivalent of the setTimeout and setInterval functions in the web version of JavaScript. GeoLocation allows us to get the user's current location:

Next, we initialize all the observable values that we'll be using. These are the variables that you have seen in the UX markup earlier. The values for these variables are updated throughout the lifetime of the app, so we make them an observable variable. This effectively allows us to update the contents of the UI whenever any of these values change:

After that, we can now set the initial values for the toggle button and timer text:

That's how you change the value of an observable variable. Since these are not inside any function, this should update the UI immediately when the app is launched.

Set the initial values for the timer, lap time, and location for each lap:

The toggle() function is used for starting and stopping the timer. When the timer is currently stopped and the user taps on the toggle button, that's the only time we reset the values for the timer and laps. This is because we want the user to see these values even after they stopped the timer. 

After that, get the user's current location and push it on the locations array. This allows us to compare it to the next location later, once the user adds a lap. Then, create a timer which executes every 10 milliseconds. We increment both the overall time and the lap_time for every execution. Then update the UI with the formatted value using the formatTimer() function:

When the user stops the timer, we delete it using the delete() method in the timer. This requires the timer_id that was returned when the timer was created:

Next is the function for formatting the timer. This works by converting the milliseconds into seconds and into minutes. We already know that this function is executed every 10 milliseconds. And the time is incremented by 1 every time it executes. So to get the milliseconds, we simply multiply the time by 10. From there, we just calculate the seconds and minutes based on the equivalent value for each unit of measurement:

Every time the user taps on the refresh button, the addLap() function is executed. This adds a new entry on top of the laps observable: 

Here's the function for getting the distance covered in meters. This uses the Haversine formula:

Don't forget to export all the observable values:

Geolocation Package

To keep things lightweight, Fuse doesn't really include all the packages that it supports by default. For things like geolocation and local notifications, you need to tell Fuse to include them when building the app. Open StopWatch.unoproj at the root of your project directory and include Fuse.GeoLocation under the Packages array:

This should instruct Fuse to include the Geolocation package whenever building the app for custom preview or for generating an installer. 

Setting Up for Custom Preview 

Before you can run the app on your iOS device, you need to add a bundle identifier to the app first. Open the StopWatch.unoproj file and add the following under iOS. This will be the unique identification for the app when it's submitted to the app store:

Next, on Xcode, log in with your Apple developer account. If you don't already have one, you can go to the Apple developer website and create one. It's actually free to develop and test apps on your iOS device. However, there are some limitations if you're not part of the developer program.

Once your account is created, go to Xcode preferences and add your Apple account. Then click on Manage Certificates and add a new certificate for iOS development. This certificate is used to ensure that the app is from a known source.

Once that's done, you should now be able to run the app on your device. Click on Preview > Preview on iOS in Fuse Studio and wait for it to launch Xcode. Once Xcode is open, select your device and click the play button. This will build the app and install it on your device. If there's a build error, it's most likely that the preview bundle identifier is not unique:

change the bundle ID

Changing the Bundle Identifier to something unique should solve the issue. Once the error under the signing section disappears, click on the play button again to rebuild the app. This should install the app on your device. 

However, you won't be able to open the app until you approve it. You can do that on your iOS device by going to Settings General Device Management and selecting the email associated with your Apple Developer account. Approve it, and that should unlock the app.

For Android, you should be able to preview the app without any additional steps.

Conclusion

That's it! In this tutorial, you've learned the basics of creating an app using the Fuse framework. Specifically, you've created a stopwatch app. By creating this app, you've learned how to work with Fuse's UX Markup and a few of Fuse's JavaScript APIs. You also learned how to use Fuse Studio to preview the app on your computer and your phone while developing it.

2018-05-22T18:00:00.000Z2018-05-22T18:00:00.000ZWern Ancheta

Creating Your First App With Fuse

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-30837

Now that you've learned the basic concepts of Fuse, it's time to put things into practice and build an app. In this tutorial, you'll learn how to develop an app using the Fuse framework. Specifically, you're going to learn the following:

  • How to code using UX Markup.
  • How to use the Observable, Timer, and Geolocation APIs.
  • How to preview an app using desktop preview and custom preview.

If you need a refresher on Fuse, check out my previous post in this series: Introducing Fuse for Cross-Platform App Development.

Prerequisites

To start working with Fuse, go to the downloads page and sign up for an account. You can also log in to an existing account if you have one. 

Fuse is available for both Windows and macOS. Download and install the correct installer for your platform. On the downloads page, they also point out the Fuse plugins available for various text editors. Install the one for your text editor. The Fuse plugins include code completion, goto definition, and viewing of logs generated from the app, all of which makes developing apps more convenient.

We'll also cover how to preview the app using custom preview. This requires Android Studio or Xcode to be installed on your computer.  

A basic understanding of web technologies such as HTML, CSS, and JavaScript is helpful but not required.

What You'll Be Creating

You'll be creating a stopwatch app which also measures the distance covered. The distance is measured using geolocation. The user can also create laps, and the individual distance and time for each lap will be displayed on the screen.

Here's what the app will look like:

Final Output HIIT Stopwatch

You can view the complete source code in the tutorial GitHub repo.

Creating a New Fuse Project

Once you have installed Fuse Studio, you should now be able to create a new Fuse project. Just open Fuse Studio and click on the New Fuse Project button. Enter the name of the project, and click Create:

Create a new Fuse project

This will create a new folder in the selected directory. Open that folder and open the MainView.ux file. By default, it will only have the <App> markup. Update it to include a <Text>, and then save the file:

The preview should now be updated with the text you specified:

Hello world output

That's the main development workflow in Fuse. Just save the changes to any of the files in the project directory, and they will automatically get reflected in the desktop preview. 

You can also see the logs in the bottom panel. You can trigger your own by using console.log(), like in the browser. The only difference is that you have to JSON.stringify() objects in order to see their value, since the console.log() implementation in Fuse can only output strings. 

UX Markup

Now we're ready to build the app. Open the MainView.ux file and remove the <Text> element from earlier. That way, we can start with a blank slate:

Including Fonts

Just like in an HTML document, the standard is to include the assets—things like fonts, stylesheets, and scripts—before the actual markup of the page. So add the following inside the <App> element:

This imports the font specified in the File attribute and gives it the name Thin. Note that this doesn't make it the default font for the whole page. If you want to use this font, you have to use its name (Thin) on the specific text you want to apply it to. 

You can download the font from the tutorial GitHub repo. After that, create an assets/fonts/robot folder inside the root project directory and put the .ttf file in it.

If you want to use another font, you can download it from dafont.com. That's where I downloaded the font for this app.

Next, we want to use icons inside the app. Fuse doesn't really have built-in elements and icon sets which allow you to do that. What it offers is a way to include existing icon fonts in your app. Since icon fonts are essentially fonts, we can use the same method for including fonts:

You can download the icon font from the GitHub repo or download it directly from fontawesome.com. Note that not all icons on fontawesome are free, so it's best to check the actual icon page before using it. If you see a "pro" label next to the icon, then you can't simply use it in your project without paying. 

Including JavaScript

Next, we need to include the JavaScript file for this page. We can do that using the <JavaScript> element:

Don't forget to create the scripts/MainView.js file at the root of the project directory. 

Creating New Components

To maximize code reuse, Fuse allows us to create custom components from existing ones. In the code below, we're using a <Panel> to create a custom button. Think of it like a div which acts as a container for other elements. In this case, we're using it as a reusable component for creating a button. 

Fuse comes with many elements. There are elements for laying out content such as the <Panel>, elements for showing user controls, pages and navigation, scripting and data, and primitives for building the UI. Each one has its own set of properties, allowing you to modify the data, presentation, and behavior.

To create a reusable component, add a ux:Class property to a presentation element that you'd like to use as a base. In this case, we're using a <Panel> as the base. You can then add some default styling. This is similar to how styling is done in CSS. Margin adds space outside of the container. Here we've only specified a single value, so this margin is applied on all sides of the panel. Color adds a background color to the element:

Inside the <Panel>, we want to show the button text. We want to make this into a reusable component, so we need a way to pass in properties for when we use this component later on. This allows us to achieve different results by only changing the properties. 

Inside the <Panel>, use the data type of the value you want to pass in as the name of the element, and then add the name of the property using ux:Property. You can then show the value supplied to the property by using {ReadProperty PropertyName}, where PropertyName is the value you supplied to ux:Property. This will allow you to supply a Text property whenever you're using the <ToggleBtn> component.

Next, we want to offer the user some sort of feedback while the button is being pressed. We can do that via triggers and animators. Triggers are basically the event listeners—in this case, <WhilePressed>. And animators are the animations or effects you want to perform while the trigger is active. The code below will make the button 10% bigger than its original size and change its color. Duration and DurationBack allow you to specify how long it takes for the animation to reach its peak and reach its end.

Next, we create the <IconBtn> component. As the name suggests, this is a button which only shows an icon as its content. This works the same way as the previous component, though there are a few new things we've done here. 

First is the ux:Name property. This allows us to give a name to a specific element so we can refer to it later. In this case, we're using it to change its Color property while the button is being pressed. 

We've also used a conditional element called <WhileTrue>. This allows us to disable the <WhilePressed> trigger when the value for is_running is a falsy one. We'll supply the value for this variable once we get to the JavaScript part. For now, know that this variable indicates whether the timer is currently running or not.

Main Content

We can now proceed with the main content. First, we wrap everything in a <StackPanel>. As the name suggests, this allows us to "stack" its children either vertically or horizontally. By default, it uses vertical orientation so we don't need to explicitly specify it: 

In the code above, we used four values for the Margin. Unlike CSS, the value distribution is left, top, right, bottom. If only two values are specified, it's left-right, top-bottom. You can use the selection tool in Fuse Studio to visualize the margins applied.

Next, we add a background image for the page. This accepts the file path to the background image you want to use. A StretchMode of Fill makes the background stretch itself to fill the entire screen:

You can download the background image I've used from the tutorial GitHub repo. Or you can find similar patterns on the Toptal website

Next, show the name of the app. Below it is the time-elapsed text field. This text needs to be updated frequently, so we need to turn it into a variable which can be updated via JavaScript. To output some text initialized in this page's JavaScript file, you need to wrap the variable name in curly braces. Later on, you'll see how the value for this variable is supplied from the JavaScript file:

Next, we use the <IconBtn> component that we created earlier—not unlike in a web environment where we use the ID of the font. In Fuse, you have to use the Unicode assigned to the icon font you want to use. You also need to use &#x as a prefix. When this button is pressed (called Clicked), the addLap() function declared in the JavaScript file is executed:

In Font Awesome, you can find the unicode of the icon font on its own page.

Right below the button for adding a new lap is some text which indicates that the button above is for adding new laps:

Next, show the button for starting and stopping the timer. This also executes a function which we will declare later:

Next, we need to output the laps added by the user. This includes the lap number, distance covered, and time spent. The <Each> element allows us to iterate through a collection of objects and display the individual properties for each object:

In the code above, we're using the <DockPanel> to wrap the contents for each item. This type of panel allows us to "dock" its children on different sides (top, left, right, and bottom) of the available space. By default, this positions its children directly on top of each other. To evenly space them out, you need to add the Alignment property. 

JavaScript Code

Now we're ready to add the JavaScript code. In Fuse, JavaScript is mainly used for the business logic and working with the device's native functionality. Effects, transitions, and animations for interacting with the UI are already handled by the UX Markup.

Start by importing all the APIs that we need. This includes Observable, which is mainly used for assigning variables in the UI. These variables can then be updated using JavaScript. Timer is the equivalent of the setTimeout and setInterval functions in the web version of JavaScript. GeoLocation allows us to get the user's current location:

Next, we initialize all the observable values that we'll be using. These are the variables that you have seen in the UX markup earlier. The values for these variables are updated throughout the lifetime of the app, so we make them an observable variable. This effectively allows us to update the contents of the UI whenever any of these values change:

After that, we can now set the initial values for the toggle button and timer text:

That's how you change the value of an observable variable. Since these are not inside any function, this should update the UI immediately when the app is launched.

Set the initial values for the timer, lap time, and location for each lap:

The toggle() function is used for starting and stopping the timer. When the timer is currently stopped and the user taps on the toggle button, that's the only time we reset the values for the timer and laps. This is because we want the user to see these values even after they stopped the timer. 

After that, get the user's current location and push it on the locations array. This allows us to compare it to the next location later, once the user adds a lap. Then, create a timer which executes every 10 milliseconds. We increment both the overall time and the lap_time for every execution. Then update the UI with the formatted value using the formatTimer() function:

When the user stops the timer, we delete it using the delete() method in the timer. This requires the timer_id that was returned when the timer was created:

Next is the function for formatting the timer. This works by converting the milliseconds into seconds and into minutes. We already know that this function is executed every 10 milliseconds. And the time is incremented by 1 every time it executes. So to get the milliseconds, we simply multiply the time by 10. From there, we just calculate the seconds and minutes based on the equivalent value for each unit of measurement:

Every time the user taps on the refresh button, the addLap() function is executed. This adds a new entry on top of the laps observable: 

Here's the function for getting the distance covered in meters. This uses the Haversine formula:

Don't forget to export all the observable values:

Geolocation Package

To keep things lightweight, Fuse doesn't really include all the packages that it supports by default. For things like geolocation and local notifications, you need to tell Fuse to include them when building the app. Open StopWatch.unoproj at the root of your project directory and include Fuse.GeoLocation under the Packages array:

This should instruct Fuse to include the Geolocation package whenever building the app for custom preview or for generating an installer. 

Setting Up for Custom Preview 

Before you can run the app on your iOS device, you need to add a bundle identifier to the app first. Open the StopWatch.unoproj file and add the following under iOS. This will be the unique identification for the app when it's submitted to the app store:

Next, on Xcode, log in with your Apple developer account. If you don't already have one, you can go to the Apple developer website and create one. It's actually free to develop and test apps on your iOS device. However, there are some limitations if you're not part of the developer program.

Once your account is created, go to Xcode preferences and add your Apple account. Then click on Manage Certificates and add a new certificate for iOS development. This certificate is used to ensure that the app is from a known source.

Once that's done, you should now be able to run the app on your device. Click on Preview > Preview on iOS in Fuse Studio and wait for it to launch Xcode. Once Xcode is open, select your device and click the play button. This will build the app and install it on your device. If there's a build error, it's most likely that the preview bundle identifier is not unique:

change the bundle ID

Changing the Bundle Identifier to something unique should solve the issue. Once the error under the signing section disappears, click on the play button again to rebuild the app. This should install the app on your device. 

However, you won't be able to open the app until you approve it. You can do that on your iOS device by going to Settings General Device Management and selecting the email associated with your Apple Developer account. Approve it, and that should unlock the app.

For Android, you should be able to preview the app without any additional steps.

Conclusion

That's it! In this tutorial, you've learned the basics of creating an app using the Fuse framework. Specifically, you've created a stopwatch app. By creating this app, you've learned how to work with Fuse's UX Markup and a few of Fuse's JavaScript APIs. You also learned how to use Fuse Studio to preview the app on your computer and your phone while developing it.

2018-05-22T18:00:00.000Z2018-05-22T18:00:00.000ZWern Ancheta

Code an Image Gallery Android App With Picasso

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

Picasso is a popular open-source Android library for loading both local and remote images. Learn how to easily use it for handling your image loading needs. 

1. What Is Picasso?

Picasso (name inspired by the famous French artist Pablo Picasso) is a very popular open-source Android library for loading images in your Android app. According to the official docs, it states:

...Picasso allows for hassle-free image loading in your application—often in one line of code!

Note that Picasso uses OkHttp (a network library from the same developer) under the hood to load the images over the internet. 

2. So Why Use Picasso?

Now you have learned what Picasso is all about, the next question you might ask is why use it?

Developing your own media loading and display functionality in Java or Kotlin can be a real pain: you have to take care of caching, decoding, managing network connections, threading, exception handling, and more. Picasso is an easy to use, well planned, well documented, and thoroughly tested library that can save you a lot of precious time—and save you some headaches. 

Here are many of the common pitfalls of loading images on Android that are dealt with for you by Picasso, according to the official docs:

  • handling ImageView recycling and download cancellation in an adapter
  • complex image transformations with minimal memory use
  • automatic memory and disk caching

Adding images to your app can make your Android app come alive. So in this tutorial, we'll learn about Picasso 2 by building a simple image gallery app. It will load the images via the internet and display them as thumbnails in a RecyclerView, and when a user clicks on an image, it will open a detail activity containing the larger image. 

A sample project (in Kotlin) for this tutorial can be found on our GitHub repo so you can easily follow along.

Good artists copy, great artists steal. — Pablo Picasso

3. Prerequisites

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

Fire up Android Studio and create a new project (you can name it PicassoDemo) with an empty activity called MainActivity. Make sure to also check the Include Kotlin support check box.

Android Studios Add an Activity to Mobile dialog

4. Declare Dependencies

After creating a new project, specify the following dependencies in your build.gradle. At the time of writing, the latest version of Picasso is 2.71828

Or with Maven:

Make sure you sync your project after adding Picasso and the RecyclerView v7 artifacts.

5. Add Internet Permission

Because Picasso is going to perform a network request to load images via the internet, we need to include the permission INTERNET in our AndroidManifest.xml

So go do that now!

Note that this is only required if you're going to load images from the internet. This is not required if you are only loading images locally on the device. 

6. Create the Layout

We'll start by creating our RecyclerView inside the activity_main.xml layout file. 

Creating the Custom Item Layout

Next, let's create the XML layout (item_image.xml) that will be used for each item (ImageView) within the RecyclerView

Now that we have created the layouts needed for our simple gallery app, the next step is to create the RecyclerView adapter for populating data. Before we do that, though, let's create our simple data model. 

7. Create a Data Model

We are going to define a simple data model for our RecyclerView. This model implements Parcelable for high-performance transport of data from one component to another in Android. In our case, data will be transported from SunsetGalleryActivity to SunsetPhotoActivity

Note that this model SunsetPhoto has only a single field called url (for demo purposes), but you can have more if you want. This class implements Parcelable, which means we have to override some methods. 

We can make use of Android Studio IDEA to generate these methods for us, but the downside to this is maintenance. How? Anytime we add any new fields to this class, we might forget to explicitly update the constructor and writeToParcel methods, which can lead to some bugs if we don't update the methods.  

Now, to circumvent updating or writing these boilerplate methods, Kotlin 1.1.14 introduced the @Parcelize annotation. This annotation will help us generate the writeToParcel, writeFromParcel, and describeContents methods automatically under the hood for us. 

Now, our code SunsetPhoto class is just two lines! Awesome! 

Remember to add the following code to your app module build.gradle:

In addition, I included a companion object (or static method in Java) getSunsetPhotos() in the SunsetPhoto model class that will simply return an ArrayList of SunsetPhoto when called.

8. Create the Adapter

We'll create an adapter to populate our RecyclerView with data. We'll also implement a click listener to open the detail activity—SunsetPhotoActivity—passing it an instance of SunsetPhoto as an intent extra. The detail activity will show a close-up of the image. We'll create it in a later section.

Notice that we used the apply extension function to put an object as extra to the intent. As a reminder, the apply function returns the object passed to it as an argument (i.e. the receiver object). 

9. Loading Images From a URL

We're going to need Picasso to do its job in this section—not to paint us a work of art, but to fetch images from the internet and display them. We'll display these images individually in their respective ImageViews inside our RecyclerView onBindViewHolder() method as the user scrolls the app. 

Step by step, here's what the calls to Picasso are doing:

The get() Method

This returns the global Picasso instance (singleton instance) initialized with the following default configurations: 

  • LRU memory cache of 15% the available application RAM.
  • Disk cache of 2% storage space up to 50MB but no less than 5MB. Note: this is only available on API 14+.
  • Three download threads for disk and network access.

Note that if these settings do not meet the requirements of your application, you're free to construct your own Picasso instance with full control of these configurations by using Picasso.Builder

Finally, you call the build() method to return you a Picasso instance with your own configurations. 

It's recommended you do this in your Application.onCreate and then set it as the singleton instance with Picasso.setSingletonInstance in that method—to make sure that the Picasso instance is the global one.

The load() Method 

load(String path) starts an image request using the specified path. This path can be a remote URL, file resource, content resource, or Android resource.

  • placeholder(int placeholderResId): a local placeholder resource id or drawable to be used while the image is being loaded and then displayed. It serves as a good user experience to display a placeholder image while the image is downloading.  

Note that Picasso first checks if the image requested is in the memory cache, and if it is, it displays the image from there (we'll discuss caching in Picasso more in a later section).

Other Methods

  • error(int errorResId): a drawable to be used if the requested image could not be loaded—probably because the website is down. 
  • noFade(): Picasso always fades in the image to be displayed into the ImageView. If you don't want this fade-in animation, simply call the noFade() method. 
  • into(ImageView imageView): the target image view into which the image will be placed.

Image Resizing and Transformation

If the server you are requesting the image from doesn't give you the image you need in the required size, you can easily resize that image using resize(int targetWidth, int targetHeight). Calling this method resizes the image and then displays it on the ImageView. Note that the dimensions are in pixels (px), not dp. 

You can pass in an Android dimension resource for both the width and height using the method resizeDimen(int targetWidthResId, int targetHeightResId). This method will convert the dimension size to raw pixels and then call resize() under the hood—passing the converted sizes (in pixels) as arguments. 

Note that these resize methods won't respect aspect ratio. In other words, your image aspect ratio can be distorted. 

Fortunately, Picasso gives us some useful methods to solve this issue: 

  • centerCrop(): scales the image uniformly (maintaining the image's aspect ratio) so that the image fills up the given area, with as much of the image showing as possible. If needed, the image will be cropped horizontally or vertically to fit. Calling this method crops an image inside of the bounds specified by resize().
  • centerInside(): scales the image so that both dimensions are equal to or less than the requested bounds. This will center an image inside of the bounds specified by resize()
  • onlyScaleDown(): only resize an image if the original image size is bigger than the target size specified by resize().
  • fit(): attempt to resize the image to fit exactly into the target ImageView's bounds.

Image Rotation

Picasso has an easy API to rotate an image and then display that image. The rotate(float degrees) method rotates the image by the specified degrees.

In the example above, this would rotate the image by 90 degrees. The rotate(float degrees, float pivotX, float pivotY) method rotates the image by the specified degrees around a pivot point.

Here we are going to rotate the image by 30 degrees around the pivot point 200, 100 pixels. 

Transformation

Apart from just manipulating an image by rotating it, Picasso also gives us the option to apply a custom transformation to an image before displaying it.  

You simply create a class that implements the Picasso Transformation interface. You then have to override two methods: 

  • Bitmap transform(Bitmap source): this transforms the source bitmap into a new bitmap. 
  • String key(): returns a unique key for the transformation, used for caching purposes.

After you're done creating your custom transformation, you simply execute it by invoking transform(Transformation transformation) on your Picasso instance. Note that you can also pass a list of Transformation to transform()

Here, I applied a circle crop transformation to the image from the Picasso Transformations open-source Android library. This library has many transformations you can apply to an image with Picasso—including transformations for blurring or grey-scaling an image. Go check it out if you want to apply some cool transformations to your images.  

10. Initializing the Adapter

Here, we simply create our RecyclerView with GridLayoutManager as the layout manager, initialize our adapter, and bind it to the RecyclerView

11. Creating the Detail Activity

Create a new activity and name it SunsetPhotoActivity. We get the SunsetPhoto extra and load the image—inside onStart()—with Picasso as we did before. 

The Detail Layout

Here's a layout to display the detail activity. It just displays an ImageView that will show the full-resolution version of the loaded image. 

12. Caching Mechanism in Picasso

If you observe carefully, you'll notice that when you revisit an image that was previously loaded, it loads even faster than before. What made it faster? It's Picasso's caching mechanism, that's what.

Here is what's going on under the hood. After an image has been loaded once from the internet, Picasso will cache it both in memory and on disk, saving repeated network requests and permitting faster retrieval of the image. When that image is needed again, Picasso will first check if the image is available in memory, and if it's there, it will return it immediately. If that image is not in memory, Picasso will check the disk next, and if it's there, it returns it. If it's not there, Picasso will finally do a network request for that image and display it. 

In summary, here's what goes on (under the hood) for an image request: memory -> disk -> network. 

Depending on your application, though, you might want to avoid caching—for example, if the images being displayed are likely to change often and not be reloaded.

So How Do You Disable Caching? 

You can avoid memory caching by calling memoryPolicy(MemoryPolicy.NO_CACHE). This will simply skip the memory cache lookup when processing an image request. 

Note that there is another enum: MemoryPolicy.NO_STORE. This is useful if you are very certain that you will only request an image once. Applying this will also not store the image in the memory cache—thereby not forcing out other bitmaps from the memory cache. 

But be very aware that the image will still be cached on the disk—to prevent that also, you use networkPolicy(@NonNull NetworkPolicy policy, @NonNull NetworkPolicy... additional), which takes one or more of the following enum values:

  • NetworkPolicy.NO_CACHE: skips checking the disk cache and forces loading through the network.
  • NetworkPolicy.NO_STORE: skips storing the result into the disk cache.
  • NetworkPolicy.OFFLINE: forces the request through the disk cache only, skipping the network.

To avoid both memory and disk caching altogether, just call both methods one after the other:

13. Request Listeners

In Picasso, you can implement a listener or callback to monitor the status of the request you made as the image loads. Only one of these methods will be called if you implement the Target interface on a request. 

  • void onBitmapFailed(e: Exception?, errorDrawable: Drawable?): triggered whenever the image could not be successfully loaded. Here, we can access the exception that was thrown. 
  • void onBitmapLoaded(Bitmap bitmap, LoadedFrom from): fired whenever an image has been successfully loaded. Here, we get the Bitmap to show the user. 
  • void onPrepareLoad(Drawable placeHolderDrawable): invoked right before your request is submitted. 

Here you could also show and then hide a progress dialog if you had one. 

There is another callback listener you can implement if you want, called Callback. This interface has just two methods: onSuccess() and onError(Exception e). The former is called when the image request load was successful, and the later is called when there is an error in processing the request. 

Going back to our image gallery app (inside SunsetPhotoActivity), let's modify the display a little by using a Callback object that will set the bitmap to the ImageView and also change the background colour of the layout by extracting the dark and vibrant colour of our image using the Android Palette API

So include the palette artifact in your app module's build.gradle:

Let's now implement the Callback interface in our Picasso request. 

14. Testing the App

Finally, you can run the app! Click on a thumbnail to get a full-sized version of the image.

Final app result

15. Prioritizing Requests

When you want to load different images at the same time on the same screen, you have the option to order which one is more important than the other. In other words, you can load important images first. 

You simply call priority() on your Picasso request instance and pass in any of the enums: Priority.LOW, Priority.NORMAL, or Priority.HIGH

16. Tagging Requests

By tagging your Picasso requests, you can resume, pause, or cancel requests which are associated with specific tags. Depending on your use case, you can tag your requests with a string or objects that should define the scope of the request as a Context, an Activity, or a Fragment. You can easily tag a Picasso request by calling tag(@NonNull Object tag) on one. Pass it an instance of Object which serves as the tag. 

Here are the following operations you can perform on tagged Picasso requests:

  • pauseTag(Object tag): pause all requests associated with the given tag. 
  • resumeTag(Object tag): resume paused requests with the given tag.
  • cancelTag(Object tag): cancel any existing requests with the given tag.

Though tagging your requests gives you some control over your requests, you should be very careful when using tags because of the potential for memory leaks. Here's what the official documentation says:

Picasso will keep a reference to the tag for as long as this tag is paused and/or has active requests. Look out for potential leaks.

Loading From the File System

It's straightforward to load images locally in your app.

Conclusion

Nice job! In this tutorial, you've built a complete image gallery app with Picasso, and along the way you've learned how the library works and how you can integrate it into your own project. 

You've also learned how to display both local and remote images, tagging requests, prioritizing requests, and how to apply image transformations like resizing. Not only that, but you've seen how easy it is to enable and disable caching, error handling, and custom request listeners. 

To learn more about Picasso, you can refer to its official documentation. To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

2018-05-24T13:00:00.000Z2018-05-24T13:00:00.000ZChike Mgbemena

Code an Image Gallery Android App With Picasso

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-30966
Final product image
What You'll Be Creating

Picasso is a popular open-source Android library for loading both local and remote images. Learn how to easily use it for handling your image loading needs. 

1. What Is Picasso?

Picasso (name inspired by the famous French artist Pablo Picasso) is a very popular open-source Android library for loading images in your Android app. According to the official docs, it states:

...Picasso allows for hassle-free image loading in your application—often in one line of code!

Note that Picasso uses OkHttp (a network library from the same developer) under the hood to load the images over the internet. 

2. So Why Use Picasso?

Now you have learned what Picasso is all about, the next question you might ask is why use it?

Developing your own media loading and display functionality in Java or Kotlin can be a real pain: you have to take care of caching, decoding, managing network connections, threading, exception handling, and more. Picasso is an easy to use, well planned, well documented, and thoroughly tested library that can save you a lot of precious time—and save you some headaches. 

Here are many of the common pitfalls of loading images on Android that are dealt with for you by Picasso, according to the official docs:

  • handling ImageView recycling and download cancellation in an adapter
  • complex image transformations with minimal memory use
  • automatic memory and disk caching

Adding images to your app can make your Android app come alive. So in this tutorial, we'll learn about Picasso 2 by building a simple image gallery app. It will load the images via the internet and display them as thumbnails in a RecyclerView, and when a user clicks on an image, it will open a detail activity containing the larger image. 

A sample project (in Kotlin) for this tutorial can be found on our GitHub repo so you can easily follow along.

Good artists copy, great artists steal. — Pablo Picasso

3. Prerequisites

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

Fire up Android Studio and create a new project (you can name it PicassoDemo) with an empty activity called MainActivity. Make sure to also check the Include Kotlin support check box.

Android Studios Add an Activity to Mobile dialog

4. Declare Dependencies

After creating a new project, specify the following dependencies in your build.gradle. At the time of writing, the latest version of Picasso is 2.71828

Or with Maven:

Make sure you sync your project after adding Picasso and the RecyclerView v7 artifacts.

5. Add Internet Permission

Because Picasso is going to perform a network request to load images via the internet, we need to include the permission INTERNET in our AndroidManifest.xml

So go do that now!

Note that this is only required if you're going to load images from the internet. This is not required if you are only loading images locally on the device. 

6. Create the Layout

We'll start by creating our RecyclerView inside the activity_main.xml layout file. 

Creating the Custom Item Layout

Next, let's create the XML layout (item_image.xml) that will be used for each item (ImageView) within the RecyclerView

Now that we have created the layouts needed for our simple gallery app, the next step is to create the RecyclerView adapter for populating data. Before we do that, though, let's create our simple data model. 

7. Create a Data Model

We are going to define a simple data model for our RecyclerView. This model implements Parcelable for high-performance transport of data from one component to another in Android. In our case, data will be transported from SunsetGalleryActivity to SunsetPhotoActivity

Note that this model SunsetPhoto has only a single field called url (for demo purposes), but you can have more if you want. This class implements Parcelable, which means we have to override some methods. 

We can make use of Android Studio IDEA to generate these methods for us, but the downside to this is maintenance. How? Anytime we add any new fields to this class, we might forget to explicitly update the constructor and writeToParcel methods, which can lead to some bugs if we don't update the methods.  

Now, to circumvent updating or writing these boilerplate methods, Kotlin 1.1.14 introduced the @Parcelize annotation. This annotation will help us generate the writeToParcel, writeFromParcel, and describeContents methods automatically under the hood for us. 

Now, our code SunsetPhoto class is just two lines! Awesome! 

Remember to add the following code to your app module build.gradle:

In addition, I included a companion object (or static method in Java) getSunsetPhotos() in the SunsetPhoto model class that will simply return an ArrayList of SunsetPhoto when called.

8. Create the Adapter

We'll create an adapter to populate our RecyclerView with data. We'll also implement a click listener to open the detail activity—SunsetPhotoActivity—passing it an instance of SunsetPhoto as an intent extra. The detail activity will show a close-up of the image. We'll create it in a later section.

Notice that we used the apply extension function to put an object as extra to the intent. As a reminder, the apply function returns the object passed to it as an argument (i.e. the receiver object). 

9. Loading Images From a URL

We're going to need Picasso to do its job in this section—not to paint us a work of art, but to fetch images from the internet and display them. We'll display these images individually in their respective ImageViews inside our RecyclerView onBindViewHolder() method as the user scrolls the app. 

Step by step, here's what the calls to Picasso are doing:

The get() Method

This returns the global Picasso instance (singleton instance) initialized with the following default configurations: 

  • LRU memory cache of 15% the available application RAM.
  • Disk cache of 2% storage space up to 50MB but no less than 5MB. Note: this is only available on API 14+.
  • Three download threads for disk and network access.

Note that if these settings do not meet the requirements of your application, you're free to construct your own Picasso instance with full control of these configurations by using Picasso.Builder

Finally, you call the build() method to return you a Picasso instance with your own configurations. 

It's recommended you do this in your Application.onCreate and then set it as the singleton instance with Picasso.setSingletonInstance in that method—to make sure that the Picasso instance is the global one.

The load() Method 

load(String path) starts an image request using the specified path. This path can be a remote URL, file resource, content resource, or Android resource.

  • placeholder(int placeholderResId): a local placeholder resource id or drawable to be used while the image is being loaded and then displayed. It serves as a good user experience to display a placeholder image while the image is downloading.  

Note that Picasso first checks if the image requested is in the memory cache, and if it is, it displays the image from there (we'll discuss caching in Picasso more in a later section).

Other Methods

  • error(int errorResId): a drawable to be used if the requested image could not be loaded—probably because the website is down. 
  • noFade(): Picasso always fades in the image to be displayed into the ImageView. If you don't want this fade-in animation, simply call the noFade() method. 
  • into(ImageView imageView): the target image view into which the image will be placed.

Image Resizing and Transformation

If the server you are requesting the image from doesn't give you the image you need in the required size, you can easily resize that image using resize(int targetWidth, int targetHeight). Calling this method resizes the image and then displays it on the ImageView. Note that the dimensions are in pixels (px), not dp. 

You can pass in an Android dimension resource for both the width and height using the method resizeDimen(int targetWidthResId, int targetHeightResId). This method will convert the dimension size to raw pixels and then call resize() under the hood—passing the converted sizes (in pixels) as arguments. 

Note that these resize methods won't respect aspect ratio. In other words, your image aspect ratio can be distorted. 

Fortunately, Picasso gives us some useful methods to solve this issue: 

  • centerCrop(): scales the image uniformly (maintaining the image's aspect ratio) so that the image fills up the given area, with as much of the image showing as possible. If needed, the image will be cropped horizontally or vertically to fit. Calling this method crops an image inside of the bounds specified by resize().
  • centerInside(): scales the image so that both dimensions are equal to or less than the requested bounds. This will center an image inside of the bounds specified by resize()
  • onlyScaleDown(): only resize an image if the original image size is bigger than the target size specified by resize().
  • fit(): attempt to resize the image to fit exactly into the target ImageView's bounds.

Image Rotation

Picasso has an easy API to rotate an image and then display that image. The rotate(float degrees) method rotates the image by the specified degrees.

In the example above, this would rotate the image by 90 degrees. The rotate(float degrees, float pivotX, float pivotY) method rotates the image by the specified degrees around a pivot point.

Here we are going to rotate the image by 30 degrees around the pivot point 200, 100 pixels. 

Transformation

Apart from just manipulating an image by rotating it, Picasso also gives us the option to apply a custom transformation to an image before displaying it.  

You simply create a class that implements the Picasso Transformation interface. You then have to override two methods: 

  • Bitmap transform(Bitmap source): this transforms the source bitmap into a new bitmap. 
  • String key(): returns a unique key for the transformation, used for caching purposes.

After you're done creating your custom transformation, you simply execute it by invoking transform(Transformation transformation) on your Picasso instance. Note that you can also pass a list of Transformation to transform()

Here, I applied a circle crop transformation to the image from the Picasso Transformations open-source Android library. This library has many transformations you can apply to an image with Picasso—including transformations for blurring or grey-scaling an image. Go check it out if you want to apply some cool transformations to your images.  

10. Initializing the Adapter

Here, we simply create our RecyclerView with GridLayoutManager as the layout manager, initialize our adapter, and bind it to the RecyclerView

11. Creating the Detail Activity

Create a new activity and name it SunsetPhotoActivity. We get the SunsetPhoto extra and load the image—inside onStart()—with Picasso as we did before. 

The Detail Layout

Here's a layout to display the detail activity. It just displays an ImageView that will show the full-resolution version of the loaded image. 

12. Caching Mechanism in Picasso

If you observe carefully, you'll notice that when you revisit an image that was previously loaded, it loads even faster than before. What made it faster? It's Picasso's caching mechanism, that's what.

Here is what's going on under the hood. After an image has been loaded once from the internet, Picasso will cache it both in memory and on disk, saving repeated network requests and permitting faster retrieval of the image. When that image is needed again, Picasso will first check if the image is available in memory, and if it's there, it will return it immediately. If that image is not in memory, Picasso will check the disk next, and if it's there, it returns it. If it's not there, Picasso will finally do a network request for that image and display it. 

In summary, here's what goes on (under the hood) for an image request: memory -> disk -> network. 

Depending on your application, though, you might want to avoid caching—for example, if the images being displayed are likely to change often and not be reloaded.

So How Do You Disable Caching? 

You can avoid memory caching by calling memoryPolicy(MemoryPolicy.NO_CACHE). This will simply skip the memory cache lookup when processing an image request. 

Note that there is another enum: MemoryPolicy.NO_STORE. This is useful if you are very certain that you will only request an image once. Applying this will also not store the image in the memory cache—thereby not forcing out other bitmaps from the memory cache. 

But be very aware that the image will still be cached on the disk—to prevent that also, you use networkPolicy(@NonNull NetworkPolicy policy, @NonNull NetworkPolicy... additional), which takes one or more of the following enum values:

  • NetworkPolicy.NO_CACHE: skips checking the disk cache and forces loading through the network.
  • NetworkPolicy.NO_STORE: skips storing the result into the disk cache.
  • NetworkPolicy.OFFLINE: forces the request through the disk cache only, skipping the network.

To avoid both memory and disk caching altogether, just call both methods one after the other:

13. Request Listeners

In Picasso, you can implement a listener or callback to monitor the status of the request you made as the image loads. Only one of these methods will be called if you implement the Target interface on a request. 

  • void onBitmapFailed(e: Exception?, errorDrawable: Drawable?): triggered whenever the image could not be successfully loaded. Here, we can access the exception that was thrown. 
  • void onBitmapLoaded(Bitmap bitmap, LoadedFrom from): fired whenever an image has been successfully loaded. Here, we get the Bitmap to show the user. 
  • void onPrepareLoad(Drawable placeHolderDrawable): invoked right before your request is submitted. 

Here you could also show and then hide a progress dialog if you had one. 

There is another callback listener you can implement if you want, called Callback. This interface has just two methods: onSuccess() and onError(Exception e). The former is called when the image request load was successful, and the later is called when there is an error in processing the request. 

Going back to our image gallery app (inside SunsetPhotoActivity), let's modify the display a little by using a Callback object that will set the bitmap to the ImageView and also change the background colour of the layout by extracting the dark and vibrant colour of our image using the Android Palette API

So include the palette artifact in your app module's build.gradle:

Let's now implement the Callback interface in our Picasso request. 

14. Testing the App

Finally, you can run the app! Click on a thumbnail to get a full-sized version of the image.

Final app result

15. Prioritizing Requests

When you want to load different images at the same time on the same screen, you have the option to order which one is more important than the other. In other words, you can load important images first. 

You simply call priority() on your Picasso request instance and pass in any of the enums: Priority.LOW, Priority.NORMAL, or Priority.HIGH

16. Tagging Requests

By tagging your Picasso requests, you can resume, pause, or cancel requests which are associated with specific tags. Depending on your use case, you can tag your requests with a string or objects that should define the scope of the request as a Context, an Activity, or a Fragment. You can easily tag a Picasso request by calling tag(@NonNull Object tag) on one. Pass it an instance of Object which serves as the tag. 

Here are the following operations you can perform on tagged Picasso requests:

  • pauseTag(Object tag): pause all requests associated with the given tag. 
  • resumeTag(Object tag): resume paused requests with the given tag.
  • cancelTag(Object tag): cancel any existing requests with the given tag.

Though tagging your requests gives you some control over your requests, you should be very careful when using tags because of the potential for memory leaks. Here's what the official documentation says:

Picasso will keep a reference to the tag for as long as this tag is paused and/or has active requests. Look out for potential leaks.

Loading From the File System

It's straightforward to load images locally in your app.

Conclusion

Nice job! In this tutorial, you've built a complete image gallery app with Picasso, and along the way you've learned how the library works and how you can integrate it into your own project. 

You've also learned how to display both local and remote images, tagging requests, prioritizing requests, and how to apply image transformations like resizing. Not only that, but you've seen how easy it is to enable and disable caching, error handling, and custom request listeners. 

To learn more about Picasso, you can refer to its official documentation. To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

2018-05-24T13:00:00.000Z2018-05-24T13:00:00.000ZChike Mgbemena

10 Best React Native App Templates of 2018

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29602

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.

2018-05-29T14:36:24.000Z2018-05-29T14:36:24.000ZNona Blackman

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!

2018-05-30T13:45:38.000Z2018-05-30T13:45:38.000ZNona Blackman

15 Best iOS App Templates of 2018

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29163

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!

2018-05-30T13:45:38.000Z2018-05-30T13:45:38.000ZNona Blackman

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.

2018-06-01T13:26:55.000Z2018-06-01T13:26:55.000ZDoron Katz

Building a Shopping List Application With CloudKit: Adding Records

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24731

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 9 and Swift 4. If you are using an older version of Xcode, then keep in mind that you might be 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? Read this introductory tutorial to CocoaPods to 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 9.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.

Open the Identity Inspector on the right and change Class to ListsViewController

Step 2: Adding a Table View

When the user opens the application, they're 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.

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 an 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 to 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: preparing 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 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 the 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 the 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 straightforward. The methods related to the view lifecycle 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.

2018-06-01T13:26:55.000Z2018-06-01T13:26:55.000ZDoron Katz
Viewing all 1836 articles
Browse latest View live