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

Swift From Scratch: An Introduction to Functions

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

To get anything done in Swift, you need to learn the ins and outs of functions. Functions are exceptionally powerful and flexible in Swift. The basics are simple, especially if you've worked with other programming languages before. But because of Swift's flexible syntax, functions can become confusing if you're not familiar with the basics. 

In this article, we focus on the basics first. Then we'll go on to explore the more complex syntax and use cases in the next article. It's important that you don't skim the basics as they are essential to understand where a function's power comes from. Let's start by dissecting the anatomy of a function in Swift with an example.

1. Learn by Example

A function is nothing more than a block of code that can be executed whenever it's needed. Let's look at an example of the basic anatomy of a Swift function. Fire up Xcode and create a new playground. Add the following function definition to the playground.

A function begins with the func keyword and is followed by the name of the function, printHelloWorld in our example. As in many other languages, the name of the function is followed by a pair of parentheses that contain the function's parameters—the input to the function.

The body of the function is wrapped in a pair of curly braces. The printHelloWorld() function contains a single statement that prints the string Hello World! to the standard output. This is what a basic function looks like in Swift. The syntax is simple, clean, and minimalist.

You can invoke the function by typing the name of the function, followed by a pair of parentheses.

2. Parameters

Let's make the above example a bit more complex by adding parameters to the function definition. This simply means that we provide the function with input values it can use in the function's body. In the following example, we define the printMessage(message:) function, which accepts one parameter, message, of type String.

A function can accept multiple parameters or input values. The parameters are wrapped by the parentheses that follow the function's name. The name of the parameter is followed by a colon and the parameter's type. As you remember, this is very similar to declaring a variable or constant. It simply says that the message parameter is of typeString.

Instead of printing a hard-coded string as we did in the printHelloWorld() function, we print the message parameter's value. This makes the function flexible and more useful.

Invoking the function is very similar to what we saw earlier. The only difference is that we pass in an argument when invoking the function.

Note that the terms parameters and arguments are often used interchangeably, but there is a subtle, semantic difference in Swift. In Swift, parameters are the values specified in the function definition, while arguments are the values passed to the function when it is invoked.

Multiple Parameters

As I mentioned earlier, the syntax of functions is very flexible, and it shouldn't surprise you that it's perfectly possible to pass multiple arguments to a function. In the next example, we create a variation on the printMessage(message:times:) function that allows us to print the message multiple times.

While the name of the function is identical to that of the original printMessage(message:) function, the function's type is different. 

It's important you understand the previous sentence. Read it again.

Each function has a type, consisting of the parameter types and the return type. We'll explore return types in a moment. Functions can have the same name as long as their type is different, as shown by the previous two function definitions.

The type of the first function is (String) -> (), while the type of the second function is(String, Int) -> (). The name of both functions is the same. Don't worry about the -> symbol. Its meaning will become clear in a few moments when we discuss return types.

The second printMessage(message:times:) function defines two parameters, message of type String and times of type Int. This definition illustrates one of the features Swift has adopted from Objective-C, readable function and method names. While the name of the function is printMessage, it's easy to understand what the function is supposed to do by reading the names of the function's parameters.

In the second printMessage(message:times:) function, we create a for-in loop to print the message string times times. We use the half-open range operator, ..<, as we saw earlier in this series.

Invoking a Function

When we start typing printMessage in the playground, Xcode displays both functions in the autocompletion menu. Thanks to the function's type, it's easy to choose the function we're interested in. Calling the second printMessage(message:times:) function is as simple as:

Default Values

One of my favorite features is the ability to define default values for parameters. This may sound silly if you're coming from a language that has had this feature for ages, but this is pretty great if you've been working with C and Objective-C for many years.

In short, Swift allows developers to define default values for the parameters of a function. Let's define a new function that prints the current date in a specific format. Make sure you add the following import statement at the top of your playground to import the UIKit framework.

Let's first define the printDate(date:format:) function without making use of default values for any of the parameters.

If you're not familiar with the Foundation framework and you don't understand what's happening in the function body, then that's fine. The focus of this example isn't on the implementation of formatting a date. In printDate(date:format:), we use the value of the format parameter to format the value of date. If we don't pass in a value for the format parameter, the compiler throws an error.

A Function Argument Is Missing

We can remedy this by defining a default value for the function's second parameter, as shown in the updated function definition below.

Defining a default value is as simple as specifying a value in the list of parameters in the function's definition. The result is that the compiler no longer complains and the error disappears.

Even though we have specified a default value for the format parameter, we can still pass in a value if we want to.

Note that Apple recommends positioning parameters with a default value at the end of the list of parameters. This is certainly a good idea and common in most other programming languages that support optional parameters.

3. Return Type

The functions we've seen so far don't return anything to us when we invoke them. Let's make the printDate(date:format:) function more useful by returning the formatted date as a string, instead of printing the formatted date in the function's body. This requires two changes, as you can see below.

The first thing we change is the function's definition. After the list of parameters, we specify the return type, String. The return type is preceded by the -> symbol. If you've worked with CoffeeScript, then this will look familiar.

Instead of printing the formatted date using the print(_:separator:terminator:) function, we use the return keyword to return the value from the function. That's all we need to do. Let's try it out.

We invoke the printDate(date:format:) function, store the returned value in the constant formattedDate, and print the value of formattedDate in the standard output. Note that the name of the printDate(date:format:) function no longer reflects what it does, so you may want to change it to formatDate instead.

No Return Type

The other functions we've defined in this tutorial didn't have a return type. When a function doesn't have a return type, it isn't necessary to include the -> symbol in the function definition.

A few paragraphs earlier, I told you that none of the functions we had defined returned a value to us. That's actually not entirely true. Let me explain the nitty-gritty details with an experiment. Add the following line to your playground and see what happens.

The Compiler Shows a Warning

This is interesting. Swift doesn't have a problem that we store the return value of the printHelloWorld() function in a constant, but it does warn us that the type of the returned value is not what we might think it is.

What's happening here? Every function in Swift returns a value, even if we don't define a return type in the function definition. When a function doesn't explicitly specify a return type, the function implicitly returns Void, which is equivalent to an empty tuple, or () for short. You can see this in the playground's output pane and it is also mentioned in the warning the compiler outputs.

We can get rid of the above warning by explicitly declaring the type of value, an empty tuple. I agree that it's not very useful to store an empty tuple in a constant, but it illustrates to you that every function has a return value.

Tuples

Another great feature of Swift is the ability to return multiple values from a function by returning a tuple. The following example illustrates how this works. Let me repeat that it's not important that you understand how the timeComponentsForDate(date:) function does its job. The focus is the return value of the function, a tuple with three elements.

The function accepts one argument, a Date instance, and returns a tuple with three labeled values. Labeling the tuple's values is only for convenience; it is possible to omit the labels.

However, as the following example illustrates, labeling the values of the tuple returned from the function is very convenient and makes your code easier to understand.

It's also possible to return an optional value from a function if there are scenarios in which the function has no value to return. This is as simple as defining the return type of the function as optional, as shown below.

Conclusion

In this tutorial, we explored the basics of functions in Swift. It's important that you understand the syntax of functions, because in the next article we'll explore more advanced functions that build on what we covered in this tutorial.

I encourage you to read the article again if necessary and, more importantly, write a few functions in a playground to become familiar with the syntax. The basics are easy to understand, but you only get the hang of them by practicing.

If you want to learn how to use Swift 3 to code real-world apps, check out our course Create iOS Apps With Swift 3. Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. 

 


2017-03-10T19:15:24.948Z2017-03-10T19:15:24.948ZBart Jacobs

Create a Pokémon GO Style Augmented Reality Game With Vuforia: Image Targets

$
0
0

In this tutorial we'll dive back into the Vuforia Augmented Reality (AR) library, exploring one of its most interesting resources—the Image Target. We'll expand on the Shoot the Cubes game that we created in earlier lessons, adding a new level where the player needs to defend their base from attacking cubes. 

 

This tutorial can be completed alone, although if you want an introduction to AR with Vuforia and Unity3D, check out the earlier posts in the series.

Image Targets

Any kind of image can be a Vuforia Image Target. However, the more detailed and intricate the image, the better it will be recognized by the algorithm. 

A lot of factors will be part of the recognizing calculation, but basically the image must have a reasonable level of contrast, resolution, and distinguishing elements. A blue sky photograph wouldn't work very well, but a picture of some grass would work gracefully. Image Targets can be shipped with the application, uploaded to the application through the cloud, or directly created in the app by the user.

Adding a Target

Let’s begin by adding an ImageTarget element to our Unity project. 

First, download the course assets from the button in the sidebar. Then, in your Unity project, create a new scene called DefendTheBase: in the Project window, select the Scenes folder and click on Create> Scene. Now open that scene and remove all the default scene objects from the hierarchy.

Next we'll add a light and camera. Click on Add> Light> Directional Light to add a directional light. Select this new light and set Soft Shadow as the Shadow Type option. 

After that, drag and drop an ARCamera object from Vuforia> Prefabs. Select the ARCamera object and in the inspector panel, set the App License Key created on the Vuforia developer page (see the first tutorial for instructions). Select DEVICE_TRACKING for the World Center Mod.

Finally, drag and drop an ImageTargetto the hierarchy from Vuforia> Prefabs.

Now we have to add a Vuforia Database. First, navigate to https://developer.vuforia.com/target-manager. Click on Add Database and choose a name.

There are three types of Database to choose from:

  1. Device: The Database is saved on the device and all targets are updated locally.
  2. Cloud: Database on the Vuforia servers.
  3. VuMark: Database exclusive to VuMark targets. It is also saved on the device.

In this case, choose the Device option and click on create.

Select the new database so we can start adding targets to it. Now it is time to add targets to the database. For now, we’ll just use the Single Image option.

Navigate to the previously downloaded files, pick ImageTarget1, and set its Width to 1 and click on Add. (Note: If you prefer to create your own Image Target, read the guide first.)

Vuforia Database

Now you can download the database, selecting Unity Editor as the chosen platform. Open the file and select all elements to be imported. We must also prepare our Unity scene to recognize the ImageTarget with this database we have created.

In the Unity editor, click on the ImageTarget object. First, find and expand Image Target Behavior in the object inspector. Select a Type of Predefined. Choose the image target we created earlier for Database. Finally, make sure that the Enable Extended Tracking and Enable Smart Terrain options are both disabled.

Image Target settings

The ImageTarget prefab is made of a series of components, including some scripts like Image Target Behavior, Turn Off Behavior, and Default Tracker Event Handler. If you want to deeply understand how the system works, read those scripts and try to understand their relationship to other components. 

For this tutorial, we won't dig too deep, though. We’ll only need to concentrate on the Default Tracker Event Handler, which receives calls when the image target tracking status changes. So let’s use this script as a base to create our own script behavior.

Create a copy of this script that we can extend. First select Default Tracker Event Handler, click on options and select Edit Script. Now, make a copy of the script. If you’re using MonoDevelop, click File> Save As and save as ImageTargetBehavior, saving it in the Scripts folder.

The TargetBehaviorScript Script

We won’t need the Vuforia namespace in our script. Remove the line “namespace Vuforia” and the brackets. That means we'll need to explicitly reference the Vuforia namespace when we want to access its classes: 

The most important method in this class will be the OnTrackableStateChanged method that receives calls when the image target is found or lost by the camera device. According to the target status, it calls OnTrackingFound or OnTrackingLost, and we’ll need to edit those methods as well. But first, let’s think about how we want the image target to behave. 

In this game, the user will defend a base that appears on an image target. Let’s consider the following game mechanics:

  • Once the target is recognized by the system, the base appears and enemies start to spawn and fly toward the base in a kamikaze style.
  • Every time an enemy hits the base, the base will take some damage and the enemy will be destroyed.
  • To win the game the user must shoot and destroy all enemies before the base is destroyed.
  • If the image target is lost (is no longer visible from the device camera), the game will start a countdown timer. If the timer gets to zero, the game is lost. While the target is lost, all enemies will stop advancing toward the base.

So we’ll need to adapt those game mechanics on top of what we built in the last tutorial. We'll create the enemy spawning logic in the next section with an empty object named _SpawnController, using the same logic adopted in the first part of the game.

For now, let's look at the tracking found logic.

Back in the Unity editor, we can create the base object that will be spawned by the spawn controller. 

First, on the ImageTarget object, disable the Default Trackable Event Handler script.

Next, click on Add Component and select the Target Behavior Script. From the Hierarchy panel, right click on ImageTarget and create a new cube named "Base". This cube should be inserted inside the ImageTarget object.

Make sure that the Base has Box Collider and Mesh Renderer enabled. 

Optionally, you could also insert a Plane object inside the ImageTarget using the ImageTarget submitted earlier in Vuforia as a texture. This would create an interesting effect, projecting shadows from the target and creating a richer experience.

Hierarchy and Image Target final settings

Adapting the SpawnScript

Now we will adapt the _SpawnController used in the last tutorial. Save the current scene and open ShootTheCubesMain from the last tutorial. In the Hierarchy panel, select the _SpawnController and drag it to the Prefabs folder to make it a Unity Prefab.

Save this new scene and reopen DefendTheBase. Drag _SpawnController from the prefabs folder to the Hierarchy panel. With the _SpawnController selected, click on Add Tag on the Inspector panel. Name the new tag _SpawnController and apply it to the object. 

In the Project window, select the Cube element in the Prefab folder and set its Tag, back on its inspector, to 'Enemy'.

Set Cubes tag to Enemy

Finally, open the Scripts folder and open SpawnScript. We need to make this script adapt itself to the loaded scene.

Next, we need to create two public methods to receive calls from TargetBehaviorScript when the target is found or lost: 

  • BaseOn (Vector3 basePosition) will be called when the target is found by the camera and the Base object is shown. It will change the spawning position, start the process, and inform all cubes that were previously added to the stage that the base is visible.

  • The BaseOff() method will be used when the target is lost. It will stop the staging process and inform all cube elements that the base was lost. 

The SetPosition (System.Nullable<Vector3> pos) uses the target’s current position to modify the object x, y, and z axes, and it can also receive a null value when the scene loaded is ShootTheCubesMain.

InformBaseOnToCubes() and InformBaseOffToCubes() are responsible for informing all staged cubes of the current base status.

The SpawnLoop() and SpawnElement() methods are using almost the same logic as the last tutorial.

Creating the Enemies

Now we’ll need to create some enemies. We'll use the Cube object that we created in the last tutorial, making some modifications to its script.

In the Prefabs folder, add a Cube object to the hierarchy. Then select the object and edit the CubeBehaviorScript.

We’ll preserve almost the same logic in this script, but with the following differences:

  • The Cube will pursue the Base when the target is found by the camera.
  • When the Cube hits the Base, it will destroy itself and give some damage to the Base.
  • The script needs to know the name of the scene loaded and adapt itself accordingly. 

If the scene's name is DefendTheBase, it must find the Base object and start to move towards it.

The CubeSettings() also need to adapt according to the scene loaded. The Cube only orbits on the y-axis for the DefendTheBase scene.

We’ll add some new logic to the RotateCube() method. The cube objects will rotate around the base while the target is visible. When the target is not visible, they will continue to rotate around the Camera, using the same logic as in the last tutorial.

To move the object toward the base, we’ll need to check first if the base is present, and then apply the position steps to the object.

The DestroyCube() method is the same as before, but now we'll add a new method—the TargetHit(GameObject) method—that will be called when the base is hit. Note that the BaseHealthScript referenced in TargetHit() hasn't been created yet.

Finally, we’ll add the public methods to be called when the cube takes a hit, when it collides with the base, or when the base changes status.

Controlling the Base Health

The enemies are being staged and flying toward the base, but they don't cause any damage when they collide—neither to the base nor to the enemy. We need to create a script to respond to collisions and also to add a health bar to the screen, so the user knows how well they are doing.

Let’s begin adding the health bar. In the Hierarchy panel in the Unity editor, click on Create> UI> Slider. A new Canvas element will be added to the hierarchy. It contains UI elements, including the new Slider. Expand the Canvas and select the Slider.

Change the slider element name to UIHealth. In the Inspector panel, expand Rect Transform and set Width to 400 and Height to 40. Set Pos X to -220Pos Y to 30, and Pos Z to 0.

Now expand the slider script in the hierarchy. Unselect the Interactable option. For Target Graphic, click on the small ‘dot’ on the right side and select the Background image. 

  • Set the Min Value to 0 and Max Value to 100.
  • Select Whole Numbers.
  • Set Value to 100.
UIHealth Settings

Now, expand the Slider panel to expose its child elements: Background, Fill Area, and Handle Slide Area.

  • Delete Handle Slide Area.
  • Select Background and set its Color to a darker shade of green, like #12F568FF.
  • Expand Fill Area and select the Fill object and set its color to #7FEA89FF.

This is how the Game Window should look with the health bar.

Game window with health bar

The Base Health Script

The code is very simple; it just subtracts the damage made by the enemies from the total amount of the base’s health. Once the health gets to zero, the player loses the game. It will also add a rotation animation to the Base. Create a new C# script called MyBase.

Now we need to add and configure the script. 

Select the Base in the hierarchy, click on Add Component, and add an Audio Source. Now drag MyBase to the Base element and, in the Inspector panel, expand MyBase. Select a sound effect for the explosion and hit. I’ve used the explosion clip used in the last tutorial, but feel free to add your own. Finally, in the Health Slider, select the UISlider element.

Base settings

Defending the Base

Our new game experience is almost done. We only need to shoot some lasers to start defending our base. Let's create a script for the laser! 

First drag the _PlayerController from the Prefab folder to the hierarchy. Expand _PlayerController and select _LaserController. In the Inspector panel, find Laser Script and click on Edit.

The only thing that we need to change in this script is the position of the laser.

Trying Out the Game

 

That was a lot of work, but now it's time to play the game! Print out the target image and try to run your game on your phone or tablet. Have some fun with it and see if you can come up with some ways to improve the game! 

At this point, you have a good understanding of how the Vuforia system works and how to use it with Unity. I expect that you've enjoyed this journey as much as I have. See you soon!

To learn more about Augmented Reality with Vuforia and Unity, check out our video course here on Envato Tuts+!

2017-03-13T15:03:55.000Z2017-03-13T15:03:55.000ZTin Megali

Create a Pokémon GO Style Augmented Reality Game With Vuforia: Image Targets

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

In this tutorial we'll dive back into the Vuforia Augmented Reality (AR) library, exploring one of its most interesting resources—the Image Target. We'll expand on the Shoot the Cubes game that we created in earlier lessons, adding a new level where the player needs to defend their base from attacking cubes. 

 

This tutorial can be completed alone, although if you want an introduction to AR with Vuforia and Unity3D, check out the earlier posts in the series.

Image Targets

Any kind of image can be a Vuforia Image Target. However, the more detailed and intricate the image, the better it will be recognized by the algorithm. 

A lot of factors will be part of the recognizing calculation, but basically the image must have a reasonable level of contrast, resolution, and distinguishing elements. A blue sky photograph wouldn't work very well, but a picture of some grass would work gracefully. Image Targets can be shipped with the application, uploaded to the application through the cloud, or directly created in the app by the user.

Adding a Target

Let’s begin by adding an ImageTarget element to our Unity project. 

First, download the course assets from the button in the sidebar. Then, in your Unity project, create a new scene called DefendTheBase: in the Project window, select the Scenes folder and click on Create> Scene. Now open that scene and remove all the default scene objects from the hierarchy.

Next we'll add a light and camera. Click on Add> Light> Directional Light to add a directional light. Select this new light and set Soft Shadow as the Shadow Type option. 

After that, drag and drop an ARCamera object from Vuforia> Prefabs. Select the ARCamera object and in the inspector panel, set the App License Key created on the Vuforia developer page (see the first tutorial for instructions). Select DEVICE_TRACKING for the World Center Mod.

Finally, drag and drop an ImageTargetto the hierarchy from Vuforia> Prefabs.

Now we have to add a Vuforia Database. First, navigate to https://developer.vuforia.com/target-manager. Click on Add Database and choose a name.

There are three types of Database to choose from:

  1. Device: The Database is saved on the device and all targets are updated locally.
  2. Cloud: Database on the Vuforia servers.
  3. VuMark: Database exclusive to VuMark targets. It is also saved on the device.

In this case, choose the Device option and click on create.

Select the new database so we can start adding targets to it. Now it is time to add targets to the database. For now, we’ll just use the Single Image option.

Navigate to the previously downloaded files, pick ImageTarget1, and set its Width to 1 and click on Add. (Note: If you prefer to create your own Image Target, read the guide first.)

Vuforia Database

Now you can download the database, selecting Unity Editor as the chosen platform. Open the file and select all elements to be imported. We must also prepare our Unity scene to recognize the ImageTarget with this database we have created.

In the Unity editor, click on the ImageTarget object. First, find and expand Image Target Behavior in the object inspector. Select a Type of Predefined. Choose the image target we created earlier for Database. Finally, make sure that the Enable Extended Tracking and Enable Smart Terrain options are both disabled.

Image Target settings

The ImageTarget prefab is made of a series of components, including some scripts like Image Target Behavior, Turn Off Behavior, and Default Tracker Event Handler. If you want to deeply understand how the system works, read those scripts and try to understand their relationship to other components. 

For this tutorial, we won't dig too deep, though. We’ll only need to concentrate on the Default Tracker Event Handler, which receives calls when the image target tracking status changes. So let’s use this script as a base to create our own script behavior.

Create a copy of this script that we can extend. First select Default Tracker Event Handler, click on options and select Edit Script. Now, make a copy of the script. If you’re using MonoDevelop, click File> Save As and save as ImageTargetBehavior, saving it in the Scripts folder.

The TargetBehaviorScript Script

We won’t need the Vuforia namespace in our script. Remove the line “namespace Vuforia” and the brackets. That means we'll need to explicitly reference the Vuforia namespace when we want to access its classes: 

The most important method in this class will be the OnTrackableStateChanged method that receives calls when the image target is found or lost by the camera device. According to the target status, it calls OnTrackingFound or OnTrackingLost, and we’ll need to edit those methods as well. But first, let’s think about how we want the image target to behave. 

In this game, the user will defend a base that appears on an image target. Let’s consider the following game mechanics:

  • Once the target is recognized by the system, the base appears and enemies start to spawn and fly toward the base in a kamikaze style.
  • Every time an enemy hits the base, the base will take some damage and the enemy will be destroyed.
  • To win the game the user must shoot and destroy all enemies before the base is destroyed.
  • If the image target is lost (is no longer visible from the device camera), the game will start a countdown timer. If the timer gets to zero, the game is lost. While the target is lost, all enemies will stop advancing toward the base.

So we’ll need to adapt those game mechanics on top of what we built in the last tutorial. We'll create the enemy spawning logic in the next section with an empty object named _SpawnController, using the same logic adopted in the first part of the game.

For now, let's look at the tracking found logic.

Back in the Unity editor, we can create the base object that will be spawned by the spawn controller. 

First, on the ImageTarget object, disable the Default Trackable Event Handler script.

Next, click on Add Component and select the Target Behavior Script. From the Hierarchy panel, right click on ImageTarget and create a new cube named "Base". This cube should be inserted inside the ImageTarget object.

Make sure that the Base has Box Collider and Mesh Renderer enabled. 

Optionally, you could also insert a Plane object inside the ImageTarget using the ImageTarget submitted earlier in Vuforia as a texture. This would create an interesting effect, projecting shadows from the target and creating a richer experience.

Hierarchy and Image Target final settings

Adapting the SpawnScript

Now we will adapt the _SpawnController used in the last tutorial. Save the current scene and open ShootTheCubesMain from the last tutorial. In the Hierarchy panel, select the _SpawnController and drag it to the Prefabs folder to make it a Unity Prefab.

Save this new scene and reopen DefendTheBase. Drag _SpawnController from the prefabs folder to the Hierarchy panel. With the _SpawnController selected, click on Add Tag on the Inspector panel. Name the new tag _SpawnController and apply it to the object. 

In the Project window, select the Cube element in the Prefab folder and set its Tag, back on its inspector, to 'Enemy'.

Set Cubes tag to Enemy

Finally, open the Scripts folder and open SpawnScript. We need to make this script adapt itself to the loaded scene.

Next, we need to create two public methods to receive calls from TargetBehaviorScript when the target is found or lost: 

  • BaseOn (Vector3 basePosition) will be called when the target is found by the camera and the Base object is shown. It will change the spawning position, start the process, and inform all cubes that were previously added to the stage that the base is visible.

  • The BaseOff() method will be used when the target is lost. It will stop the staging process and inform all cube elements that the base was lost. 

The SetPosition (System.Nullable<Vector3> pos) uses the target’s current position to modify the object x, y, and z axes, and it can also receive a null value when the scene loaded is ShootTheCubesMain.

InformBaseOnToCubes() and InformBaseOffToCubes() are responsible for informing all staged cubes of the current base status.

The SpawnLoop() and SpawnElement() methods are using almost the same logic as the last tutorial.

Creating the Enemies

Now we’ll need to create some enemies. We'll use the Cube object that we created in the last tutorial, making some modifications to its script.

In the Prefabs folder, add a Cube object to the hierarchy. Then select the object and edit the CubeBehaviorScript.

We’ll preserve almost the same logic in this script, but with the following differences:

  • The Cube will pursue the Base when the target is found by the camera.
  • When the Cube hits the Base, it will destroy itself and give some damage to the Base.
  • The script needs to know the name of the scene loaded and adapt itself accordingly. 

If the scene's name is DefendTheBase, it must find the Base object and start to move towards it.

The CubeSettings() also need to adapt according to the scene loaded. The Cube only orbits on the y-axis for the DefendTheBase scene.

We’ll add some new logic to the RotateCube() method. The cube objects will rotate around the base while the target is visible. When the target is not visible, they will continue to rotate around the Camera, using the same logic as in the last tutorial.

To move the object toward the base, we’ll need to check first if the base is present, and then apply the position steps to the object.

The DestroyCube() method is the same as before, but now we'll add a new method—the TargetHit(GameObject) method—that will be called when the base is hit. Note that the BaseHealthScript referenced in TargetHit() hasn't been created yet.

Finally, we’ll add the public methods to be called when the cube takes a hit, when it collides with the base, or when the base changes status.

Controlling the Base Health

The enemies are being staged and flying toward the base, but they don't cause any damage when they collide—neither to the base nor to the enemy. We need to create a script to respond to collisions and also to add a health bar to the screen, so the user knows how well they are doing.

Let’s begin adding the health bar. In the Hierarchy panel in the Unity editor, click on Create> UI> Slider. A new Canvas element will be added to the hierarchy. It contains UI elements, including the new Slider. Expand the Canvas and select the Slider.

Change the slider element name to UIHealth. In the Inspector panel, expand Rect Transform and set Width to 400 and Height to 40. Set Pos X to -220Pos Y to 30, and Pos Z to 0.

Now expand the slider script in the hierarchy. Unselect the Interactable option. For Target Graphic, click on the small ‘dot’ on the right side and select the Background image. 

  • Set the Min Value to 0 and Max Value to 100.
  • Select Whole Numbers.
  • Set Value to 100.
UIHealth Settings

Now, expand the Slider panel to expose its child elements: Background, Fill Area, and Handle Slide Area.

  • Delete Handle Slide Area.
  • Select Background and set its Color to a darker shade of green, like #12F568FF.
  • Expand Fill Area and select the Fill object and set its color to #7FEA89FF.

This is how the Game Window should look with the health bar.

Game window with health bar

The Base Health Script

The code is very simple; it just subtracts the damage made by the enemies from the total amount of the base’s health. Once the health gets to zero, the player loses the game. It will also add a rotation animation to the Base. Create a new C# script called MyBase.

Now we need to add and configure the script. 

Select the Base in the hierarchy, click on Add Component, and add an Audio Source. Now drag MyBase to the Base element and, in the Inspector panel, expand MyBase. Select a sound effect for the explosion and hit. I’ve used the explosion clip used in the last tutorial, but feel free to add your own. Finally, in the Health Slider, select the UISlider element.

Base settings

Defending the Base

Our new game experience is almost done. We only need to shoot some lasers to start defending our base. Let's create a script for the laser! 

First drag the _PlayerController from the Prefab folder to the hierarchy. Expand _PlayerController and select _LaserController. In the Inspector panel, find Laser Script and click on Edit.

The only thing that we need to change in this script is the position of the laser.

Trying Out the Game

 

That was a lot of work, but now it's time to play the game! Print out the target image and try to run your game on your phone or tablet. Have some fun with it and see if you can come up with some ways to improve the game! 

At this point, you have a good understanding of how the Vuforia system works and how to use it with Unity. I expect that you've enjoyed this journey as much as I have. See you soon!

To learn more about Augmented Reality with Vuforia and Unity, check out our video course here on Envato Tuts+!

2017-03-13T15:03:55.000Z2017-03-13T15:03:55.000ZTin Megali

Swift From Scratch: Function Parameters, Types, and Nesting

$
0
0

In the previous article, we explored the basics of functions in Swift. Functions, however, have a lot more to offer. In this article, we continue our exploration of functions and look into function parameters, nesting, and types.

1. Local and External Parameter Names

Parameter Names

Let us revisit one of the examples from the previous article. The printMessage(message:) function defines one parameter, message.

We assign a name, message, to the parameter and use this name when we call the function.

But notice that we also use the same name to reference the value of the parameter in the body of the function.

In Swift, a parameter always has a local parameter name, and it optionally has an external parameter name. In the example, the local and external parameter names are identical.

API Guidelines

As of Swift 3, the Swift team has defined a clear set of API guidelines. I won't go into those guidelines in this tutorial, but I want to point out that the definition of the printMessage(message:) function deviates from those guidelines. The name of the function contains the word message, and the parameter is also named message. In other words, we are repeating ourselves.

It would be more elegant if we could invoke the printMessage(message:) function without the message keyword. This is what I have in mind.

This is possible, and it is more in line with the Swift API guidelines. But what is different? The difference is easy to spot if we take a look at the updated function definition. The updated example also reveals more about the anatomy of functions in Swift.

In a function definition, each parameter is defined by an external parameter name, a local parameter name, a colon, and the type of the parameter. If the local and external parameter names are identical, we only write the parameter name once. That is why the first example defines one parameter name, message.

If we don't want to assign an external parameter name to a parameter, we use the _, an underscore. This informs the compiler that the parameter doesn't have an external parameter name, and that means we can omit the parameter name when the function is invoked.

External Parameter Names

Objective-C is known for its long method names. While this may look clunky and inelegant to outsiders, it makes methods easy to understand and, if chosen well, very descriptive. The Swift team understood this advantage and introduced external parameter names from day one.

When a function accepts several parameters, it isn't always obvious which argument corresponds to which parameter. Take a look at the following example to better understand the problem. Notice that the parameters don't have an external parameter name.

The power(_:_:) function raises the value of a by the exponent b. Both parameters are of type Int. While most people will intuitively pass the base value as the first argument and the exponent as the second argument, this isn't clear from the function's type, name, or signature. As we saw in the previous article, invoking the function is straightforward.

To avoid confusion, we can give the parameters of a function external names. We can then use these external names when the function is called to unambiguously indicate which argument corresponds to which parameter. Take a look at the updated example below.

Note that the function's body hasn't changed since the local names haven't changed. However, when we invoke the updated function, the difference is clear and the result is less confusing.

While the types of both functions are identical, (Int, Int) -> Int, the functions are different. In other words, the second function isn't a redeclaration of the first function. The syntax to invoke the second function may remind you of Objective-C. Not only are the arguments clearly described, but the combination of function and parameter names also describe the purpose of the function.

In some cases, you want to use the same name for the local and the external parameter name. This is possible, and there's no need to type the parameter name twice. In the following example, we use base and exponent as the local and external parameter names.

By defining one name for each parameter, the parameter name serves as the local and external name of the parameter. This also means that we need to update the body of the function.

It's important to note that by providing an external name for a parameter, you are required to use that name when invoking the function. This brings us to default values.

Default Values

We covered default parameter values in the previous article. This is the function we defined in that article.

What happens if we don't define an external parameter name for the second parameter, which has a default value?

The compiler doesn't seem to care. But is this what we want? It is best to define an external parameter name to optional parameters (parameters with a default value) to avoid confusion and ambiguity.

Notice that we are repeating ourselves again in the previous example. There is no need to define an external parameter name for the date parameter. The next example shows what the printDate(_:format:) function would look like if we followed the Swift API guidelines.

We can now invoke the formatDate(_:format:) function without using the date label for the first parameter and with an optional date format.

2. Parameters and Mutability

Let us revisit the first example of this tutorial, the printMessage(_:) function. What happens if we change the value of the message parameter inside the function's body?

It doesn't take long for the compiler to start complaining.

Parameters and Mutability

The parameters of a function are constants. In other words, while we can access the values of function parameters, we cannot change their value. To work around this limitation, we declare a variable in the function's body and use that variable instead.

3. Variadic Parameters

While the term may sound odd at first, variadic parameters are common in programming. A variadic parameter is a parameter that accepts zero or more values. The values need to be of the same type. Using variadic parameters in Swift is trivial, as the following example illustrates.

The syntax is easy to understand. To mark a parameter as variadic, you append three dots to the parameter's type. In the function body, the variadic parameter is accessible as an array. In the above example, args is an array of Int values.

Because Swift needs to know which arguments correspond to which parameters, a variadic parameter is required to be the last parameter. It also implies that a function can have at most one variadic parameter.

The above also applies if a function has parameters with default values. The variadic parameter should always be the last parameter.

4. In-Out Parameters

Earlier in this tutorial, you learned that the parameters of a function are constants. If you want to pass a value into a function, modify it in the function, and pass it back out of the function, in-out parameters are what you need.

The following example shows an example of how in-out parameters work in Swift and what the syntax looks like.

We define the first parameter as an in-out parameter by adding the inout keyword. The second parameter is a regular parameter with an external name of withString and a local name of prefix. How do we invoke this function?

We declare a variable, input, of type String and pass it to the prefixString(_:with:) function. The second parameter is a string literal. By invoking the function, the value of the input variable becomes Hello, world!. Note that the first argument is prefixed with an ampersand, &, to indicate that it is an in-out parameter.

It goes without saying that constants and literals cannot be passed in as in-out parameters. The compiler throws an error when you do as illustrated in the following examples.

In-Out Parameters

It's evident that in-out parameters cannot have default values or be variadic. If you forget these details, the compiler kindly reminds you with an error.

5. Nesting

In C and Objective-C, functions and methods cannot be nested. In Swift, however, nested functions are quite common. The functions we saw in this and the previous article are examples of global functions—they are defined in the global scope.

When we define a function inside a global function, we refer to that function as a nested function. A nested function has access to the values defined in its enclosing function. Take a look at the following example to better understand this.

While the functions in this example aren't terribly useful, they illustrate the idea of nested functions and capturing values. The printHelloWorld() function is only accessible from within the printMessage(_:) function.

As illustrated in the example, the printHelloWorld() function has access to the constant a. The value is captured by the nested function and is therefore accessible from within that function. Swift takes care of capturing values, including managing the memory of those values.

6. Function Types

Functions as Parameters

In the previous article, we briefly touched upon function types. A function has a particular type, composed of the function's parameter types and its return type. The printMessage(_:) function, for example, is of type (String) -> (). Remember that () symbolizes Void, which is equivalent to an empty tuple.

Because every function has a type, it's possible to define a function that accepts another function as a parameter. The following example shows how this works.

The printMessage(_:with:) function accepts a string as its first parameter and a function of type (String) -> () as its second parameter. In the function's body, the function that we pass in is invoked with the message argument.

The example also illustrates how we can invoke the printMessage(_:with:) function. The myMessage constant is passed in as the first argument and the printMessage(_:) function as the second argument. How cool is that?

Functions as Return Types

It is also possible to return a function from a function. The next example is a bit contrived, but it illustrates what the syntax looks like.

The compute(_:) function accepts a boolean and returns a function of type (Int, Int) -> Int. The compute(_:) function contains two nested functions that are also of type (Int, Int) -> Int, add(_:_:) and subtract(_:_:).

The compute(_:) function returns a reference to either the add(_:_:) or the subtract(_:_:) function, based on the value of the addition parameter.

The example also shows how to use the compute(_:) function. We store a reference to the function that is returned by the compute(_:) function in the computeFunction constant. We then invoke the function stored in computeFunction, passing in 1 and 2, store the result in the result constant, and print the value of result in the standard output. The example may look complex, but it is actually easy to understand if you know what is going on.

Conclusion

You should now have a good understanding of how functions work in Swift and what you can do with them. Functions are fundamental to the Swift language, and you will use them extensively when working with Swift.

In the next article, we dive head first into closures—a powerful construct reminiscent of blocks in C and Objective-C, closures in JavaScript, and lambdas in Ruby.

If you want to learn how to use Swift 3 to code real-world apps, check out our course Create iOS Apps With Swift 3. Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. 

 


2017-03-15T22:41:58.794Z2017-03-15T22:41:58.794ZBart Jacobs

Swift From Scratch: Function Parameters, Types, and Nesting

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

In the previous article, we explored the basics of functions in Swift. Functions, however, have a lot more to offer. In this article, we continue our exploration of functions and look into function parameters, nesting, and types.

1. Local and External Parameter Names

Parameter Names

Let us revisit one of the examples from the previous article. The printMessage(message:) function defines one parameter, message.

We assign a name, message, to the parameter and use this name when we call the function.

But notice that we also use the same name to reference the value of the parameter in the body of the function.

In Swift, a parameter always has a local parameter name, and it optionally has an external parameter name. In the example, the local and external parameter names are identical.

API Guidelines

As of Swift 3, the Swift team has defined a clear set of API guidelines. I won't go into those guidelines in this tutorial, but I want to point out that the definition of the printMessage(message:) function deviates from those guidelines. The name of the function contains the word message, and the parameter is also named message. In other words, we are repeating ourselves.

It would be more elegant if we could invoke the printMessage(message:) function without the message keyword. This is what I have in mind.

This is possible, and it is more in line with the Swift API guidelines. But what is different? The difference is easy to spot if we take a look at the updated function definition. The updated example also reveals more about the anatomy of functions in Swift.

In a function definition, each parameter is defined by an external parameter name, a local parameter name, a colon, and the type of the parameter. If the local and external parameter names are identical, we only write the parameter name once. That is why the first example defines one parameter name, message.

If we don't want to assign an external parameter name to a parameter, we use the _, an underscore. This informs the compiler that the parameter doesn't have an external parameter name, and that means we can omit the parameter name when the function is invoked.

External Parameter Names

Objective-C is known for its long method names. While this may look clunky and inelegant to outsiders, it makes methods easy to understand and, if chosen well, very descriptive. The Swift team understood this advantage and introduced external parameter names from day one.

When a function accepts several parameters, it isn't always obvious which argument corresponds to which parameter. Take a look at the following example to better understand the problem. Notice that the parameters don't have an external parameter name.

The power(_:_:) function raises the value of a by the exponent b. Both parameters are of type Int. While most people will intuitively pass the base value as the first argument and the exponent as the second argument, this isn't clear from the function's type, name, or signature. As we saw in the previous article, invoking the function is straightforward.

To avoid confusion, we can give the parameters of a function external names. We can then use these external names when the function is called to unambiguously indicate which argument corresponds to which parameter. Take a look at the updated example below.

Note that the function's body hasn't changed since the local names haven't changed. However, when we invoke the updated function, the difference is clear and the result is less confusing.

While the types of both functions are identical, (Int, Int) -> Int, the functions are different. In other words, the second function isn't a redeclaration of the first function. The syntax to invoke the second function may remind you of Objective-C. Not only are the arguments clearly described, but the combination of function and parameter names also describe the purpose of the function.

In some cases, you want to use the same name for the local and the external parameter name. This is possible, and there's no need to type the parameter name twice. In the following example, we use base and exponent as the local and external parameter names.

By defining one name for each parameter, the parameter name serves as the local and external name of the parameter. This also means that we need to update the body of the function.

It's important to note that by providing an external name for a parameter, you are required to use that name when invoking the function. This brings us to default values.

Default Values

We covered default parameter values in the previous article. This is the function we defined in that article.

What happens if we don't define an external parameter name for the second parameter, which has a default value?

The compiler doesn't seem to care. But is this what we want? It is best to define an external parameter name to optional parameters (parameters with a default value) to avoid confusion and ambiguity.

Notice that we are repeating ourselves again in the previous example. There is no need to define an external parameter name for the date parameter. The next example shows what the printDate(_:format:) function would look like if we followed the Swift API guidelines.

We can now invoke the formatDate(_:format:) function without using the date label for the first parameter and with an optional date format.

2. Parameters and Mutability

Let us revisit the first example of this tutorial, the printMessage(_:) function. What happens if we change the value of the message parameter inside the function's body?

It doesn't take long for the compiler to start complaining.

Parameters and Mutability

The parameters of a function are constants. In other words, while we can access the values of function parameters, we cannot change their value. To work around this limitation, we declare a variable in the function's body and use that variable instead.

3. Variadic Parameters

While the term may sound odd at first, variadic parameters are common in programming. A variadic parameter is a parameter that accepts zero or more values. The values need to be of the same type. Using variadic parameters in Swift is trivial, as the following example illustrates.

The syntax is easy to understand. To mark a parameter as variadic, you append three dots to the parameter's type. In the function body, the variadic parameter is accessible as an array. In the above example, args is an array of Int values.

Because Swift needs to know which arguments correspond to which parameters, a variadic parameter is required to be the last parameter. It also implies that a function can have at most one variadic parameter.

The above also applies if a function has parameters with default values. The variadic parameter should always be the last parameter.

4. In-Out Parameters

Earlier in this tutorial, you learned that the parameters of a function are constants. If you want to pass a value into a function, modify it in the function, and pass it back out of the function, in-out parameters are what you need.

The following example shows an example of how in-out parameters work in Swift and what the syntax looks like.

We define the first parameter as an in-out parameter by adding the inout keyword. The second parameter is a regular parameter with an external name of withString and a local name of prefix. How do we invoke this function?

We declare a variable, input, of type String and pass it to the prefixString(_:with:) function. The second parameter is a string literal. By invoking the function, the value of the input variable becomes Hello, world!. Note that the first argument is prefixed with an ampersand, &, to indicate that it is an in-out parameter.

It goes without saying that constants and literals cannot be passed in as in-out parameters. The compiler throws an error when you do as illustrated in the following examples.

In-Out Parameters

It's evident that in-out parameters cannot have default values or be variadic. If you forget these details, the compiler kindly reminds you with an error.

5. Nesting

In C and Objective-C, functions and methods cannot be nested. In Swift, however, nested functions are quite common. The functions we saw in this and the previous article are examples of global functions—they are defined in the global scope.

When we define a function inside a global function, we refer to that function as a nested function. A nested function has access to the values defined in its enclosing function. Take a look at the following example to better understand this.

While the functions in this example aren't terribly useful, they illustrate the idea of nested functions and capturing values. The printHelloWorld() function is only accessible from within the printMessage(_:) function.

As illustrated in the example, the printHelloWorld() function has access to the constant a. The value is captured by the nested function and is therefore accessible from within that function. Swift takes care of capturing values, including managing the memory of those values.

6. Function Types

Functions as Parameters

In the previous article, we briefly touched upon function types. A function has a particular type, composed of the function's parameter types and its return type. The printMessage(_:) function, for example, is of type (String) -> (). Remember that () symbolizes Void, which is equivalent to an empty tuple.

Because every function has a type, it's possible to define a function that accepts another function as a parameter. The following example shows how this works.

The printMessage(_:with:) function accepts a string as its first parameter and a function of type (String) -> () as its second parameter. In the function's body, the function that we pass in is invoked with the message argument.

The example also illustrates how we can invoke the printMessage(_:with:) function. The myMessage constant is passed in as the first argument and the printMessage(_:) function as the second argument. How cool is that?

Functions as Return Types

It is also possible to return a function from a function. The next example is a bit contrived, but it illustrates what the syntax looks like.

The compute(_:) function accepts a boolean and returns a function of type (Int, Int) -> Int. The compute(_:) function contains two nested functions that are also of type (Int, Int) -> Int, add(_:_:) and subtract(_:_:).

The compute(_:) function returns a reference to either the add(_:_:) or the subtract(_:_:) function, based on the value of the addition parameter.

The example also shows how to use the compute(_:) function. We store a reference to the function that is returned by the compute(_:) function in the computeFunction constant. We then invoke the function stored in computeFunction, passing in 1 and 2, store the result in the result constant, and print the value of result in the standard output. The example may look complex, but it is actually easy to understand if you know what is going on.

Conclusion

You should now have a good understanding of how functions work in Swift and what you can do with them. Functions are fundamental to the Swift language, and you will use them extensively when working with Swift.

In the next article, we dive head first into closures—a powerful construct reminiscent of blocks in C and Objective-C, closures in JavaScript, and lambdas in Ruby.

If you want to learn how to use Swift 3 to code real-world apps, check out our course Create iOS Apps With Swift 3. Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. 

 


2017-03-15T22:41:58.794Z2017-03-15T22:41:58.794ZBart Jacobs

Swift From Scratch: An Introduction to Classes and Structures

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

Up to now, we've covered the basics of the Swift programming language. If you followed along, you should now have a solid understanding of variables, constants, functions, and closures. It's now time to use what we've learned and apply that knowledge to the object-oriented structures of Swift.

To understand the concepts discussed in this tutorial, it's important that you have a basic understanding of object-oriented programming. If you're not familiar with classes, objects, and methods, then I recommend you first read up on these topics before continuing with this tutorial.

eBook: Object-Oriented Programming With Swift

1. Introduction

In this lesson, we're going to explore the fundamental building blocks of object-oriented programming in Swift, classes and structures. In Swift, classes and structures feel and behave very similarly, but there are a number of key differences that you need to understand to avoid common pitfalls.

In Objective-C, classes and structures are very different. This isn't true for Swift. In Swift, for example, both classes and structures can have properties and methods. Unlike C structures, structures in Swift can be extended, and they can also conform to protocols.

The obvious question is: "What's the difference between classes and structures?" We'll revisit this question later in this tutorial. Let's first explore what a class looks like in Swift.

2. Terminology

Before we start working with classes and structures, I'd like to clarify a few commonly used terms in object-oriented programming. The terms classes, objects, and instances often confuse people new to object-oriented programming. Therefore, it's important that you know how Swift uses these terms.

Objects and Instances

A class is a blueprint or template for an instance of that class. The term "object" is often used to refer to an instance of a class. In Swift, however, classes and structures are very similar, and therefore it's easier and less confusing to use the term "instance" for both classes and structures.

Methods and Functions

Earlier in this series, we worked with functions. In the context of classes and structures, we usually refer to functions as methods. In other words, methods are functions that belong to a particular class or structure. In the context of classes and structures, you can use both terms interchangeably since every method is a function.

3. Defining a Class

Let's get our feet wet and define a class. Fire up Xcode and create a new playground. Remove the contents of the playground and add the following class definition.

The class keyword indicates that we're defining a class named Person. The implementation of the class is wrapped in a pair of curly braces. Even though the Person class isn't very useful in its current form, it's a proper, functional Swift class.

Properties

As in most other object-oriented programming languages, a class can have properties and methods. In the updated example below, we define three properties:

  • firstName, a variable property of type String?
  • lastName, a variable property of type String?
  • birthPlace: a constant property of type String

As the example illustrates, defining properties in a class definition is similar to defining regular variables and constants. We use the var keyword to define a variable property and the let keyword to define a constant property.

The above properties are also known as stored properties. Later in this series, we learn about computed properties. As the name implies, stored properties are properties that are stored by the class instance. They are similar to properties in Objective-C.

It's important to note that every stored property needs to have a value after initialization or be defined as an optional type. In the above example, we give the birthPlace property an initial value of "Belgium". This tells Swift that the birthplace property is of type String. Later in this article, we take a look at initialization in more detail and explore how it ties in with initializing properties.

Even though we defined the birthPlace property as a constant, it is possible to change its value during the initialization of a Person instance. Once the instance has been initialized, the birthPlace property can no longer be modified since we defined the property as a constant property with the let keyword.

Methods

We can add behavior or functionality to a class through functions or methods. In many programming languages, method is used instead of function in the context of classes and instances. Defining a method is almost identical to defining a function. In the next example, we define the fullName() method in the Person class.

The method fullName() is nested in the class definition. It accepts no parameters and returns a String. The implementation of the fullName() method is straightforward. Through optional binding, which we discussed earlier in this series, we access the values stored in the firstName and lastName properties.

We store the first and last name of the Person instance in an array and join the parts with a space. The reason for this somewhat awkward implementation should be obvious: the first and last name can be blank, which is why both properties are of type String?.

Instantiation

We've defined a class with a few properties and a method. How do we create an instance of the Person class? If you're familiar with Objective-C, then you're going to love the conciseness of the following snippet.

Instantiating an instance of a class is very similar to invoking a function. To create an instance, the name of the class is followed by a pair of parentheses, and the return value is assigned to a constant or variable.

In our example, the constant john now points to an instance of the Person class. Does this mean that we can't change any of its properties? The next example answers this question.

We can access the properties of an instance using the convenience of the dot syntax. In the example, we set firstName to "John", lastName to "Doe", and birthPlace to "France". Before we draw any conclusions based on the above example, we need to check for any errors in the playground.

Cannot Assign to Property

Setting firstName and lastName doesn't seem to cause any problems. But assigning "France" to the birthPlace property results in an error. The explanation is simple.

Even though john is declared as a constant, that doesn't prevent us from modifying the Person instance. There's one caveat, though: only variable properties can be modified after initializing an instance. Properties that are defined as constant cannot be modified once a value is assigned.

A constant property can be modified during the initialization of an instance. While the birthPlace property cannot be changed once a Person instance is created, the class wouldn't be very useful if we could only instantiate Person instances with a birthplace of "Belgium". Let's make the Person class a bit more flexible.

Initialization

Initialization is a phase in the lifetime of an instance of a class or structure. During initialization, we prepare the instance for use by populating its properties with initial values. The initialization of an instance can be customized by implementing an initializer, a special type of method. Let's define an initializer for the Person class.

We've defined an initializer, but we run into several problems. Take a look at the error the compiler throws at us.

Defining an Initializer

Not only is the initializer pointless, the compiler also warns us that we cannot modify the value of the birthPlace property since it already has an initial value. We can resolve the error by removing the initial value of the birthPlace property.

Note that the name of the initializer, init(), isn't preceded by the func keyword. In contrast to initializers in Objective-C, an initializer in Swift doesn't return the instance that's being initialized.

Another important detail is how we set the birthPlace property with an initial value. We set the birthPlace property by using the property name, but it's also fine to be more explicit like this.

The self keyword refers to the instance that's being initialized. This means that self.birthPlace refers to the birthPlace property of the instance. We can omit self, as in the first example, because there's no confusion about which property we're referring to. This isn't always the case, though. Let me explain what I mean.

Parameters

The initializer we defined isn't very useful at the moment, and it doesn't solve the problem we started with: being able to define the birthPlace of a person during initialization. 

In many situations, you want to pass initial values to the initializer to customize the instance you're instantiating. This is possible by creating a custom initializer that accepts one or more arguments. In the following example, we create a custom initializer that accepts one argument, birthPlace, of type String.

Two things are worth pointing out. First, we are required to access the birthPlace property through self.birthPlace to avoid ambiguity since the local parameter name is equal to birthPlace. Second, even though we haven't specified an external parameter name, Swift by default creates an external parameter name that's equal to the local parameter name.

In the following example, we instantiate another Person instance by invoking the custom initializer we just defined.

By passing a value for the birthPlace parameter to the initializer, we can assign a custom value to the constant birthPlace property during initialization.

Multiple Initializers

As in Objective-C, a class or structure can have multiple initializers. In the following example, we create two Person instances. In the first line, we use the default initializer. In the second line, we use the custom initializer we defined earlier.

4. Defining a Structure

Structures are surprisingly similar to classes, but there are a few key differences. Let's start by defining a basic structure.

At first glance, the only difference is the use of the struct keyword instead of the class keyword. The example also shows us an alternative approach to supply initial values to properties. Instead of setting an initial value for each property, we can give properties an initial value in the initializer of the structure. Swift won't throw an error, because it also inspects the initializer to determine the initial value—and type—of each property.

5. Classes and Structures

You may start to wonder what the difference is between classes and structures. At first glance, they look identical in form and function, with the exception of the class and struct keywords. There are a number of key differences, though.

Inheritance

Classes support inheritance, whereas structures don't. The following example illustrates this. The inheritance design pattern is indispensable in object-oriented programming and, in Swift, it's a key difference between classes and structures.

In the above example, the Person class is the parent or superclass of the Student class. This means that the Student class inherits the properties and behavior of the Person class. The last line illustrates this. We initialize a Student instance by invoking the custom initializer defined in the Person class.

Copying and Referencing

The following concept is probably the most important concept in Swift you'll learn today, the difference between value types and reference types. Structures are value types, which means that they are passed by value. An example illustrates this concept best.

We define a structure, Point, to encapsulate the data to store a coordinate in a two-dimensional space. We instantiate point1 with x equal to 0 and y equal to 0. We assign point1 to point2 and set the x coordinate of point1 to 10. If we output the x coordinate of both points, we discover that they are not equal.

Structures are passed by value, while classes are passed by reference. If you plan to continue working with Swift, you need to understand the previous statement. When we assigned point1 to point2, Swift created a copy of point1 and assigned it to point2. In other words, point1 and point2 each point to a different instance of the Point structure.

Let's now repeat this exercise with the Person class. In the following example, we instantiate a Person instance, set its properties, assign person1 to person2, and update the firstName property of person1. To see what passing by reference means for classes, we output the value of the firstName property of both Person instances.

The example proves that classes are reference types. This means that person1 and person2 refer to or reference the same Person instance. By assigning person1 to person2, Swift doesn't create a copy of person1. The person2 variable points to the same Person instance person1 is pointing to. Changing the firstName property of person1 also affects the firstName property of person2, because they are referencing the same Person instance.

As I mentioned several times in this article, classes and structures are very similar. What separates classes and structures is very important. If the above concepts aren't clear, then I encourage you to read the article one more time to let the concepts we covered sink in.

Conclusion

In this installment of Swift From Scratch, we've started exploring the basics of object-oriented programming in Swift. Classes and structures are the fundamental building blocks of most Swift projects, and we'll learn more about them in the next few lessons of this series.

In the next lesson, we continue our exploration of classes and structures by taking a closer look at properties and inheritance.

If you want to learn how to use Swift 3 to code real-world apps, check out our course Create iOS Apps With Swift 3. Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. 

 


2017-03-22T03:44:16.490Z2017-03-22T03:44:16.490ZBart Jacobs

Code Your First Ionic 2 App: Getting Set Up

$
0
0

With the recent release of Ionic 2, you might be one of those hybrid app developers who wants to try it out. But maybe you're overwhelmed by the amount of learning needed to get started.

That's why I want to give you a good start by walking you step by step through the creation of your first Ionic 2 app. If you're already familiar with Ionic then the concepts might easily "click" with you. But if you're a complete beginner, not to worry—I'll won't assume any prior knowledge of the framework.

App Overview

In this tutorial and the next one, you'll be creating a photo sharing app that lets users pick an image from their device and share it to Instagram. Here's what the app is going to look like:

Completed photo sharer app

Set Up Your Environment

Before you can start developing apps with Ionic 2, you first have to set up your development environment. This includes the following bits of software:

  • Android SDK: apps built with Cordova and Ionic rely on the same developer tools used by native app developers.
  • Node.js: this is mainly used by Ionic for tooling—things like compiling code and checking for errors.
  • An Android device or emulator for testing. You can install the default Android emulator with the Android SDK installer.

I'm not going to show you how to set up your development environment. The Cordova platform guide already does a great job of that:

Those two pages will show you everything you need to know about setting up Cordova for iOS or Android. Once your dev environment is all set, we can move on to the next step.

Install Cordova and Ionic 

Phew! Now you can actually install Cordova and Ionic. Use the following command:

Once they're done installing, assuming you didn't get any errors, you can verify if they were indeed installed with the following commands: cordova --version and ionic --version. That will show you the versions of the Cordova and Ionic frameworks installed on your system. For me, they return 6.4.0 and 2.2.1.

If you want to see more detailed version information such as the Ionic Framework version and Ionic CLI version, use the following instead:

Here's a sample output:

Create a New Ionic Project

The Ionic CLI provides the ionic start command for easily creating a new project:

Here's a template to help you understand what each individual option does:

The starter template that was used here is blank. This contains only the bare minimum in order to get something shown on the screen. There are others, but they can be a little overwhelming.

Remember that the Ionic CLI caters to both Ionic 1 and Ionic 2 projects, so you still have to specify the --v2 option in order to bootstrap an Ionic 2 project since Ionic 1 is still the default. But once you're inside an Ionic 2 project, the Ionic CLI is smart enough to know which version to use.

Adding the Platform

By default, Ionic doesn't come with any platforms which you can deploy to. You can add one by using the ionic platform add command followed by the platform you want to deploy to:

If you want to deploy to another platform, just replace android with whatever platform you want.

Installing the Plugins

For this app, you'll need two plugins: one for selecting an image from the user's library, and one for sharing the image to the Instagram app. 

First is the Image Picker plugin. This gives the app the ability to select images from the user's photo library.

Next is the Instagram plugin. This allows you to forward the image to the Instagram app for posting.

Those two plugins that you've just installed are part of a curated set of ES6 and TypeScript wrappers for Cordova plugins called Ionic Native. Their main job is to make it easier to interact with Cordova plugins by wrapping plugin callbacks in Promises or Observables

Development Workflow

Now you're ready to actually start coding the app. But before we get to that, let's first take a look at Ionic 2's development workflow and folder structure. 

In Ionic 2, most of the development work is done inside the src folder. These files are recompiled every time you make changes to the files in this folder. Unlike in Ionic 1, compilation is necessary because the source files are written in TypeScript (compiled to ES5 code) and Sass (compiled to CSS code). Every time you make a change, the code is also checked for errors, which are reported back to the developer through the console or the app preview. Once compilation is done, the resulting files are copied to the www folder, and the changes are reflected in the app preview.

Folder Structure

To get comfortable working with an Ionic 2 project, you need to familiarize yourself with the folder structure. For starters, you need to know what each folder is used for so that you know where to put your source files and where to look for files that you need. 

  • node_modules: this is where the Ionic 2 dependencies are stored. Most of the time you don't need to touch this folder unless there's a problem with one of the dependencies and you have to re-install it.
  • platforms: this is where platform-specific code is placed and where the app installer is put when you build the app for running on a device or emulator. That means all of the files in your www and plugins folders get copied here every time you build your app. 
  • plugins: this is where plugins are stored, obviously—both the default Ionic plugins and any other plugins you install.
  • resources: this is where you'll put app resources such as the icon and splash screen.
  • src: this is where you'll be coding most of the time. All the templates, stylesheets and TypeScript files that make up your app are stored here.
  • www: this is where your compiled files go. The files in here are served in the app preview.
  • hooks: this is where the Cordova development hook scripts are stored. These are used if you have custom scripts that you want to execute during some part of the development lifecycle (e.g. when a platform or plugin is added).

Running the Development Server

While developing an app, it's useful to see a live preview of the app that is updated while you make changes to the code. To launch the development server, use the following command:

That will start the process of watching for changes in the source files and will begin compiling them in real time. By default, Ionic will serve the preview at http://localhost:8100/. You'll see something like the following, and then you can go ahead and preview your app in the browser at the reported URL.

ionic serve output

Next Steps

Now that our development environment is set up, we're ready to jump into coding the app! Stay tuned tomorrow for the next post, where I'll show you how to actually code the app, building the UI and all the photo-sharing functionality. It's going to be fun!

In the meantime, check out some of our other tutorials on Ionic 2!

If you want an in-depth and practical introduction to the Ionic 2 framework, try our course Getting Started With Ionic 2.

 

In this course, Reggie Dawson will teach you all about the Ionic framework and will show you how to build a mobile app from scratch. Along the way, you'll learn about the Ionic component library, about programming statically-typed JavaScript with TypeScript, and about integrating an Ionic 2 app with a rich media API.

2017-03-22T11:24:48.000Z2017-03-22T11:24:48.000ZWernher-Bel Ancheta

Code Your First Ionic 2 App: Getting Set Up

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

With the recent release of Ionic 2, you might be one of those hybrid app developers who wants to try it out. But maybe you're overwhelmed by the amount of learning needed to get started.

That's why I want to give you a good start by walking you step by step through the creation of your first Ionic 2 app. If you're already familiar with Ionic then the concepts might easily "click" with you. But if you're a complete beginner, not to worry—I'll won't assume any prior knowledge of the framework.

App Overview

In this tutorial and the next one, you'll be creating a photo sharing app that lets users pick an image from their device and share it to Instagram. Here's what the app is going to look like:

Completed photo sharer app

Set Up Your Environment

Before you can start developing apps with Ionic 2, you first have to set up your development environment. This includes the following bits of software:

  • Android SDK: apps built with Cordova and Ionic rely on the same developer tools used by native app developers.
  • Node.js: this is mainly used by Ionic for tooling—things like compiling code and checking for errors.
  • An Android device or emulator for testing. You can install the default Android emulator with the Android SDK installer.

I'm not going to show you how to set up your development environment. The Cordova platform guide already does a great job of that:

Those two pages will show you everything you need to know about setting up Cordova for iOS or Android. Once your dev environment is all set, we can move on to the next step.

Install Cordova and Ionic 

Phew! Now you can actually install Cordova and Ionic. Use the following command:

Once they're done installing, assuming you didn't get any errors, you can verify if they were indeed installed with the following commands: cordova --version and ionic --version. That will show you the versions of the Cordova and Ionic frameworks installed on your system. For me, they return 6.4.0 and 2.2.1.

If you want to see more detailed version information such as the Ionic Framework version and Ionic CLI version, use the following instead:

Here's a sample output:

Create a New Ionic Project

The Ionic CLI provides the ionic start command for easily creating a new project:

Here's a template to help you understand what each individual option does:

The starter template that was used here is blank. This contains only the bare minimum in order to get something shown on the screen. There are others, but they can be a little overwhelming.

Remember that the Ionic CLI caters to both Ionic 1 and Ionic 2 projects, so you still have to specify the --v2 option in order to bootstrap an Ionic 2 project since Ionic 1 is still the default. But once you're inside an Ionic 2 project, the Ionic CLI is smart enough to know which version to use.

Adding the Platform

By default, Ionic doesn't come with any platforms which you can deploy to. You can add one by using the ionic platform add command followed by the platform you want to deploy to:

If you want to deploy to another platform, just replace android with whatever platform you want.

Installing the Plugins

For this app, you'll need two plugins: one for selecting an image from the user's library, and one for sharing the image to the Instagram app. 

First is the Image Picker plugin. This gives the app the ability to select images from the user's photo library.

Next is the Instagram plugin. This allows you to forward the image to the Instagram app for posting.

Those two plugins that you've just installed are part of a curated set of ES6 and TypeScript wrappers for Cordova plugins called Ionic Native. Their main job is to make it easier to interact with Cordova plugins by wrapping plugin callbacks in Promises or Observables

Development Workflow

Now you're ready to actually start coding the app. But before we get to that, let's first take a look at Ionic 2's development workflow and folder structure. 

In Ionic 2, most of the development work is done inside the src folder. These files are recompiled every time you make changes to the files in this folder. Unlike in Ionic 1, compilation is necessary because the source files are written in TypeScript (compiled to ES5 code) and Sass (compiled to CSS code). Every time you make a change, the code is also checked for errors, which are reported back to the developer through the console or the app preview. Once compilation is done, the resulting files are copied to the www folder, and the changes are reflected in the app preview.

Folder Structure

To get comfortable working with an Ionic 2 project, you need to familiarize yourself with the folder structure. For starters, you need to know what each folder is used for so that you know where to put your source files and where to look for files that you need. 

  • node_modules: this is where the Ionic 2 dependencies are stored. Most of the time you don't need to touch this folder unless there's a problem with one of the dependencies and you have to re-install it.
  • platforms: this is where platform-specific code is placed and where the app installer is put when you build the app for running on a device or emulator. That means all of the files in your www and plugins folders get copied here every time you build your app. 
  • plugins: this is where plugins are stored, obviously—both the default Ionic plugins and any other plugins you install.
  • resources: this is where you'll put app resources such as the icon and splash screen.
  • src: this is where you'll be coding most of the time. All the templates, stylesheets and TypeScript files that make up your app are stored here.
  • www: this is where your compiled files go. The files in here are served in the app preview.
  • hooks: this is where the Cordova development hook scripts are stored. These are used if you have custom scripts that you want to execute during some part of the development lifecycle (e.g. when a platform or plugin is added).

Running the Development Server

While developing an app, it's useful to see a live preview of the app that is updated while you make changes to the code. To launch the development server, use the following command:

That will start the process of watching for changes in the source files and will begin compiling them in real time. By default, Ionic will serve the preview at http://localhost:8100/. You'll see something like the following, and then you can go ahead and preview your app in the browser at the reported URL.

ionic serve output

Next Steps

Now that our development environment is set up, we're ready to jump into coding the app! Stay tuned tomorrow for the next post, where I'll show you how to actually code the app, building the UI and all the photo-sharing functionality. It's going to be fun!

In the meantime, check out some of our other tutorials on Ionic 2!

If you want an in-depth and practical introduction to the Ionic 2 framework, try our course Getting Started With Ionic 2.

 

In this course, Reggie Dawson will teach you all about the Ionic framework and will show you how to build a mobile app from scratch. Along the way, you'll learn about the Ionic component library, about programming statically-typed JavaScript with TypeScript, and about integrating an Ionic 2 app with a rich media API.

2017-03-22T11:24:48.000Z2017-03-22T11:24:48.000ZWernher-Bel Ancheta

Android Things: Understanding and Writing Drivers

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

In the previous article of this series, you learned about the various types of peripheral input and output devices and connections that can be used with Android Things. Next, you can expand on this knowledge to write new classes, known as drivers, that make interfacing with peripherals even easier. This article will focus on the type of drivers that can be written for Android Things.

Android Things User-Space Drivers

User-space drivers allow developers to inject new hardware into the Android framework, allowing them to interact with the already established Android APIs. While you can communicate directly with devices using the standard input/output APIs, writing a custom driver will allow your app to support various hardware profiles and directly work with the Android OS. In addition, your code will be more structured and easily support code reuse.

There are three primary driver classifications that you will learn about in this article: GPS drivers, Human Input Device (HID) drivers, and sensor drivers.

GPS Drivers

If your device needs location information, then you may want to add a GPS device into your app. By registering your GPS peripheral with the UserDriverManager, you will be able to inject your device's location data into the Android framework, allowing it to be used by Android's location services. This will combine the GPS data with WiFi and any other location source to provide more accurate data results for your app. 

Typically, your GPS modules will connect to an Android Things device through a UART connection. We won't go too in-depth about UART in this tutorial, but you can learn all about how it works for peripherals in the previous tutorial of this series

GPS module and Adafruit breakout board

To work with your GPS module, you will need to create a new Java component to communicate with your new device. We will call this class GpsDriverService.

In order to register your GPS module with the Android framework for location data, you will first need to create a GpsDriver object in your GpsDriverService. This object can be registered with the UserDriverManager with the registerGpsDriver() call.

Once your GPS module has received location data and sent it to your Android Things device over your serial UART connection, you will need to parse it and add it to a Location object. 

Most GPS modules will return location data in the NMEA format, though parsing this data is beyond the scope of this tutorial. There are four required data items for your Location object: accuracy, time, latitude, and longitude. You can also optionally include altitude, bearing, and speed (if the device is moving).

Once you have your Location object populated, you can pass it to the GpsDriver by calling reportLocation().

Once your component is created, you will need to instantiate it, start reading data, and listen to updates in your app. 

When your app is finished, you will need to unregister your driver and remove your location listener.

In addition, you will need to ensure that your app has the ACCESS_FINE_LOCATION permission. You can find details for ensuring an app has required permissions in this tutorial

When first working with an app that uses a new permission in Android Things, you will need to reboot your device after you install your app to ensure that the permission has been granted.

Human Input Device Drivers

The Android framework comes with a built-in pipeline for handling input from user button and motion events, which is used for things such as media buttons, controller joysticks, and keyboard key presses. By creating an InputDriver, you can tie your own human interactions to the standard Android input pipeline so that your device can properly react to your users. 

For simplicity, we will only look at button input events and how to tie them into the Android framework, though motion events are handled in a very similar fashion. Similarly to the last portion of this tutorial, we will ignore the more specific implementation details of the input devices and focus on tying received events to the Android platform.

Button Events

When a button event occurs from a button that you have attached to your Android Things device, you will want to record that and send it through the Android pipeline. 

The first thing you will need to do is create an InputDriver object in a new Service and initialize it. The driver can be initialized using a builder that accepts the input type, a name for your input, a version, and a key code that the button represents.

Once your InputDriver is initialized, you can register it with the UserDriverManager using the registerInputDriver() call.

Once you have registered your InputDriver, your driver service can wait for events to be sent to it from your button implementation class. If your custom button is pressed, you can notify the service and create a new KeyEvent, which can be placed on the Android input pipeline using the emit(KeyEvent) method. This method will return true if the KeyEvent is able to be sent to the Android framework, and false if an error occurs.

The final thing you will need to do is unregister your InputDriver object from the UserDriverManager when your app has finished running.

Listening for Input Events

Now that you are able to emit button input events to the Android input pipeline, it's time to listen for them. This is where all of the work to funnel your new button events into the Android framework pays off. In your application's Activity, you simply need to add a method for when a KeyEvent is down, and another for when a KeyEvent is up. In those methods, you can check the KeyEvent's key code and handle the event appropriately.

Sensor Drivers

Some of the most common components you will use with an Android Things board are sensors. As Android has a fairly robust sensor framework, it only makes sense that we would want to be able to add data from our external components into that pipeline. 

To start, you will need to make a new Java class that interacts with your hardware sensor. This class will need to extend UserSensorDriver and implement the read() method. In addition, if your sensor supports low power or sleep modes, you can override the setEnabled() method and act accordingly. 

The following code snippet is a stubbed version of a component class that would read data through the Peripheral I/O API to retrieve an X, Y and Z data value and return a new UserSensorReading. If the data is not currently available, your class can throw a new IOException.

Once your component class is created, you can create a new Service that will instantiate it, as well as create a new UserSensor object and attach it to the Android sensor pipeline. 

There are two types of sensors you can add to this pipeline. The first are predefined types, such as gyroscopes, accelerometers, light, and proximity, and can be added to the pipeline like so:

You'll notice that a SensorManager.DynamicSensorCallback is used in the above example. This notifies your app when the sensor is available to the framework, as registration can take some time, so that the framework does not attempt to read data from an unavailable device.

Adafruit pressure and temperature sensor

The second type is custom, which covers anything not already supported in Android. Some examples include water pH levels, wind speed, motion detection, or anything else that you can measure with new hardware. 

By replacing the setType() builder parameter with setCustomType(), you can add your device's name and reporting mode to control how it will trigger on the pipeline.

Finally, when your app is finished running, you will need to unregister your new component from the UserDriverManager.

Conclusion

In this tutorial, you have learned how to take components built using the Peripheral I/O API and tie them into the appropriate Android frameworks for use in your Android Things apps. 

At this point in the series, you have all of the tools necessary to create some more in-depth Android Things projects. In addition to writing your own drivers, you can find drivers that were written and implement them into your own project. You can find the source for these drivers from the Android Things GitHub repo, or check out some working samples using these drivers.

In the next article of this series, we will go a step further and create a full Android Things project that takes pictures from a Raspberry Pi and uploads them to Firebase. In the meantime, check out some of our other tutorials on Android app development here on Envato Tuts+!

2017-03-24T12:14:29.000Z2017-03-24T12:14:29.000ZPaul Trebilcox-Ruiz

Code Your First Ionic 2 App: A Photo Sharing App

$
0
0

In this two-part tutorial series, you're learning how to create your very first Ionic 2 app. Now that you've set up your development environment and learned about the development workflow in Ionic 2, it's time to get your hands dirty by coding the app. 

If you haven't yet, follow along with the first post to get your development environment set up and to bootstrap your project.

This second part will cover the things you need to know when it comes to coding apps in Ionic 2. You will learn how to create pages for the app, how to get user input, and how to use plugins to access native functionality. Once you're done, you'll be running the app in a device or emulator. But before you get to that, let's take a moment to talk about what you will be creating.

What You'll Be Creating

In this tutorial, you'll be creating a photo sharing app. The basic flow should be as follows:

  1. User opens the app and logs in. They'll get redirected to the page for picking an image for sharing. 
  2. User clicks on the Pick Image button. The image picker shows up, and the user picks one image. That image will then be previewed.
  3. User enters a caption and clicks on the Share Image button to pass the image to the Instagram app.

This tutorial will only show you how to run the app on an Android device, but Cordova (the framework that Ionic runs on) is cross-platform. Ionic 2 has built-in themes for Android, iOS, and Windows, so it's easy to create a version of your app for those devices as well. 

Here's what the app is going to look like:

Completed photo sharing app

Project Setup

If you followed along with the previous tutorial then you've already got your Ionic 2 development environment set up and your project scaffolded out. We used the following Ionic 2 CLI commands to create the project folder tree and prepare for deployment to Android:

We also installed a couple helpful plugins:

Coding the Home Page

For the rest of the tutorial, you'll be primarily be working inside the src folder, so assume that the src folder is the root every time you see a file path. (If you want a refresher on the paths that are created by the Ionic starter template, take a look at the previous tutorial.)

Inside the src directory are four folders:

  • app: this is where app-wide code is defined. If you need to run specific code when the app starts, or you want to update the global CSS, then this is the place to go. 
  • assets: this is where assets such as images used as content for the app go.
  • pages: this is where the code for individual pages goes. Every page has its own folder, and inside each folder are three files which define the template (HTML), styling (CSS), and the script (TypeScript) for the page.
  • themes: this is where you go if you want to modify the default Ionic 2 theme.

Home Page Template

By default, the Ionic blank starter template already comes with a home page. So all you have to do is edit it to show the content that you want. Open the pages/home/home.html file and clear its current contents. Add the following at the top of the page:

The code above is the boilerplate for the app's header. The <ion-navbar> component serves as a navigational toolbar. It will automatically show a back button whenever you navigate away from the default page. <ion-title> sets the title of the nav bar.

Next is the actual page content. You can define that inside the <ion-content> component. Default padding can be applied by specifying the padding option. Inside that container, create a new list which contains the input fields for entering the username and password. Creating a list to contain edit fields is a standard practice in Ionic—it allows you to stack each field neatly on top of each other. Below the list is the button for logging in.

Let's take a moment to look at the code for entering text and clicking a button. In Ionic, you can define a text input fields using the <ion-input> component. To bind the text field to a class property defined in your page script, use [(ngModel)]. Then the value assigned to it is the name of the class property. 

To set up two-way data binding, you can set [value] to the same property name used for the [(ngModel)]. This allows you to update the value of the text field by changing the value of the model from the page script. Later on, you'll see how to define a class property inside the page script.

To define buttons, use the standard button element in HTML. If you're wondering why it's not <ion-button>, it's because of accessibility reasons. Buttons are a crucial interface component, so the Ionic team decided to stick with the standard HTML buttons to make them accessible. The ion-button directive is instead added to provide additional functionality. 

Ionic 2 buttons

To add a click handler, you use the (click) directive, with a value specifying the function (defined in your page script) to execute when the click event happens.

Home Page Script

Open the pages/home/home.ts file, clear all of its contents, and add the following:

Breaking down the code above, we first import the Angular component class which has all the Ionic directives already baked in.

Next, we import the controllers for navigation and alerts from the ionic-angular package. This is where all the Ionic controllers are included.  

After that, we'll import the PickerPage. You'll be creating it later, so leave it commented out for now. Remember to remove the comment once you're ready for it to be loaded.

After the imports, use the @Component decorator to specify the HTML template to be used by the script:

Now we can define the class for our home page script. We'll want to export this class so that it can be imported from other files in the app.

Make the NavController and AlertController available throughout the class by defining them as parameters in the constructor. This allows you to use this.navCtrl, for example, when you want to use the NavController to navigate to another page.

Now we're ready to define properties of our controller that can be referenced from the template. These properties will contain the current value of the text field for username and password:

To keep things simple, we'll use hard-coded values for the username and password. But for real-world apps, you would usually make a request to a server to authenticate the user.

Inside the login() function, create an alert for when the user inputs an incorrect username or password:

If the credentials are incorrect, show the alert:

Ionic 2 alerts

If the username and password input by the user match the hard-coded values, use the NavController to push the Picker Page into the navigation stack. Whatever page you push into the navigation stack will become the current page, while popping a page effectively navigates to the previous page. This is how navigation works in Ionic 2. 

Picker Page

Next, you need to create the picker page. As you already know, the standard is to create a separate folder for each page, and each folder will have three files in it. Thankfully, the Ionic CLI also comes with a command that allows us to create new pages:

This uses the generate command, which will create the page folder with those three files inside. Best of all, each file already comes with some boilerplate code that you can start with. 

Picker Page Template

Once that's done, open the pages/picker/picker.html file and replace the boilerplate code with the following:

None of this code is really unfamiliar except for the hidden directive and the use of an <ion-card> component. 

The hidden directive allows you to hide an element based on a specific value defined in your page script. So if has_picked_image is true, only then will this div be visible.

The <ion-card> component is used for creating cards. Cards are a great way to display images inside apps.

Ionic 2 card images

Picker Page Style

Open the pages/picker/picker.scss file and add the following:

Picker Page Script

Open the pages/picker/picker.ts file and add the following:

I'll break this down a bit. First we import the plugins that you installed earlier. Notice that the plugins are all installed under the same package (ionic-native). This is really nice because instead of having to import every single plugin in its own line, you can just do it in a single line.

Next we declare the class properties:

When the Pick Image button is clicked, define the options for the image picker. These options are pretty self-explanatory, but I've added some comments to clarify what each one does.

Specifying the width and the height doesn't necessarily mean that the resulting image would be using those exact width and height. What it means is that Ionic will use those dimensions as the maximum width or height in such a way that the aspect ratio is still maintained. 

We're using data URI as the output type because the Instagram plugin only accepts data URIs. This means you also have to adjust the width, height, and quality to the bare minimum because data URIs can be very long if the quality is high—the entire image is encoded in a URI string! This could make the app crash, so it's always a good practice to stick with lower quality and smaller images when working with data URIs. 

Next, use the Image Picker plugin to trigger the image selection screen. Since we're just expecting a single image, we can simply access the first item in the array of results. We also have to prepend the prefix for data URIs.

Finally, when the Share Image button is clicked, the share method provided by the Instagram plugin will trigger the sharing screen in the Instagram app to launch. This will already have the image pre-filled. 

The caption won't be copied, though. The Instagram app disabled pre-filled captions and so the caption field will be empty once the Instagram app is opened. As a workaround, the Instagram plugin copies the caption to the clipboard instead. This means that the user can just paste it on the caption text field in the Instagram app instead.  

Bringing Everything Together

The final step is to open the app/app.module.ts file. This is the root module of the app where you define all the pages and providers (such as the default Ionic error handler) that you will use throughout the app. 

Make sure all the pages you've created are defined, otherwise you'll get an error when you navigate to a page that hasn't been defined. By default, the HomePage is already defined here, so you just have to add the PickerPage. Just import it at the top of the file and then add it under the declarations and entryComponents array. Note that MyApp is not a page; it's a component that serves as an empty shell for the pages to be loaded in.

If you open the app/app.components.ts file, you'll see the following:

This is where you can define the root page—the page that the user will see once they open the app. In this case, the HomePage is the root page. This is also perfect for executing initialization code, since the code in here only gets executed once when the user launches the app. When initializing something (e.g. asking for permission to enable Bluetooth), you'll always want to wait until the platform.ready() event is fired. Only once that event has fired can you be sure that native functions are ready to be called. 

Running the App

Now you're ready to run the app on a mobile device or emulator. You can do that by executing the following command:

Be sure that you have a device connected to your computer or that you have a running instance of an emulator when you execute the command above. If it still doesn't work, check that you have enabled USB debugging in your device and run adb devices. That will trigger your computer to connect to your device. Simply agree to the prompt in your device once you see the authentication prompt.  

If you want to have a copy of the APK file so you can share it with a friend, you can generate one by executing the following instead:

This will create an android-debug.apk file in the platforms/android/build/outputs/apk folder.

Conclusion

That's it! In this tutorial, you created your very first Ionic 2 app. It's a simple app, and you might even have found it easy. But you learned how to set up an environment for developing Ionic 2 apps, and you learned some basic concepts that you can apply when developing apps in the future. These include getting the current value from a text field, responding to click events, linking images, and using plugins to access native functionality. So pat yourself on the back! You did a good job getting this far.

In the meantime, check out some of our other tutorials on Ionic 2!

If you want an in-depth and practical introduction to the Ionic 2 framework, try our course Getting Started With Ionic 2.

 

In this course, Reggie Dawson will teach you all about the Ionic framework and will show you how to build a mobile app from scratch. Along the way, you'll learn about the Ionic component library, about programming statically-typed JavaScript with TypeScript, and about integrating an Ionic 2 app with a rich media API.

2017-03-24T15:58:09.000Z2017-03-24T15:58:09.000ZWernher-Bel Ancheta

Code Your First Ionic 2 App: A Photo Sharing App

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

In this two-part tutorial series, you're learning how to create your very first Ionic 2 app. Now that you've set up your development environment and learned about the development workflow in Ionic 2, it's time to get your hands dirty by coding the app. 

If you haven't yet, follow along with the first post to get your development environment set up and to bootstrap your project.

This second part will cover the things you need to know when it comes to coding apps in Ionic 2. You will learn how to create pages for the app, how to get user input, and how to use plugins to access native functionality. Once you're done, you'll be running the app in a device or emulator. But before you get to that, let's take a moment to talk about what you will be creating.

What You'll Be Creating

In this tutorial, you'll be creating a photo sharing app. The basic flow should be as follows:

  1. User opens the app and logs in. They'll get redirected to the page for picking an image for sharing. 
  2. User clicks on the Pick Image button. The image picker shows up, and the user picks one image. That image will then be previewed.
  3. User enters a caption and clicks on the Share Image button to pass the image to the Instagram app.

This tutorial will only show you how to run the app on an Android device, but Cordova (the framework that Ionic runs on) is cross-platform. Ionic 2 has built-in themes for Android, iOS, and Windows, so it's easy to create a version of your app for those devices as well. 

Here's what the app is going to look like:

Completed photo sharing app

Project Setup

If you followed along with the previous tutorial then you've already got your Ionic 2 development environment set up and your project scaffolded out. We used the following Ionic 2 CLI commands to create the project folder tree and prepare for deployment to Android:

We also installed a couple helpful plugins:

Coding the Home Page

For the rest of the tutorial, you'll be primarily be working inside the src folder, so assume that the src folder is the root every time you see a file path. (If you want a refresher on the paths that are created by the Ionic starter template, take a look at the previous tutorial.)

Inside the src directory are four folders:

  • app: this is where app-wide code is defined. If you need to run specific code when the app starts, or you want to update the global CSS, then this is the place to go. 
  • assets: this is where assets such as images used as content for the app go.
  • pages: this is where the code for individual pages goes. Every page has its own folder, and inside each folder are three files which define the template (HTML), styling (CSS), and the script (TypeScript) for the page.
  • themes: this is where you go if you want to modify the default Ionic 2 theme.

Home Page Template

By default, the Ionic blank starter template already comes with a home page. So all you have to do is edit it to show the content that you want. Open the pages/home/home.html file and clear its current contents. Add the following at the top of the page:

The code above is the boilerplate for the app's header. The <ion-navbar> component serves as a navigational toolbar. It will automatically show a back button whenever you navigate away from the default page. <ion-title> sets the title of the nav bar.

Next is the actual page content. You can define that inside the <ion-content> component. Default padding can be applied by specifying the padding option. Inside that container, create a new list which contains the input fields for entering the username and password. Creating a list to contain edit fields is a standard practice in Ionic—it allows you to stack each field neatly on top of each other. Below the list is the button for logging in.

Let's take a moment to look at the code for entering text and clicking a button. In Ionic, you can define a text input fields using the <ion-input> component. To bind the text field to a class property defined in your page script, use [(ngModel)]. Then the value assigned to it is the name of the class property. 

To set up two-way data binding, you can set [value] to the same property name used for the [(ngModel)]. This allows you to update the value of the text field by changing the value of the model from the page script. Later on, you'll see how to define a class property inside the page script.

To define buttons, use the standard button element in HTML. If you're wondering why it's not <ion-button>, it's because of accessibility reasons. Buttons are a crucial interface component, so the Ionic team decided to stick with the standard HTML buttons to make them accessible. The ion-button directive is instead added to provide additional functionality. 

Ionic 2 buttons

To add a click handler, you use the (click) directive, with a value specifying the function (defined in your page script) to execute when the click event happens.

Home Page Script

Open the pages/home/home.ts file, clear all of its contents, and add the following:

Breaking down the code above, we first import the Angular component class which has all the Ionic directives already baked in.

Next, we import the controllers for navigation and alerts from the ionic-angular package. This is where all the Ionic controllers are included.  

After that, we'll import the PickerPage. You'll be creating it later, so leave it commented out for now. Remember to remove the comment once you're ready for it to be loaded.

After the imports, use the @Component decorator to specify the HTML template to be used by the script:

Now we can define the class for our home page script. We'll want to export this class so that it can be imported from other files in the app.

Make the NavController and AlertController available throughout the class by defining them as parameters in the constructor. This allows you to use this.navCtrl, for example, when you want to use the NavController to navigate to another page.

Now we're ready to define properties of our controller that can be referenced from the template. These properties will contain the current value of the text field for username and password:

To keep things simple, we'll use hard-coded values for the username and password. But for real-world apps, you would usually make a request to a server to authenticate the user.

Inside the login() function, create an alert for when the user inputs an incorrect username or password:

If the credentials are incorrect, show the alert:

Ionic 2 alerts

If the username and password input by the user match the hard-coded values, use the NavController to push the Picker Page into the navigation stack. Whatever page you push into the navigation stack will become the current page, while popping a page effectively navigates to the previous page. This is how navigation works in Ionic 2. 

Picker Page

Next, you need to create the picker page. As you already know, the standard is to create a separate folder for each page, and each folder will have three files in it. Thankfully, the Ionic CLI also comes with a command that allows us to create new pages:

This uses the generate command, which will create the page folder with those three files inside. Best of all, each file already comes with some boilerplate code that you can start with. 

Picker Page Template

Once that's done, open the pages/picker/picker.html file and replace the boilerplate code with the following:

None of this code is really unfamiliar except for the hidden directive and the use of an <ion-card> component. 

The hidden directive allows you to hide an element based on a specific value defined in your page script. So if has_picked_image is true, only then will this div be visible.

The <ion-card> component is used for creating cards. Cards are a great way to display images inside apps.

Ionic 2 card images

Picker Page Style

Open the pages/picker/picker.scss file and add the following:

Picker Page Script

Open the pages/picker/picker.ts file and add the following:

I'll break this down a bit. First we import the plugins that you installed earlier. Notice that the plugins are all installed under the same package (ionic-native). This is really nice because instead of having to import every single plugin in its own line, you can just do it in a single line.

Next we declare the class properties:

When the Pick Image button is clicked, define the options for the image picker. These options are pretty self-explanatory, but I've added some comments to clarify what each one does.

Specifying the width and the height doesn't necessarily mean that the resulting image would be using those exact width and height. What it means is that Ionic will use those dimensions as the maximum width or height in such a way that the aspect ratio is still maintained. 

We're using data URI as the output type because the Instagram plugin only accepts data URIs. This means you also have to adjust the width, height, and quality to the bare minimum because data URIs can be very long if the quality is high—the entire image is encoded in a URI string! This could make the app crash, so it's always a good practice to stick with lower quality and smaller images when working with data URIs. 

Next, use the Image Picker plugin to trigger the image selection screen. Since we're just expecting a single image, we can simply access the first item in the array of results. We also have to prepend the prefix for data URIs.

Finally, when the Share Image button is clicked, the share method provided by the Instagram plugin will trigger the sharing screen in the Instagram app to launch. This will already have the image pre-filled. 

The caption won't be copied, though. The Instagram app disabled pre-filled captions and so the caption field will be empty once the Instagram app is opened. As a workaround, the Instagram plugin copies the caption to the clipboard instead. This means that the user can just paste it on the caption text field in the Instagram app instead.  

Bringing Everything Together

The final step is to open the app/app.module.ts file. This is the root module of the app where you define all the pages and providers (such as the default Ionic error handler) that you will use throughout the app. 

Make sure all the pages you've created are defined, otherwise you'll get an error when you navigate to a page that hasn't been defined. By default, the HomePage is already defined here, so you just have to add the PickerPage. Just import it at the top of the file and then add it under the declarations and entryComponents array. Note that MyApp is not a page; it's a component that serves as an empty shell for the pages to be loaded in.

If you open the app/app.components.ts file, you'll see the following:

This is where you can define the root page—the page that the user will see once they open the app. In this case, the HomePage is the root page. This is also perfect for executing initialization code, since the code in here only gets executed once when the user launches the app. When initializing something (e.g. asking for permission to enable Bluetooth), you'll always want to wait until the platform.ready() event is fired. Only once that event has fired can you be sure that native functions are ready to be called. 

Running the App

Now you're ready to run the app on a mobile device or emulator. You can do that by executing the following command:

Be sure that you have a device connected to your computer or that you have a running instance of an emulator when you execute the command above. If it still doesn't work, check that you have enabled USB debugging in your device and run adb devices. That will trigger your computer to connect to your device. Simply agree to the prompt in your device once you see the authentication prompt.  

If you want to have a copy of the APK file so you can share it with a friend, you can generate one by executing the following instead:

This will create an android-debug.apk file in the platforms/android/build/outputs/apk folder.

Conclusion

That's it! In this tutorial, you created your very first Ionic 2 app. It's a simple app, and you might even have found it easy. But you learned how to set up an environment for developing Ionic 2 apps, and you learned some basic concepts that you can apply when developing apps in the future. These include getting the current value from a text field, responding to click events, linking images, and using plugins to access native functionality. So pat yourself on the back! You did a good job getting this far.

In the meantime, check out some of our other tutorials on Ionic 2!

If you want an in-depth and practical introduction to the Ionic 2 framework, try our course Getting Started With Ionic 2.

 

In this course, Reggie Dawson will teach you all about the Ionic framework and will show you how to build a mobile app from scratch. Along the way, you'll learn about the Ionic component library, about programming statically-typed JavaScript with TypeScript, and about integrating an Ionic 2 app with a rich media API.

2017-03-24T15:58:09.000Z2017-03-24T15:58:09.000ZWernher-Bel Ancheta

10 Best Weather App Templates

$
0
0

CodeCanyon offers a wide range of application templates to get your app project up and running quickly. In this article, I'll show you the top ten weather templates you can choose from to kick start your own weather app. 

Android App Templates 

Simple Weather 5.0

This is a simple weather template with two screens—the main screen which contains the weather info and the settings screen to control the units. Along with an attractive layout, its notable features include five day weather forecasts updated every hour, the ability to add multiple locations, and also AdMob integration. This template is already integrated with the OpenWeatherMap API, but you can easily customize it to any other API if you want. Why don't you give it a shot by downloading the APK from the Play Store? 

Simple Weather 50 template screenshots

Weminder

Weminder is a single-screen app template. It has a visually appealing UI and some eye-catching features including automatic location detection for weather updates, seven-day weather forecasts, and the ability to set alerts for weather information. It's also set up with AdMob and Google Analytics and is compatible with the latest Android version. You are free to try out the app by downloading the APK to see if it fits your needs. 

Weminder app template screenshots

Map Tracking 

If you need something more than just a simple weather app, then Map Tracking might fit your needs. This material design app is packed with awesome features such as location-aware weather updates, a speedometer, embedded Google Maps, and AdMob integration. An Android APK is freely available for you to download, so you can give it a try!  

Map Tracking app template screenshots

Weather App

This template is a simple Material Design app with a beautiful UI and clean layout. The app tracks your current location—if given permission—and displays detailed weather information for both the current day and seven-day weather forecasts. You can also search for weather information for any other location. You should really check it out by downloading the APK

Weather App template screenshots

Weather Pro - Météo

Weather Pro is an Android template with a unique style and added rich features such as the ability to change the UI theme, seven-day weather forecasts for either your current location or another, ability to change the temperature units to either Celsius or Fahrenheit, and AdMob integration. The app is freely available on the Google Play Store for you to try it out!

Weather Pro app template screenshots

News App 

News App is a Material Design Android app template that is more than just a weather app. It has a weather widget that displays both the current weather information using the device GPS sensor and also the five-day weather forecast. But it also has features like news feeds, authentication (through Google, Facebook or email), notifications, and an admin panel powered by Firebase. An APK is available for download so that you can try it out and decide if it is right for you!

News App template screenshots

iOS App Templates 

Simple Weather V1

Just like the name says, Simple Weather is a very simple Swift 3 app template, and it supports all iOS versions through iOS 10. Users can search for weather info by location or use location awareness, they can get the latest four-day weather forecast, and they can change the app configuration in the settings screen. It's AdMob ready if you want to use Google's ad network as your app revenue model.

Simple Weather V app template screenshots

Weather App

This template is built for both the iOS and watchOS platforms. A Swift 3 app, it has a simple and clean UI. Users can get the current weather information for any location in real time—both on their phone and on their watch. It's compatible with the latest iOS 10 and watchOS 3. 

Weather App template screenshots

iOS City Guide - Sleep, Eat, Enjoy

iOS City Guide is a Swift 3 app template that offers much more than a vanilla weather app. Apart from the real-time seven-day weather forecast, it's also packed with other features such as live updating information on hotels, restaurants, bars, and clubs. If you want more than just an ordinary weather app, you might want to consider iOS City Guide. It's compatible with the latest iOS 10. 

iOS City Guide app template screenshots

Store Finder 

Store Finder is another iOS app template that is more than just a weather app. Store Finder is packed with features such as the ability to locate a store—and it has a weather feature that fetches and displays the current weather information for a location. 

Unlike most of the iOS apps in this list, it is written in Objective C, so if that is your language of choice, Store Finder might be the template for you. It also includes a PHP back-end and Google Maps integration. This app template is compatible with iOS 10. 

Store Finder app template screenshots

Conclusion

App templates are a great way to jump start your next development project, or to learn from other people's work. This article lists just a few of the popular mobile app templates available on Envato Market. If you are looking for inspiration or you're building an application and need help with a particular feature, then you may find your answer in some of these templates.

Put one of these templates to use right now, or check out some of the other templates for complete apps available on CodeCanyon. Learn more about them right here on Envato Tuts+!

2017-03-27T16:16:30.000Z2017-03-27T16:16:30.000ZChike Mgbemena

10 Best Weather App Templates

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

CodeCanyon offers a wide range of application templates to get your app project up and running quickly. In this article, I'll show you the top ten weather templates you can choose from to kick start your own weather app. 

Android App Templates 

Simple Weather 5.0

This is a simple weather template with two screens—the main screen which contains the weather info and the settings screen to control the units. Along with an attractive layout, its notable features include five day weather forecasts updated every hour, the ability to add multiple locations, and also AdMob integration. This template is already integrated with the OpenWeatherMap API, but you can easily customize it to any other API if you want. Why don't you give it a shot by downloading the APK from the Play Store? 

Simple Weather 50 template screenshots

Weminder

Weminder is a single-screen app template. It has a visually appealing UI and some eye-catching features including automatic location detection for weather updates, seven-day weather forecasts, and the ability to set alerts for weather information. It's also set up with AdMob and Google Analytics and is compatible with the latest Android version. You are free to try out the app by downloading the APK to see if it fits your needs. 

Weminder app template screenshots

Map Tracking 

If you need something more than just a simple weather app, then Map Tracking might fit your needs. This material design app is packed with awesome features such as location-aware weather updates, a speedometer, embedded Google Maps, and AdMob integration. An Android APK is freely available for you to download, so you can give it a try!  

Map Tracking app template screenshots

Weather App

This template is a simple Material Design app with a beautiful UI and clean layout. The app tracks your current location—if given permission—and displays detailed weather information for both the current day and seven-day weather forecasts. You can also search for weather information for any other location. You should really check it out by downloading the APK

Weather App template screenshots

Weather Pro - Météo

Weather Pro is an Android template with a unique style and added rich features such as the ability to change the UI theme, seven-day weather forecasts for either your current location or another, ability to change the temperature units to either Celsius or Fahrenheit, and AdMob integration. The app is freely available on the Google Play Store for you to try it out!

Weather Pro app template screenshots

News App 

News App is a Material Design Android app template that is more than just a weather app. It has a weather widget that displays both the current weather information using the device GPS sensor and also the five-day weather forecast. But it also has features like news feeds, authentication (through Google, Facebook or email), notifications, and an admin panel powered by Firebase. An APK is available for download so that you can try it out and decide if it is right for you!

News App template screenshots

iOS App Templates 

Simple Weather V1

Just like the name says, Simple Weather is a very simple Swift 3 app template, and it supports all iOS versions through iOS 10. Users can search for weather info by location or use location awareness, they can get the latest four-day weather forecast, and they can change the app configuration in the settings screen. It's AdMob ready if you want to use Google's ad network as your app revenue model.

Simple Weather V app template screenshots

Weather App

This template is built for both the iOS and watchOS platforms. A Swift 3 app, it has a simple and clean UI. Users can get the current weather information for any location in real time—both on their phone and on their watch. It's compatible with the latest iOS 10 and watchOS 3. 

Weather App template screenshots

iOS City Guide - Sleep, Eat, Enjoy

iOS City Guide is a Swift 3 app template that offers much more than a vanilla weather app. Apart from the real-time seven-day weather forecast, it's also packed with other features such as live updating information on hotels, restaurants, bars, and clubs. If you want more than just an ordinary weather app, you might want to consider iOS City Guide. It's compatible with the latest iOS 10. 

iOS City Guide app template screenshots

Store Finder 

Store Finder is another iOS app template that is more than just a weather app. Store Finder is packed with features such as the ability to locate a store—and it has a weather feature that fetches and displays the current weather information for a location. 

Unlike most of the iOS apps in this list, it is written in Objective C, so if that is your language of choice, Store Finder might be the template for you. It also includes a PHP back-end and Google Maps integration. This app template is compatible with iOS 10. 

Store Finder app template screenshots

Conclusion

App templates are a great way to jump start your next development project, or to learn from other people's work. This article lists just a few of the popular mobile app templates available on Envato Market. If you are looking for inspiration or you're building an application and need help with a particular feature, then you may find your answer in some of these templates.

Put one of these templates to use right now, or check out some of the other templates for complete apps available on CodeCanyon. Learn more about them right here on Envato Tuts+!

2017-03-27T16:16:30.000Z2017-03-27T16:16:30.000ZChike Mgbemena

New Course: Go Further With Swift

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

Are you ready to get beyond the basics of iOS app programming and tackle some more advanced topics?

If so, you should check out our new course, Go Further With Swift: Animation, Networking, and Custom Controls. In it, you'll learn some advanced skills for building professional-quality iOS apps. 

Follow along with Markus Mühlberger as he codes a functional iOS weather app with live weather data, custom UI components, and some slick animations to bring everything to life.

You can take our new course straight away with a free 10-day trial of our monthly subscription. If you decide to continue, it costs just $15 a month, and you’ll get access to hundreds of courses, with new ones added every week.

 

Or if you want to make things simpler, why not start with a ready-made iOS weather app template from Envato Market?

Weather app template

2017-03-27T18:24:28.000Z2017-03-27T18:24:28.000ZAndrew Blackman

New Course: Go Further With Swift

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

Are you ready to get beyond the basics of iOS app programming and tackle some more advanced topics?

If so, you should check out our new course, Go Further With Swift: Animation, Networking, and Custom Controls. In it, you'll learn some advanced skills for building professional-quality iOS apps. 

Follow along with Markus Mühlberger as he codes a functional iOS weather app with live weather data, custom UI components, and some slick animations to bring everything to life.

You can take our new course straight away with a free 10-day trial of our monthly subscription. If you decide to continue, it costs just $15 a month, and you’ll get access to hundreds of courses, with new ones added every week.

 

Or if you want to make things simpler, why not start with a ready-made iOS weather app template from Envato Market?

Weather app template

2017-03-27T18:24:28.000Z2017-03-27T18:24:28.000ZAndrew Blackman

The Right Way to Share State Between Swift View Controllers

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

A few years ago, when I was still an employee in a mobile consultancy, I worked on an app for a big investment bank. Big companies, especially banks, usually have processes in place to ensure that their software is secure, robust, and maintainable.

Part of this process involved sending the code of the app I wrote to a third party for review. That didn’t bother me, because I thought my code was impeccable and that the review company would say the same.

When their response came back, the verdict was different than I thought. Although they said the quality of the code was not bad, they pointed to the fact that the code was hard to maintain and to test (unit testing was not very popular in iOS development back then).

I dismissed their judgement, thinking that my code was great and there was no way it could be improved. They must just not understand it!

I had the typical developer hubris: we often think that what we do is great and others don’t get it. 

In hindsight I was wrong. Not much later, I started reading about some best practices. From then on, the problems in my code started to stick out like a sore thumb. I realized that, like many iOS developers, I had succumbed to some classic pitfalls of bad coding practices.

What Most iOS Developers Get Wrong

One of the most common iOS development bad practices arises when passing state between the view controllers of an app. I myself have fallen into this trap in the past.

State propagation across view controllers is vital in any iOS app. As your users navigate through the screens of your app and interact with it, you need to keep a global state that tracks all the changes the user makes to the data.

And this is where most iOS developers reach for the obvious, but incorrect, solution: the singleton pattern.

The singleton pattern is very quick to implement, especially in Swift, and it works well. You just have to add a static variable to a class to keep a shared instance of the class itself, and you are done.

It is then easy to access this shared instance from anywhere in your code:

For this reason, many developers think they found the best solution to the problem of state propagation. But they are wrong.

The singleton pattern is actually considered an anti-pattern. There have been many discussions of this in the development community. For example, see this Stack Overflow question.

In a nutshell, singletons create these problems:

  • They introduce a lot of dependencies in your classes, making it harder to change them in the future.
  • They make global state accessible to any part of your code. This can create complex interactions that are hard to track and cause many unexpected bugs.
  • They make your classes very hard to test, since you cannot separate them from a singleton easily.

At this point, some developers think: “Ah, I have a better solution. I will use the AppDelegate instead”.

The problem is that the AppDelegate class in iOS apps is accessed through the UIApplication shared instance:

But the shared instance of UIApplication is itself a singleton. So you haven't solved anything!

The solution to this problem is dependency injection. Dependency injection means that a class does not retrieve or create its own dependencies, but it receives them from the outside.

To see how to use dependency injection in iOS apps and how it can enable state sharing, we first need to revisit one of the fundamental architectural patterns of iOS apps: the Model-View-Controller pattern.

Extending the MVC Pattern

The MVC pattern, in a nutshell, states that there are three layers in the architecture of an iOS app:

  • The model layer represents the data of an app.
  • The view layer shows information on the screen and allows interaction.
  • The controller layer acts as glue between the other two layers, moving data between them.

The usual representation of the MVC pattern is something like this:

Simplistic view of the MVC pattern

The problem is that this diagram is wrong.

This “secret” hides in plain sight in a couple of lines in Apple’s documentation:

“One can merge the MVC roles played by an object, making an object, for example, fulfill both the controller and view roles—in which case, it would be called a view controller. In the same way, you can also have model-controller objects.”

Many developers think that view controllers are the only controllers that exist in an iOS app. For this reason, a lot of code ends up being written inside them for lack of a better place. This is what brings developers to use singletons when they need to propagate state: it seems like the only possible solution.

From the lines quoted above, it is clear that we can add a new entity to our understanding of the MVC pattern: the model controller. Model controllers deal with the model of the app, fulfilling the roles that the model itself should not fulfil. This is actually how the above scheme should look:

Diagram of the MVC pattern updated with view and model controllers

The perfect example of when a model controller is useful is for keeping the app’s state. The model should represent only the data of your app. The app’s state should not be its concern.

This state keeping usually ends inside view controllers, but now we have a new and better place to put it: a model controller. This model controller can then be passed to view controllers as they come on the screen through dependency injection.

We have solved the singleton anti-pattern. Let’s see our solution in practice with an example.

Propagating State Across View Controllers Using Dependency Injection

We're going to write a simple app to see a concrete example of how this works. The app is going to show your favorite quote on one screen, and allow you to edit the quote on a second screen.

This means that our app will need two view controllers, which will need to share state. After you see how this solution works, you can expand the concept to apps of any size and complexity.

To start, we need a model type to represent the data, which in our case is a quote. This can be done with a simple struct:

The Model Controller

We then need to create a model controller that holds the state of the app. This model controller needs to be a class. This is because we will need a single instance that we will pass to all our view controllers. Value types like structs get copied when we pass them around, so they clearly are not the right solution.

All our model controller needs in our example is a property where it can keep the current quote. But, of course, in bigger apps model controllers can be more complex than this:

I assigned a default value to the quote property so we will have already something to display on the screen when the app launches. This is not necessary, and you could declare the property to be an optional initialized to nil, if you wish your app to launch with a blank state.

Create the User Interface

We have now the model controller, which will contain the state of our app. Next, we need the view controllers that will represent the screens of our app.

First, we create their user interfaces. This is how the two view controllers look inside the app’s storyboard.

view controllers in the storyboard

The interface of the first view controller is made up of a couple of labels and a button, put together with simple auto layout constraints. (You can read more on auto layout here on Envato Tuts+.)

The interface of the second view controller is the same, but has a text view to edit the text of the quote and a text field to edit the author.

The two view controllers are connected by a single modal presentation segue, which originates from the Edit quote button.

You can explore the interface and the constraints of the view controllers in the GitHub repo.

Code a View Controller With Dependency Injection

We now need to code our view controllers. The important thing that we need to keep in mind here is that they need to receive the model controller instance from the outside, through dependency injection. So they need to expose a property for this purpose.

We can call our first view controller QuoteViewController. This view controller needs a couple of outlets to the labels for the quote and author in its interface.

When this view controller comes on screen, we populate its interface to show the current quote. We put the code to do this in the controller's viewWillAppear(_:) method.

We could have put this code inside the viewDidLoad() method instead, which is quite common. The problem, though, is that viewDidLoad() is called only once, when the view controller is created. In our app, we need to update the user interface of QuoteViewController every time it comes on the screen. This is because the user can edit the quote on the second screen. 

This is why we use the viewWillAppear(_:) method instead of viewDidLoad(). In this way we can update the view controller’s UI each time it appears on the screen. If you want to know more about a view controller’s lifecycle and all the methods that get called, I wrote an article detailing all of them.

The Edit View Controller

We now need to code the second view controller. We will call this one EditViewController.

This view controller is like the previous one:

  • It has outlets for the text view and the text field the user will use to edit the quote.
  • It has a property for the dependency injection of the model controller instance.
  • It populates its user interface before coming on screen.

In this case, I used the viewDidLoad() method because this view controller comes on screen only once.

Sharing the State

We now need to pass the state between the two view controllers and to update it when the user edits the quote.

We pass the app state in the prepare(for:sender:) method of QuoteViewController. This method is triggered by the connected segue when the user taps on the Edit quote button.

Here we pass forward the instance of the ModelController that keeps the state of the app. This is where the dependency injection for the EditViewController happens.

In the EditViewController, we have to update the state to the newly entered quote before we go back to the previous view controller. We can do this in an action connected to the Save button:

Initialize the Model Controller

We are almost done, but you might have noticed that we are still missing something: the QuoteViewController passes the ModelController to the EditViewController through dependency injection. But who gives this instance to the QuoteViewController in the first place? Remember that when using dependency injection, a view controller should not create its own dependencies. These need to come from the outside.

But there is no view controller before the QuoteViewController, because this is the first view controller of our app. We need some other object to create the ModelController instance and to pass it to the QuoteViewController.

This object is the AppDelegate. The role of the app delegate is to respond to the app’s lifecycle methods and configure the app accordingly. One of these methods is application(_:didFinishLaunchingWithOptions:), which gets called as soon as the app launches. That is where we create the instance of the ModelController and pass it to the QuoteViewController:

Our app is now complete. Each view controller gets access to the global state of the app, but we don’t use singletons anywhere in our code.

You can download the Xcode project for this example app in the tutorial GitHub repo.

Conclusions

In this article you've seen how using singletons to propagate the state in an iOS app is a bad practice. Singletons create a lot of problems, despite being very easy to create and use.

We solved the problem by looking more closely at the MVC pattern and understanding the possibilities hidden in it. Through the use of model controllers and dependency injection, we were able to propagate the state of the app across all view controllers without using singletons.

This is a simple example app, but the concept can be generalized to apps of any complexity. This is the standard best practice to propagate state in iOS apps. I now use it in every app I write for my clients.

A few things to keep in mind when you expand the concept to bigger apps:

  • The model controller can save the state of the app, for example in a file. In this way, our data will be remembered every time we close the app. You could also use a more complex storage solution, for example Core Data. My recommendation is to keep this functionality in a separate model controller that only takes care of storage. That controller can then be used by the model controller that keeps the state of the app.
  • In an app with a more complex flow, you will have many containers in your app flow. These are usually navigation controllers, with the occasional tab bar controller. The concept of dependency injection still applies, but you need to take the containers into account. You can either dig into their contained view controllers when performing the dependency injection, or create custom container subclasses that pass the model controller on.
  • If you add networking to your app, this should go in a separate model controller as well. A view controller can perform a network request through this network controller and then pass the resulting data to the model controller that keeps the state. Remember that the role of a view controller is exactly this: to act as a glue object that passes data around between objects.

Stay tuned for more iOS app development tips and best practices!

2017-03-30T17:29:36.000Z2017-03-30T17:29:36.000ZMatteo Manferdini

The Right Way to Share State Between Swift View Controllers

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

A few years ago, when I was still an employee in a mobile consultancy, I worked on an app for a big investment bank. Big companies, especially banks, usually have processes in place to ensure that their software is secure, robust, and maintainable.

Part of this process involved sending the code of the app I wrote to a third party for review. That didn’t bother me, because I thought my code was impeccable and that the review company would say the same.

When their response came back, the verdict was different than I thought. Although they said the quality of the code was not bad, they pointed to the fact that the code was hard to maintain and to test (unit testing was not very popular in iOS development back then).

I dismissed their judgement, thinking that my code was great and there was no way it could be improved. They must just not understand it!

I had the typical developer hubris: we often think that what we do is great and others don’t get it. 

In hindsight I was wrong. Not much later, I started reading about some best practices. From then on, the problems in my code started to stick out like a sore thumb. I realized that, like many iOS developers, I had succumbed to some classic pitfalls of bad coding practices.

What Most iOS Developers Get Wrong

One of the most common iOS development bad practices arises when passing state between the view controllers of an app. I myself have fallen into this trap in the past.

State propagation across view controllers is vital in any iOS app. As your users navigate through the screens of your app and interact with it, you need to keep a global state that tracks all the changes the user makes to the data.

And this is where most iOS developers reach for the obvious, but incorrect, solution: the singleton pattern.

The singleton pattern is very quick to implement, especially in Swift, and it works well. You just have to add a static variable to a class to keep a shared instance of the class itself, and you are done.

It is then easy to access this shared instance from anywhere in your code:

For this reason, many developers think they found the best solution to the problem of state propagation. But they are wrong.

The singleton pattern is actually considered an anti-pattern. There have been many discussions of this in the development community. For example, see this Stack Overflow question.

In a nutshell, singletons create these problems:

  • They introduce a lot of dependencies in your classes, making it harder to change them in the future.
  • They make global state accessible to any part of your code. This can create complex interactions that are hard to track and cause many unexpected bugs.
  • They make your classes very hard to test, since you cannot separate them from a singleton easily.

At this point, some developers think: “Ah, I have a better solution. I will use the AppDelegate instead”.

The problem is that the AppDelegate class in iOS apps is accessed through the UIApplication shared instance:

But the shared instance of UIApplication is itself a singleton. So you haven't solved anything!

The solution to this problem is dependency injection. Dependency injection means that a class does not retrieve or create its own dependencies, but it receives them from the outside.

To see how to use dependency injection in iOS apps and how it can enable state sharing, we first need to revisit one of the fundamental architectural patterns of iOS apps: the Model-View-Controller pattern.

Extending the MVC Pattern

The MVC pattern, in a nutshell, states that there are three layers in the architecture of an iOS app:

  • The model layer represents the data of an app.
  • The view layer shows information on the screen and allows interaction.
  • The controller layer acts as glue between the other two layers, moving data between them.

The usual representation of the MVC pattern is something like this:

Simplistic view of the MVC pattern

The problem is that this diagram is wrong.

This “secret” hides in plain sight in a couple of lines in Apple’s documentation:

“One can merge the MVC roles played by an object, making an object, for example, fulfill both the controller and view roles—in which case, it would be called a view controller. In the same way, you can also have model-controller objects.”

Many developers think that view controllers are the only controllers that exist in an iOS app. For this reason, a lot of code ends up being written inside them for lack of a better place. This is what brings developers to use singletons when they need to propagate state: it seems like the only possible solution.

From the lines quoted above, it is clear that we can add a new entity to our understanding of the MVC pattern: the model controller. Model controllers deal with the model of the app, fulfilling the roles that the model itself should not fulfil. This is actually how the above scheme should look:

Diagram of the MVC pattern updated with view and model controllers

The perfect example of when a model controller is useful is for keeping the app’s state. The model should represent only the data of your app. The app’s state should not be its concern.

This state keeping usually ends inside view controllers, but now we have a new and better place to put it: a model controller. This model controller can then be passed to view controllers as they come on the screen through dependency injection.

We have solved the singleton anti-pattern. Let’s see our solution in practice with an example.

Propagating State Across View Controllers Using Dependency Injection

We're going to write a simple app to see a concrete example of how this works. The app is going to show your favorite quote on one screen, and allow you to edit the quote on a second screen.

This means that our app will need two view controllers, which will need to share state. After you see how this solution works, you can expand the concept to apps of any size and complexity.

To start, we need a model type to represent the data, which in our case is a quote. This can be done with a simple struct:

The Model Controller

We then need to create a model controller that holds the state of the app. This model controller needs to be a class. This is because we will need a single instance that we will pass to all our view controllers. Value types like structs get copied when we pass them around, so they clearly are not the right solution.

All our model controller needs in our example is a property where it can keep the current quote. But, of course, in bigger apps model controllers can be more complex than this:

I assigned a default value to the quote property so we will have already something to display on the screen when the app launches. This is not necessary, and you could declare the property to be an optional initialized to nil, if you wish your app to launch with a blank state.

Create the User Interface

We have now the model controller, which will contain the state of our app. Next, we need the view controllers that will represent the screens of our app.

First, we create their user interfaces. This is how the two view controllers look inside the app’s storyboard.

view controllers in the storyboard

The interface of the first view controller is made up of a couple of labels and a button, put together with simple auto layout constraints. (You can read more on auto layout here on Envato Tuts+.)

The interface of the second view controller is the same, but has a text view to edit the text of the quote and a text field to edit the author.

The two view controllers are connected by a single modal presentation segue, which originates from the Edit quote button.

You can explore the interface and the constraints of the view controllers in the GitHub repo.

Code a View Controller With Dependency Injection

We now need to code our view controllers. The important thing that we need to keep in mind here is that they need to receive the model controller instance from the outside, through dependency injection. So they need to expose a property for this purpose.

We can call our first view controller QuoteViewController. This view controller needs a couple of outlets to the labels for the quote and author in its interface.

When this view controller comes on screen, we populate its interface to show the current quote. We put the code to do this in the controller's viewWillAppear(_:) method.

We could have put this code inside the viewDidLoad() method instead, which is quite common. The problem, though, is that viewDidLoad() is called only once, when the view controller is created. In our app, we need to update the user interface of QuoteViewController every time it comes on the screen. This is because the user can edit the quote on the second screen. 

This is why we use the viewWillAppear(_:) method instead of viewDidLoad(). In this way we can update the view controller’s UI each time it appears on the screen. If you want to know more about a view controller’s lifecycle and all the methods that get called, I wrote an article detailing all of them.

The Edit View Controller

We now need to code the second view controller. We will call this one EditViewController.

This view controller is like the previous one:

  • It has outlets for the text view and the text field the user will use to edit the quote.
  • It has a property for the dependency injection of the model controller instance.
  • It populates its user interface before coming on screen.

In this case, I used the viewDidLoad() method because this view controller comes on screen only once.

Sharing the State

We now need to pass the state between the two view controllers and to update it when the user edits the quote.

We pass the app state in the prepare(for:sender:) method of QuoteViewController. This method is triggered by the connected segue when the user taps on the Edit quote button.

Here we pass forward the instance of the ModelController that keeps the state of the app. This is where the dependency injection for the EditViewController happens.

In the EditViewController, we have to update the state to the newly entered quote before we go back to the previous view controller. We can do this in an action connected to the Save button:

Initialize the Model Controller

We are almost done, but you might have noticed that we are still missing something: the QuoteViewController passes the ModelController to the EditViewController through dependency injection. But who gives this instance to the QuoteViewController in the first place? Remember that when using dependency injection, a view controller should not create its own dependencies. These need to come from the outside.

But there is no view controller before the QuoteViewController, because this is the first view controller of our app. We need some other object to create the ModelController instance and to pass it to the QuoteViewController.

This object is the AppDelegate. The role of the app delegate is to respond to the app’s lifecycle methods and configure the app accordingly. One of these methods is application(_:didFinishLaunchingWithOptions:), which gets called as soon as the app launches. That is where we create the instance of the ModelController and pass it to the QuoteViewController:

Our app is now complete. Each view controller gets access to the global state of the app, but we don’t use singletons anywhere in our code.

You can download the Xcode project for this example app in the tutorial GitHub repo.

Conclusions

In this article you've seen how using singletons to propagate the state in an iOS app is a bad practice. Singletons create a lot of problems, despite being very easy to create and use.

We solved the problem by looking more closely at the MVC pattern and understanding the possibilities hidden in it. Through the use of model controllers and dependency injection, we were able to propagate the state of the app across all view controllers without using singletons.

This is a simple example app, but the concept can be generalized to apps of any complexity. This is the standard best practice to propagate state in iOS apps. I now use it in every app I write for my clients.

A few things to keep in mind when you expand the concept to bigger apps:

  • The model controller can save the state of the app, for example in a file. In this way, our data will be remembered every time we close the app. You could also use a more complex storage solution, for example Core Data. My recommendation is to keep this functionality in a separate model controller that only takes care of storage. That controller can then be used by the model controller that keeps the state of the app.
  • In an app with a more complex flow, you will have many containers in your app flow. These are usually navigation controllers, with the occasional tab bar controller. The concept of dependency injection still applies, but you need to take the containers into account. You can either dig into their contained view controllers when performing the dependency injection, or create custom container subclasses that pass the model controller on.
  • If you add networking to your app, this should go in a separate model controller as well. A view controller can perform a network request through this network controller and then pass the resulting data to the model controller that keeps the state. Remember that the role of a view controller is exactly this: to act as a glue object that passes data around between objects.

Stay tuned for more iOS app development tips and best practices!

2017-03-30T17:29:36.000Z2017-03-30T17:29:36.000ZMatteo Manferdini

19 Best Mobile App Templates With AdMob Integration

$
0
0

Imagine that you're ready to kickstart your own mobile app development business. Chances are that you'd like to use best development practices for your first app, but that you want to code it quickly. And you'll probably want to monetize your app too! This post will show you some easy ways to launch your next ad-supported app project.

In this article, I'll introduce some highly customizable and versatile mobile app templates that you can use in your next development project. They all have Google's AdMob app monetization platform neatly integrated into them, so you can build a revenue stream for your app from day one.

These templates are all available from CodeCanyon, where you can buy and download an app template for immediate use in your development project.

Android Templates

Universal Multi-Purpose Android App

Universal - Full Multi-Purpose Android App

Universal is a flexible and versatile app template that can be customized for a broad range of designs. In addition to its built-in AdMob support, the template can easily integrate with more than ten different content providers, including WordPress, YouTube, and Facebook. It is a native Android app and comes with extensive documentation to help you get started.

Universal Android WebView App

Universal Android WebView App

Universal Android WebView App has a simple goal—bundle a solid Android WebView component with AdMob ads. It has lots of nice extra features such as Material Design styling, geolocation, and pull-to-refresh gesture support. It supports app development in HTML5, CSS3, JavaScript, jQuery, Bootstrap and other web technologies, but at the same time offers its responsive design and clean native code as well.

 Web2App

Web2App

Web2App is another app template that provides an Android WebView component, and it's packed with features. This template offers countless possibilities for customization. Not only that, but its comprehensive documentation, along with video tutorials and step-by-step instructions, make your job much easier than you might have thought possible.

Android News App

Android News App

Android News App helps you run your own news platform. The app template consists of two components: an Android client and a PHP with MySQL server. It also provides you with full control over AdMob, allowing you to enable and disable features according to your specific requirements. This is an internationalization-ready app, with an RTL (right to left) mode which will come in handy if you want to add languages other than English and expand your global audience.

City Guide—Map App for Android

City Guide

City Guide is a location-aware map and places app for Android platform. It features eight different color themes, animated effects, responsive design, and a lot more. Also, it is built with easily configurable, cleanly written code, and its documentation will make getting started a breeze. It uses a local SQL database to store data, so that reliance on the user's internet connection is minimized.

Cookbook—Recipe App for Android

Cookbook

Cookbook is an Android app template for sharing cooking recipes. With easily configurable and customizable code, you can create your own app with relatively little effort and time. The template features a responsive Material Design interface and a local SQLite database in addition to its AdMob monetization support. So it's time to start "cooking" your app, using Cookbook.

Material Wallpaper

Material Wallpaper

Android wallpaper apps are quite popular, and Material Wallpaper is a great way to cater to that market segment. It's designed according to Google's Material Design guidelines, so users get the visual experience they're expecting. The template can manage an unlimited number of categories and image galleries, thanks to its powerful and responsive admin panel. In addition to AdMob integration, it features Firebase Analytics and push notifications too.

Your Recipes App

Your Recipes App

Another great cooking app template, Your Recipes App is a complete platform with an Android client and PHP-based server. The powerful Admin Panel lets you manage your content to keep content up to date and error-free. You can send push notifications to your users with Firebase and OneSignal. There is even RTL (right to left) language support, which will help if you want to expand into other languages.

Android Games and Media App Templates

Fortin Quiz Pro

Fortin Quiz Pro

Fortin Quiz Pro is a native Android quiz app template with a PHP back-end. Questions can be organized into various categories and sub-categories, and a highly configurable timer will help you customize the difficulty levels of the quiz. Audio and images also can be used as quiz prompts instead of text, and support for Google Leaderboard will let your users share their scores with friends.

Speedy Car Game With AdMob and Leaderboard

Speedy Car Game

Speedy Car Game is an excellent way to cater to Android car game fans. You get the complete source code for this popular game type and crystal clear graphics for different screen resolutions, along with background music with sounds. Naturally, it includes Google Leaderboard and AdMob integration. 

Your Radio App

Your Radio App

Your Radio App is an internet radio streaming app for Android. It supports several popular streaming formats, including M3U and AAC. This is a well-thought-out app with some nice features. For example, the ability to stop the radio when someone is calling is useful. The powerful admin panel, the great looking Material Design UI, and the Google Cloud Messaging push notifications are also worth mentioning.

Stream Radio - Multiple Station

Stream Radio

Stream Radio is a radio streaming app supporting a large number of streaming formats such as MP3, PCM/WAVE, AAC, AMR, Vorbis, etc. It provides excellent support for handling streaming errors due to network-related issues and for dealing with bad streaming URLs. With this template, you'll get the complete Android source code, a YouTube video with step-by-step instructions, full documentation, and the demo APK file. AdMob integration is discreet and non-intrusive.

Stream Radio 2 (Single Station)

Stream Radio 2 Single Station

Another serious competitor on the list, Stream Radio 2 (Single Station) is an Android online radio streamer that supports a variety of popular streaming formats. It shares almost the same features as the multiple station app, but is restricted to a single radio station. It supports social media network integration too.

Your Videos Channel

Your Videos Channel

Your Videos Channel is a great app template for those who just need to build a video streaming platform. It doesn't matter whether you choose to serve videos from YouTube or from your own server. This app is capable enough to handle any of those options. It has a beautiful Material Design UI, a responsive Admin Panel, and support for OneSignal push notifications. It's a great way to keep users engaged with your video content while also building an additional revenue source.

iOS Templates

RealEstate Finder

RealEstate Finder

RealEstate Finder is an iOS app template with a PHP back-end. It's packed with location-based features such as geofencing and Google Maps directions, which can help you create a unique user experience. It also has streamlined communication channels with integrated telephony, SMS, and email. Back-end server access will be provided to anyone who purchases the template.

Web2App for IOS

Web2App for IOS is the iOS version of the Web2App mentioned above. This template is highly customizable and ships with comprehensive documentation, video tutorials, and step-by-step instructions that make it easy to get started. You can choose from countless display modes and colors to suit your requirements, and of course customize the AdMob integration.

SuperView—WebView App

SuperView - WebView App

SuperView allows you to wrap your website in a simple iOS app. It's ideal for web developers who want to ease the difficult learning curve associated with the Swift programming language and iOS SDK. The quality of the coding and design in this template are really impressive.

Mobile Cross-Platform Templates

ionWordpress

ionWordpress -Wordpress Full Integrated Mobile App

ionWordpress is built on the cross-platform Ionic framework and enables you to build hybrid mobile apps with HTML5, CSS, and JavaScript. The template has a beautiful UI and UX features to delight your users. It also provides easy style customization capabilities and integration with WordPress and, naturally, AdMob.

Ionic Mobile App Builder

Ionic Mobile App Builder

Ionic Mobile App Builder is another hybrid mobile app template based on the Ionic framework. This template comes with some great front-end and back-end tools including a WYSIWYG layout editor, a WordPress plugin generator, and a lot more. Even if you're not so confident in PHP and MySQL skills, that's no problem—Ionic Mobile App Builder even has a web admin panel generator that'll take care of your PHP code!

Get an App Template Now!

App templates are a great way to jumpstart your next development project, or to learn from other people's work. Pick one of these great app templates today to kick-start development of your next app. Your time is valuable, and you owe it to yourself to do everything you can to get a head start on your next project. 

There are many more templates available on Code Canyon. Put one of them to use right now, or read more about how to use an app template here on Envato Tuts+!

2017-03-31T18:11:45.000Z2017-03-31T18:11:45.000ZBala Durage Sandamal Siripathi

19 Best Mobile App Templates With AdMob Integration

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

Imagine that you're ready to kickstart your own mobile app development business. Chances are that you'd like to use best development practices for your first app, but that you want to code it quickly. And you'll probably want to monetize your app too! This post will show you some easy ways to launch your next ad-supported app project.

In this article, I'll introduce some highly customizable and versatile mobile app templates that you can use in your next development project. They all have Google's AdMob app monetization platform neatly integrated into them, so you can build a revenue stream for your app from day one.

These templates are all available from CodeCanyon, where you can buy and download an app template for immediate use in your development project.

Android Templates

Universal Multi-Purpose Android App

Universal - Full Multi-Purpose Android App

Universal is a flexible and versatile app template that can be customized for a broad range of designs. In addition to its built-in AdMob support, the template can easily integrate with more than ten different content providers, including WordPress, YouTube, and Facebook. It is a native Android app and comes with extensive documentation to help you get started.

Universal Android WebView App

Universal Android WebView App

Universal Android WebView App has a simple goal—bundle a solid Android WebView component with AdMob ads. It has lots of nice extra features such as Material Design styling, geolocation, and pull-to-refresh gesture support. It supports app development in HTML5, CSS3, JavaScript, jQuery, Bootstrap and other web technologies, but at the same time offers its responsive design and clean native code as well.

 Web2App

Web2App

Web2App is another app template that provides an Android WebView component, and it's packed with features. This template offers countless possibilities for customization. Not only that, but its comprehensive documentation, along with video tutorials and step-by-step instructions, make your job much easier than you might have thought possible.

Android News App

Android News App

Android News App helps you run your own news platform. The app template consists of two components: an Android client and a PHP with MySQL server. It also provides you with full control over AdMob, allowing you to enable and disable features according to your specific requirements. This is an internationalization-ready app, with an RTL (right to left) mode which will come in handy if you want to add languages other than English and expand your global audience.

City Guide—Map App for Android

City Guide

City Guide is a location-aware map and places app for Android platform. It features eight different color themes, animated effects, responsive design, and a lot more. Also, it is built with easily configurable, cleanly written code, and its documentation will make getting started a breeze. It uses a local SQL database to store data, so that reliance on the user's internet connection is minimized.

Cookbook—Recipe App for Android

Cookbook

Cookbook is an Android app template for sharing cooking recipes. With easily configurable and customizable code, you can create your own app with relatively little effort and time. The template features a responsive Material Design interface and a local SQLite database in addition to its AdMob monetization support. So it's time to start "cooking" your app, using Cookbook.

Material Wallpaper

Material Wallpaper

Android wallpaper apps are quite popular, and Material Wallpaper is a great way to cater to that market segment. It's designed according to Google's Material Design guidelines, so users get the visual experience they're expecting. The template can manage an unlimited number of categories and image galleries, thanks to its powerful and responsive admin panel. In addition to AdMob integration, it features Firebase Analytics and push notifications too.

Your Recipes App

Your Recipes App

Another great cooking app template, Your Recipes App is a complete platform with an Android client and PHP-based server. The powerful Admin Panel lets you manage your content to keep content up to date and error-free. You can send push notifications to your users with Firebase and OneSignal. There is even RTL (right to left) language support, which will help if you want to expand into other languages.

Android Games and Media App Templates

Fortin Quiz Pro

Fortin Quiz Pro

Fortin Quiz Pro is a native Android quiz app template with a PHP back-end. Questions can be organized into various categories and sub-categories, and a highly configurable timer will help you customize the difficulty levels of the quiz. Audio and images also can be used as quiz prompts instead of text, and support for Google Leaderboard will let your users share their scores with friends.

Speedy Car Game With AdMob and Leaderboard

Speedy Car Game

Speedy Car Game is an excellent way to cater to Android car game fans. You get the complete source code for this popular game type and crystal clear graphics for different screen resolutions, along with background music with sounds. Naturally, it includes Google Leaderboard and AdMob integration. 

Your Radio App

Your Radio App

Your Radio App is an internet radio streaming app for Android. It supports several popular streaming formats, including M3U and AAC. This is a well-thought-out app with some nice features. For example, the ability to stop the radio when someone is calling is useful. The powerful admin panel, the great looking Material Design UI, and the Google Cloud Messaging push notifications are also worth mentioning.

Stream Radio - Multiple Station

Stream Radio

Stream Radio is a radio streaming app supporting a large number of streaming formats such as MP3, PCM/WAVE, AAC, AMR, Vorbis, etc. It provides excellent support for handling streaming errors due to network-related issues and for dealing with bad streaming URLs. With this template, you'll get the complete Android source code, a YouTube video with step-by-step instructions, full documentation, and the demo APK file. AdMob integration is discreet and non-intrusive.

Stream Radio 2 (Single Station)

Stream Radio 2 Single Station

Another serious competitor on the list, Stream Radio 2 (Single Station) is an Android online radio streamer that supports a variety of popular streaming formats. It shares almost the same features as the multiple station app, but is restricted to a single radio station. It supports social media network integration too.

Your Videos Channel

Your Videos Channel

Your Videos Channel is a great app template for those who just need to build a video streaming platform. It doesn't matter whether you choose to serve videos from YouTube or from your own server. This app is capable enough to handle any of those options. It has a beautiful Material Design UI, a responsive Admin Panel, and support for OneSignal push notifications. It's a great way to keep users engaged with your video content while also building an additional revenue source.

iOS Templates

RealEstate Finder

RealEstate Finder

RealEstate Finder is an iOS app template with a PHP back-end. It's packed with location-based features such as geofencing and Google Maps directions, which can help you create a unique user experience. It also has streamlined communication channels with integrated telephony, SMS, and email. Back-end server access will be provided to anyone who purchases the template.

Web2App for IOS

Web2App for IOS is the iOS version of the Web2App mentioned above. This template is highly customizable and ships with comprehensive documentation, video tutorials, and step-by-step instructions that make it easy to get started. You can choose from countless display modes and colors to suit your requirements, and of course customize the AdMob integration.

SuperView—WebView App

SuperView - WebView App

SuperView allows you to wrap your website in a simple iOS app. It's ideal for web developers who want to ease the difficult learning curve associated with the Swift programming language and iOS SDK. The quality of the coding and design in this template are really impressive.

Mobile Cross-Platform Templates

ionWordpress

ionWordpress -Wordpress Full Integrated Mobile App

ionWordpress is built on the cross-platform Ionic framework and enables you to build hybrid mobile apps with HTML5, CSS, and JavaScript. The template has a beautiful UI and UX features to delight your users. It also provides easy style customization capabilities and integration with WordPress and, naturally, AdMob.

Ionic Mobile App Builder

Ionic Mobile App Builder

Ionic Mobile App Builder is another hybrid mobile app template based on the Ionic framework. This template comes with some great front-end and back-end tools including a WYSIWYG layout editor, a WordPress plugin generator, and a lot more. Even if you're not so confident in PHP and MySQL skills, that's no problem—Ionic Mobile App Builder even has a web admin panel generator that'll take care of your PHP code!

Get an App Template Now!

App templates are a great way to jumpstart your next development project, or to learn from other people's work. Pick one of these great app templates today to kick-start development of your next app. Your time is valuable, and you owe it to yourself to do everything you can to get a head start on your next project. 

There are many more templates available on Code Canyon. Put one of them to use right now, or read more about how to use an app template here on Envato Tuts+!

2017-03-31T18:11:45.000Z2017-03-31T18:11:45.000ZBala Durage Sandamal Siripathi

Swift From Scratch: Closures

$
0
0

If you've worked with blocks in C or Objective-C or lambdas in Ruby, then you won't have a hard time wrapping your head around the concept of closures. Closures are nothing more than blocks of functionality that you can pass around in your code.

As a matter of fact, we've already worked with closures in the previous lessons. That's right: functions are closures too. Let us start with the basics and inspect the anatomy of a closure.

1. What Is a Closure?

As I said, a closure is a block of functionality that you can pass around in your code. You can pass a closure as an argument of a function or you can store it as a property of an object. Closures have many use cases.

The name closure hints at one of the key characteristics of closures. A closure captures the variables and constants of the context in which it is defined. This is sometimes referred to as closing over those variables and constants. We're going to look at value capturing in more detail at the end of this lesson.

Flexibility

You've already learned that functions can be incredibly powerful and flexible. Because functions are closures, closures are just as flexible. In this article, you discover just how flexible and powerful they are.

Memory Management

The C programming language has a similar concept, blocks. Closures in Swift, however, have a few benefits. One of the key advantages of closures in Swift is that memory management is something you, the developer, don't have to worry about.

Even retain cycles, which aren't uncommon in C or Objective-C, are handled by Swift. This reduces hard-to-find memory leaks or crashes that are caused by invalid pointers.

2. Syntax

The basic syntax of a closure isn't difficult, and it may remind you of global and nested functions, which we covered earlier in this series. Take a look at the following example.

The first thing you notice is that the entire closure is wrapped in a pair of curly braces. The parameters of the closure are wrapped in a pair of parentheses, separated from the return type by the -> symbol. The above closure accepts one argument, a, of type Int, and returns an Int. The body of the closure starts after the in keyword.

Named closures, that is global and nested functions, look a bit different. The following example should illustrate the differences.

The most prominent differences are the use of the func keyword and the position of the parameters and return type. A closure starts and ends with a curly brace, wrapping the parameters, return type, and closure body. Despite these differences, remember that every function is a closure. Not every closure is a function, though.

3. Closures as Parameters

Closures are powerful, and the following example illustrates how useful they can be. In the example, we create an array of states. We invoke the map(_:) function on the array to create a new array that only contains the first two letters of each state as a capitalized string.

The map(_:) function or method is common to many programming languages and libraries, such as Ruby, PHP, and JavaScript. In the above example, the map(_:) function is invoked on the states array, transforms its contents, and returns a new array that contains the transformed values. Don't worry about the body of the closure for now.

Type Inference

Previously in this series, we learned that Swift is quite smart. Let me show you exactly how smart. The array of states is an array of strings. Because we invoke the map(_:) function on the array, Swift knows that the state argument is of type String. This means that we can omit the type, as shown in the updated example below.

There are a few more things we can omit from the above example, resulting in the following one-liner.

Let me explain what's happening. 

The compiler can infer that we return a string from the closure that we pass to the map(_:) function, which means there's no reason to include it in the closure expression definition. 

We can only do this if the closure's body includes a single statement, though. In that case, we can put that statement on the same line as the closure's definition, as shown in the above example. Because there's no return type in the definition and no -> symbol preceding the return type, we can omit the parentheses enclosing the closure's parameters.

Shorthand Argument Names

It doesn't stop here, though. We can make use of shorthand argument names to simplify the above closure expression even more. When using an inline closure expression, as in the above example, we can omit the list of parameters, including the in keyword that separates the parameters from the closure body.

In the closure body, we reference the arguments using shorthand argument names that Swift provides us with. The first argument is referenced by $0, the second by $1, etc.

In the updated example below, I have omitted the list of parameters and the in keyword, and replaced the state argument in the closure's body with the shorthand argument name $0. The resulting statement is more concise without compromising readability.

Trailing Closures

The Swift programming language also defines a concept known as trailing closures. The idea is simple. If you pass a closure as the last argument of a function, you can place that closure outside the parentheses of the function call. The following example demonstrates how this works.

If the only argument of the function call is the closure, then it's even possible to omit the parentheses of the function call.

Note that this also works for closures that contain multiple statements. In fact, that is the main reason trailing closures are available in Swift. If a closure is long or complex and it's the last argument of a function, it is often better to use the trailing closure syntax.

4. Capturing Values

When using closures, you'll often find yourself using or manipulating constants and variables from the closure's surrounding context in the body of the closure. This is often referred to as value capturing. It simply means that a closure can capture the values of constants and variables from the context in which it is defined. Take the following example to better understand the concept of value capturing.

I'm sure you agree the above example is a bit contrived, but it clearly shows how value capturing works in Swift. The nested functions, changeToUppercase() and changeToLowercase(), have access to the outer function's arguments, states, as well as the newStates variable declared in the outer function. 

Let me explain what happens.

The changeCase(uppercase:ofStrings:) function accepts a boolean as its first argument and a variadic parameter of type String as its second parameter. The function returns an array of strings composed of the strings passed to the function as the second argument. In the function's body, we create a mutable array of strings, newStrings, in which we store the modified strings.

The nested functions loop over the strings that are passed to the changeCase(uppercase:ofStrings:) function and change the case of each string. As you can see, they have direct access to the strings passed to the changeCase(uppercase:ofStrings:) function as well as the newStrings array, which is declared in the body of the changeCase(uppercase:ofStrings:) function.

We check the value of uppercase, call the appropriate function, and return the newStrings array. The two lines at the end of the example demonstrate how the changeCase(uppercase:ofStrings:) function works.

Even though I've demonstrated value capturing with functions, remember that every function is a closure. In other words, the same rules apply to unnamed closures.

Closures

It's been mentioned several times in this article: functions are closures. There are three kinds of closures:

  • global functions
  • nested functions
  • closure expressions

Global functions, such as the print(_:separator:terminator:) function of the Swift standard library, capture no values. Nested functions, however, have access to and can capture the values of constants and values of the function they are defined in. The previous example illustrates this concept.

Closure expressions, also known as unnamed closures, can capture the values of constants and variables of the context they are defined in. This is very similar to nested functions.

Copying and Referencing

A closure that captures the value of a variable is able to change the value of that variable. Swift is clever enough to know whether it should copy or reference the values of the constants and variables it captures.

Developers who learn Swift and have little experience with other programming languages will take this behavior for granted. However, it's an important advantage that Swift understands how captured values are being used in a closure and, as a result, can handle memory management for us.

Conclusion

Closures are an important concept, and you will use them often in Swift. They enable you to write flexible, dynamic code that is easy both to write and to understand. 

In the next article, we explore object-oriented programming in Swift, starting with objects, structures, and classes.

If you want to learn how to use Swift 3 to code advanced features for real-world apps, check out our course Go Further With Swift: Animation, Networking, and Custom Controls. Follow along with Markus Mühlberger as he codes a functional iOS weather app with live weather data, custom UI components, and some slick animations to bring everything to life.

 
2017-04-03T21:11:09.630Z2017-04-03T21:11:09.630ZBart Jacobs
Viewing all 1836 articles
Browse latest View live