Once you've developed your iOS or OS X app, it's time to submit it to Apple for release in the App Store. This process is done through iTunes Connect, which is the portal connecting developers to the world. In this tutorial, you'll learn exactly how to distribute your apps from Xcode to the App Store using iTunes Connect.
More specifically, you'll be learning about the following topics:
what is iTunes Connect
how to generate certificates, App IDs, and provisioning profiles
how to distribute an application using iTunes Connect
Apple's review process
Note that you need to be a member of one of Apple's paid developer programs to create certificates and provisioning profiles, and to access iTunes Connect.
1. What is iTunes Connect?
iTunes Connect is a suite of web-based tools for managing content sold on the iTunes Store, App Store, Mac App Store, and iBooks Store. As a member of the iOS Developer Program or Mac Developer Program, you'll use this tool to manage apps, contracts, tax and banking information, sales reports, and more. - Apple Developer Center
Once you've signed up to one of the developer programs, you'll be given access to iTunes Connect, using your Apple ID and password. While iTunes Connect can be used to manage a wide range of products, such as music, movies, and books, we'll focus on iOS and OS X apps in this tutorial.
In iTunes Connect, you can view the sales and trends of your apps, sign contracts, tax, and banking agreements, as well as manage your iOS and OS X apps. The latter is the topic of this tutorial.
2. Certificates, App IDs, and Provisioning Profiles
Before you can distribute your apps to the App Store, you'll need to create three things:
Certificate: identifies the developer or development team
App ID: uniquely identifies an app on the App Store
Provisioning Profile: ties certificate, App ID, and devices together
Certificate
Step 1
To begin generating these three items, go to the Member Center, and select Certificates, Identifiers & Profiles.
Step 2
Select the item you wish to generate from its corresponding list. We'll start by generating a certificate first.
Step 3
You're now presented with a list of your existing certificates (if any). There are two types of certificates, development and distribution. Development certificates are used during testing and development while distribution certificates are used to sign your app for ad hoc or App Store distribution.
Click the plus button in the top right and select the type of certificate you'd like to generate. Choose App Store and Ad Hoc, because that's the one you need to publish your app to the App Store. Click Continue at the bottom.
Step 4
To create a certificate, you need a Certificate Signing Request (CSR), which you need to create on your development machine. This process involves creating a public/private key pair that identifies you, the developer. Let's see how this works.
Open up the Keychain Access application on your development machine and select Certificate Assistant > Request a Certificate From a Certificate Authority... from the Keychain Access menu.
Step 5
Enter your email address and set a name for the public/private key pair by filling out he Common Name field. I've named mine Sam Berson's Tuts+ Key. Leave the second email field blank and check the checkbox Saved to Disk.
Step 6
Find a safe place for the certificate signing request and save it to disk. With the certificate signing request created, it's time to upload it to the Member Center.
Step 7
Upload the certificate signing request you just created and click Generate at the bottom. Download the certificate and add it to Keychain Access by double-clicking it. Download, install, and back up your newly generated certificate.
App ID
The App ID string contains two parts separated by a period (.)—an App ID Prefix that is defined as your Team ID by default and an App ID Suffix that is defined as a Bundle ID search string. Each part of an App ID has different and important uses for your app. - Apple Developer Center
Head back to the member center and select App IDs to create a new App ID for your application. Click the plus button in the top right to get started.
Step 1
Give the App ID an easy to remember name in the App ID Description section.
Step 2
Select whether you'd like to create an Explicit or WildcardApp ID. An explicit App ID, such as com.tutsplus.testing, is tied to a particular application and is required if you, for example, would like to enable push notifications. A wildcard App ID, such as com.tutsplus.*, can be tied to several applications and always ends with an asterisk.
Step 3
Next, select the services you'd like to enable for the App ID, such as Game Center and iCloud. These services should align with your app's capabilities in Xcode.
Step 4
Finally, click the Submit button to confirm your App ID. Then, click Done.
Provisioning Profile
Generating a provisioning profile in the Member Center is similar to creating a certificate. Let me take you through the required steps to generate a provisioning profile.
Step 1
Select the type of provisioning profile you'd like to create. You'll notice that there are three types of provisioning profiles:
iOS App Development
App Store Distribution
Ad Hoc Distribution
We are interested in an App Store Distribution provisioning profile.
Step 2
Select the App ID you created a moment ago from the drop-down menu.
Step 3
Next, select the distribution certificate you created earlier in this tutorial.
Step 4
Type in an easy to remember name and click Generate at the bottom.
Step 5
Finally, click the Download button to save it to your development machine, add it to Xcode by double-clicking it, and click Done.
3. iTunes Connect
Once you've created the provisioning profile and the app's assets, it's time to send it to Apple for review. Before you can do this, you need to make sure that your project is ready for submission. This means adding launch images and application icons, preparing screenshots, a description for iTunes Connect, etc.
Creating a New Application
Step 1
After signing into iTunes Connect, select My Apps from the list of items.
Step 2
This will show you a list of your apps. Click the plus button in the top left and select New iOS App from the menu.
Step 3
Next, you'll need to fill in some important details about your new app.
Name: The name of your app as it will appear on the App Store. This can't be longer than 255 characters.
Version: The version number is shown on the App Store and should match the one of your app in Xcode.
Primary Language: If localized app information isn't available in an App Store territory, the information from your primary language will be used instead.
SKU: A unique ID for your app that isn't visible on the App Store.
Bundle ID: The bundle identifier must match the one you used in Xcode. It can't be changed after you submit your first build.
Bundle ID Suffix: Your bundle identifier must match the one used in your app's info.plist.
Adding Metadata
Step 1
You'll now be presented with your application's dashboard through which you can manage your application's metadata, pricing, availability, etc.
Step 2
Before you can submit an application, you need to add your application's metadata, such as the name, description, keywords, etc.
Other Things to Do
Amongst the obvious things, you'll also need to add pricing information, Game Center details (if applicable), and various other things. Go through each of the tabs at the top of the dashboard to see what information Apple needs from your end.
4. Apple's Review Process
As someone whose apps have been approved and rejected by Apple several times, it's important to make sure your app meets all of Apple's criteria before submitting your app. Once you've made the bold move and have sent it to Apple for review, your app will be placed in a queue.
There are a few stages to the review process and the table below highlights the key stages, and details for each of these.
Status
Description
Waiting for Review
You've submitted your app, and it's waiting in the queue. This process may take a few days.
In Review
Your app is currently being looked at and scrutinized by Apple's review team. This process usually takes anything from a few hours to a couple of days.
Processing for App Store
Your app has been approved and will be ready for sale within 24 hours. This process is usually very quick and takes less than a couple of hours.
Ready for Sale
Your app is now ready for sale. It will be automatically released on the date set in iTunes Connect.
Rejected (various types)
Your app has been rejected and needs more work. There are various reasons all of which can be found in the iTunes Connect Developer Guide.
Once your app has been approved, take some time to consider a good release date to let your app out into the wild. Ask your friends, family, colleagues and anyone else to share your app on Twitter and Facebook, and, if you've not integrated social sharing into your first binary, why not add it as an update?
Conclusion
You should now be able to distribute an app with iTunes Connect and know more about Apple's review process. If you have any questions, feel free to leave a comment below and I'll be sure to get back to you.
Once you've developed your iOS or OS X app, it's time to submit it to Apple for release in the App Store. This process is done through iTunes Connect, which is the portal connecting developers to the world. In this tutorial, you'll learn exactly how to distribute your apps from Xcode to the App Store using iTunes Connect.
More specifically, you'll be learning about the following topics:
what is iTunes Connect
how to generate certificates, App IDs, and provisioning profiles
how to distribute an application using iTunes Connect
Apple's review process
Note that you need to be a member of one of Apple's paid developer programs to create certificates and provisioning profiles, and to access iTunes Connect.
1. What is iTunes Connect?
iTunes Connect is a suite of web-based tools for managing content sold on the iTunes Store, App Store, Mac App Store, and iBooks Store. As a member of the iOS Developer Program or Mac Developer Program, you'll use this tool to manage apps, contracts, tax and banking information, sales reports, and more. - Apple Developer Center
Once you've signed up to one of the developer programs, you'll be given access to iTunes Connect, using your Apple ID and password. While iTunes Connect can be used to manage a wide range of products, such as music, movies, and books, we'll focus on iOS and OS X apps in this tutorial.
In iTunes Connect, you can view the sales and trends of your apps, sign contracts, tax, and banking agreements, as well as manage your iOS and OS X apps. The latter is the topic of this tutorial.
2. Certificates, App IDs, and Provisioning Profiles
Before you can distribute your apps to the App Store, you'll need to create three things:
Certificate: identifies the developer or development team
App ID: uniquely identifies an app on the App Store
Provisioning Profile: ties certificate, App ID, and devices together
Certificate
Step 1
To begin generating these three items, go to the Member Center, and select Certificates, Identifiers & Profiles.
Step 2
Select the item you wish to generate from its corresponding list. We'll start by generating a certificate first.
Step 3
You're now presented with a list of your existing certificates (if any). There are two types of certificates, development and distribution. Development certificates are used during testing and development while distribution certificates are used to sign your app for ad hoc or App Store distribution.
Click the plus button in the top right and select the type of certificate you'd like to generate. Choose App Store and Ad Hoc, because that's the one you need to publish your app to the App Store. Click Continue at the bottom.
Step 4
To create a certificate, you need a Certificate Signing Request (CSR), which you need to create on your development machine. This process involves creating a public/private key pair that identifies you, the developer. Let's see how this works.
Open up the Keychain Access application on your development machine and select Certificate Assistant > Request a Certificate From a Certificate Authority... from the Keychain Access menu.
Step 5
Enter your email address and set a name for the public/private key pair by filling out he Common Name field. I've named mine Sam Berson's Tuts+ Key. Leave the second email field blank and check the checkbox Saved to Disk.
Step 6
Find a safe place for the certificate signing request and save it to disk. With the certificate signing request created, it's time to upload it to the Member Center.
Step 7
Upload the certificate signing request you just created and click Generate at the bottom. Download the certificate and add it to Keychain Access by double-clicking it. Download, install, and back up your newly generated certificate.
App ID
The App ID string contains two parts separated by a period (.)—an App ID Prefix that is defined as your Team ID by default and an App ID Suffix that is defined as a Bundle ID search string. Each part of an App ID has different and important uses for your app. - Apple Developer Center
Head back to the member center and select App IDs to create a new App ID for your application. Click the plus button in the top right to get started.
Step 1
Give the App ID an easy to remember name in the App ID Description section.
Step 2
Select whether you'd like to create an Explicit or WildcardApp ID. An explicit App ID, such as com.tutsplus.testing, is tied to a particular application and is required if you, for example, would like to enable push notifications. A wildcard App ID, such as com.tutsplus.*, can be tied to several applications and always ends with an asterisk.
Step 3
Next, select the services you'd like to enable for the App ID, such as Game Center and iCloud. These services should align with your app's capabilities in Xcode.
Step 4
Finally, click the Submit button to confirm your App ID. Then, click Done.
Provisioning Profile
Generating a provisioning profile in the Member Center is similar to creating a certificate. Let me take you through the required steps to generate a provisioning profile.
Step 1
Select the type of provisioning profile you'd like to create. You'll notice that there are three types of provisioning profiles:
iOS App Development
App Store Distribution
Ad Hoc Distribution
We are interested in an App Store Distribution provisioning profile.
Step 2
Select the App ID you created a moment ago from the drop-down menu.
Step 3
Next, select the distribution certificate you created earlier in this tutorial.
Step 4
Type in an easy to remember name and click Generate at the bottom.
Step 5
Finally, click the Download button to save it to your development machine, add it to Xcode by double-clicking it, and click Done.
3. iTunes Connect
Once you've created the provisioning profile and the app's assets, it's time to send it to Apple for review. Before you can do this, you need to make sure that your project is ready for submission. This means adding launch images and application icons, preparing screenshots, a description for iTunes Connect, etc.
Creating a New Application
Step 1
After signing into iTunes Connect, select My Apps from the list of items.
Step 2
This will show you a list of your apps. Click the plus button in the top left and select New iOS App from the menu.
Step 3
Next, you'll need to fill in some important details about your new app.
Name: The name of your app as it will appear on the App Store. This can't be longer than 255 characters.
Version: The version number is shown on the App Store and should match the one of your app in Xcode.
Primary Language: If localized app information isn't available in an App Store territory, the information from your primary language will be used instead.
SKU: A unique ID for your app that isn't visible on the App Store.
Bundle ID: The bundle identifier must match the one you used in Xcode. It can't be changed after you submit your first build.
Bundle ID Suffix: Your bundle identifier must match the one used in your app's info.plist.
Adding Metadata
Step 1
You'll now be presented with your application's dashboard through which you can manage your application's metadata, pricing, availability, etc.
Step 2
Before you can submit an application, you need to add your application's metadata, such as the name, description, keywords, etc.
Other Things to Do
Amongst the obvious things, you'll also need to add pricing information, Game Center details (if applicable), and various other things. Go through each of the tabs at the top of the dashboard to see what information Apple needs from your end.
4. Apple's Review Process
As someone whose apps have been approved and rejected by Apple several times, it's important to make sure your app meets all of Apple's criteria before submitting your app. Once you've made the bold move and have sent it to Apple for review, your app will be placed in a queue.
There are a few stages to the review process and the table below highlights the key stages, and details for each of these.
Status
Description
Waiting for Review
You've submitted your app, and it's waiting in the queue. This process may take a few days.
In Review
Your app is currently being looked at and scrutinized by Apple's review team. This process usually takes anything from a few hours to a couple of days.
Processing for App Store
Your app has been approved and will be ready for sale within 24 hours. This process is usually very quick and takes less than a couple of hours.
Ready for Sale
Your app is now ready for sale. It will be automatically released on the date set in iTunes Connect.
Rejected (various types)
Your app has been rejected and needs more work. There are various reasons all of which can be found in the iTunes Connect Developer Guide.
Once your app has been approved, take some time to consider a good release date to let your app out into the wild. Ask your friends, family, colleagues and anyone else to share your app on Twitter and Facebook, and, if you've not integrated social sharing into your first binary, why not add it as an update?
Conclusion
You should now be able to distribute an app with iTunes Connect and know more about Apple's review process. If you have any questions, feel free to leave a comment below and I'll be sure to get back to you.
In this tutorial, you'll learn how to create a mobile 3D game using C# and Unity. The objective of the game is to cut the fruit that appears on the stage using the touch screen.
You will learn about the following aspects of Unity game development in this tutorial:
importing 3D models
swipe gestures
line renderers
physics forces
2D sprites
The user interface of the game is straightforward. The screenshot below gives you an idea of the artwork we'll be using and how the final user interface will end up looking. You can find the artwork and additional resources in the tutorial's source files on GitHub.
1. Project Setup
Step 1: Create a New Unity Project
Open Unity and select New Project from the File menu to open the new project dialog. Tell Unity where you want to save the project and set theSet up defaults for: menu to 3D.
Step 2: Configure Build Settings
In the next step, you're presented with Unity's user interface. Set the project up for mobile development by choosing Build Settings from the File menu and selecting your platform of choice.
Step 3: Artwork
The first thing we need to do after selecting the target platform is choosing the size of the artwork we'll be using in the game. This will help us select a proper size for the 3D textures and 2D GUI without making the artwork blurry or use textures that are too large for the target device. For example, the artwork needs to have a higher resolution if you're targeting an iPad with a retina display than a Lumia 520.
iOS
iPad without Retina: 1024px x 768px
iPad with Retina: 2048px x 1536px
3.5" iPhone/iPod Touch without Retina: 320px x 480px
3.5" iPhone/iPod with Retina: 960px x 640px
4" iPhone/iPod Touch: 1136px x 640px
Android
Because Android is an open platform, there's a wide range of devices, screen resolutions, and pixel densities. A few of the more common ones are listed below.
Asus Nexus 7 Tablet: 800px x 1280px, 216 ppi
Motorola Droid X: 854px x 480px, 228 ppi
Samsung Galaxy SIII: 720px x 1280px, 306 ppi
Windows Phone & BlackBerry
Blackberry Z10: 720px x 1280px, 355 ppi
Nokia Lumia 520: 400px x 800px, 233 ppi
Nokia Lumia 1520: 1080px x 1920px, 367 ppi
Note that the code we'll write in this tutorial can be used to target any of the platforms.
Step 4: Export Graphics
Depending on the devices you're targeting, you may need to convert the artwork to the recommended size and pixel density. You can do this in your favorite image editor. I've used the Adjust Size... function under the Tools menu in OS X's Preview application.
Step 5: Configure Unity's User Interface
Before we get started, make sure the 2D button in the Scene panel is not highlighted. You can also modify the resolution that's being displayed in the Game panel.
You're then presented with the workspace panels, which we'll also use in this tutorial. Take a moment to look at the main interface panels, such as the Scene, Game, Hierarchy, Project, Assets, and Inspector. We'll use them frequently in this tutorial.
Step 6: Programming Language
You can use one of three programming languages when using Unity, C#, UnityScript, a variation of JavaScript, and Boo. Each programming language has its pros and cons, and it's up to you to decide which one you prefer. My personal preference goes to the C# programming language so that's the language I'll be using in this tutorial.
If you decide to use another programming language, then make sure to take a look at Unity's Script Reference for examples.
2. Resources
Sound Effects
I'll use a number of sounds to improve the audial experience of the game. The sound effects used in this tutorial were obtained from PlayOnLoop and Freesound.
3D Models
To create the game, we first need to get a few 3D models. I recommend 3docean for high quality models and textures, but if you're testing or learning, then free models will work just as fine. The models in this tutorial were downloaded from SketchUp 3D Warehouse where you can find a wide variety of 3D models.
Because Unity doesn't recognize the SketchUp file format, we need to convert it to something Unity can import. We first need to download the free version of SketchUp, which is called SketchUp Make.
Open the 3D model in SketchUp Make, select Export > 3D Model from the File menu, and choose Collada (*.dae). Choose a name and location, and click Save. This will create a file and a folder for the 3D model. The file contains the data for the 3D object while the folder contains the model's textures. In the next step, we'll import the model into Unity.
3. Import Assets
Before we start coding, we need to add the assets to the Unity project. You can do this one of several ways:
select Import New Asset from the Assets menu
drag and drop the assets in the project window
add the items to the project's assets folder
After completing this step, you should see the assets in your project's Assets folder in the Project panel.
4. Setting Up Camera & Lighting
Step 1: Setting Up the Camera
In this step, we position the main camera to create the view we want. Select the main camera from the Hierarchy panel and adjust the Transform values in the Inspector to match the ones shown below.
Don't worry if you don't see any changes. We haven't created anything for the camera to see yet.
Step 2: Setting Up the Light
For our objects to be visible in the 3D world, we need to add light to the scene. Select Create Other from the GameObject menu and select Directional Light. This will create an object that produces a beam of light. Change its Transform values as shown in the following screenshot to make it illuminate the scene.
The light should be visible on the scene as shown in the following screenshot.
5. Add Background
We'll use a Sprite texture as our background. By default, images imported to the Assets folder are converted to Texture instances that can be applied to 3D objects. We need to change these Texture instances to Sprite Texture instances for the image we want to use as the background.
Select the image you want to convert in the Assets panel and open the Inspector. Select Sprite from the Texture Type menu.
Drag and drop the background into the Hierarchy panel. It should automatically appear in the Scene panel. Adjust the Transform values in the Inspector as shown in the next screenshot.
6. Create the Score GUI
To display the game's score, we'll use Unity's GUI Text and an imported 3D model.
Step 1: Adding the Apple Model
Select the imported 3D model of your choice from the Assets panel and drag and drop it on the Scene. I'm going to use an apple model. Adjust the Transform values in the Inspector to match the ones shown below.
This will place the apple at the top left of the screen.
Step 2: Adding the GUI Text
Along with the apple model, we'll display a number indicating the player's score. This is the number of fruits the player has cut.
Select Create Other > GUI Text from the GameObject menu to create a text object, place it on the right of the apple model, and change the text in the Inspector panel to 0.
You can embed a custom font by importing it in the Assets folder and changing the Font property of the text in the Inspector.
7. Create the Timer GUI
We'll use a timer to indicate when the game is over. It's composed of a GUI Texture showing an icon and a GUI Text displaying the remaining time.
Step 1: Adding the Clock Icon
To add the clock icon, select the image you want to use in the Assets panel and open the Inspector. Select GUI from the Texture Type menu to convert it to a GUI Texture. Drag and drop the image to the Scene and change its transform values to the ones shown below.
The scene should now look like this.
Step 2: Adding the GUI Text
Repeat the steps for adding the score text to add the timer text. Don't forget to set the text to the correct time.
8. Alert Prefab
The alert is a GUI Texture that we'll show when the timer reaches 0. It will display a game over message at the center of the screen.
To create the alert, convert your alert image to a GUI Texture using the Inspector. Drag it from the Hierarchy panel to the Assets panel to convert it to a Prefab.
9.Timer Class
Let's now implement the Timer class. Select the Time GUI Text, click the Add Component button in the Inspector panel, and choose New Script. Name the script Timer and don't forget to change the language to C#. Open the newly created file and follow the next steps.
Step 1: Declare Variables
We start by creating a number of variables that we'll use in the Timer class.
private GUIText timeTF;
public GameObject alertReference
Let's take a look at each of the variables.
timeTF: a reference to the Time GUI Text
alertReference: a reference to the alert prefab
We'll use these references to access the time and alert game objects and change their values. Set the alert prefab in the Inspector.
Step 2: Setup
With the variables declared, we set the timeTF value by accessing the guiText property of the current game object. This will let us modify the text value later.
We also call the InvokeRepeating method, which will invoke the ReduceTime method every second.
The ReduceTime method is in charge of updating the timer text and displaying the alert message. The game is over when the time reaches 0. Add the following code block to the Timer class.
We start by testing if the time is about to end. If true, we pause the game by changing the timeScale property to 0, create an instance of the alert, and play the game over sound.
If the time is not about to end, we simply reduce its value by 1. To do this, we use the int.Parse method to convert the time string to a number, subtract 1, and call ToString on it to convert the result back to a string.
Step 4: Reload Method
This is the last part of the Timer class. In the Reload method, we call LoadLevel on the Application class and reload the current level, resetting every object and variable to its initial state.
This is what the complete class should look like when finished.
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour
{
private GUIText timeTF;
public GameObject alertReference;
void Start()
{
timeTF = gameObject.guiText;
InvokeRepeating("ReduceTime", 1, 1);
}
void ReduceTime()
{
if (timeTF.text == "1")
{
/* Alert */
Time.timeScale = 0;
Instantiate(alertReference, new Vector3(0.5f, 0.5f, 0), transform.rotation);
audio.Play();
GameObject.Find("AppleGUI").GetComponent<AudioSource>().Stop();
}
timeTF.text = (int.Parse(timeTF.text) - 1).ToString();
}
void Reload()
{
Application.LoadLevel (Application.loadedLevel);
}
}
10. Apple Prefab
The apple is one of the most important elements of the game and it is one of the interactive objects of the screen. The player is able to use the device's touch screen to cut the apple, increasing their score.
Drag the apple from the Assets panel to the Scene. Don't worry about its position, because we'll convert it to a Prefab in a moment and remove it from the Hierarchy.
Step 1: Add Rigidbody
To detect a collision with the apple, we need to add a Rigidbody to it. To add one, select Add Component from the Inspector panel and choose Physics > Rigidbody. You can leave the settings at their defaults.
Step 2: Add Box Collider
We also need to add a box collider to the apple to detect collisions. This collider will define the apple's hit area. Click the Add Component button in the Inspector panel, choose Physics > Box Collider, and change its values as shown in the screenshot below.
In the Scene panel, a green box should appear around the apple, representing the box collider we just added.
11. Splash Prefab
The splash prefab will be used as a visual effect for when the fruit is sliced by the player. It will appear on the stage for every fruit the player cuts and vanishes slowly over time. Convert the image to a Sprite as described earlier and add it to the Scene.
Add a script to it and drag it back to the Assets panel to create a Prefab. Open the newly created class.
12.Splash Class
The Splash class handles the images created when the fruit is sliced.
Step 1: Declare Variables
These variables are used to calculate and set an alpha value to the splash prefab. By changing its alpha property we can fade the prefab as time passes.
private Color randomAlpha;
private float currentAlpha;
Step 2: Setup
In this method we calculate a random alpha value from 0.3 to 0.5 and store that value in the randomAlpha variable. We then set the resulting alpha to the color property of the game object.
In the last line of code we invoke the method that will decrease that value every 300 milliseconds, creating a fading effect.
To reduce the alpha, we first need to obtain the current value. The currentAlpha variable stores this value. We then subtract 0.1 from that value and reassign the new alpha to the game object. The image is removed when it's almost invisible.
using UnityEngine;
using System.Collections;
public class Splash : MonoBehaviour
{
private Color randomAlpha;
private float currentAlpha;
void Start()
{
randomAlpha = new Color(1, 1, 1, Random.Range(0.3f, 0.5f));
gameObject.renderer.material.color = randomAlpha;
InvokeRepeating("ReduceAlpha", 0.3f, 0.3f);
}
void ReduceAlpha()
{
currentAlpha = gameObject.renderer.material.color.a;
if (gameObject.renderer.material.color.a <= 0.1f)
{
Destroy(gameObject);
} else
{
gameObject.renderer.material.color = new Color(1, 1, 1, currentAlpha - 0.1f);
}
}
}
13.Apple Class
With our splash prefab created, we can now continue with the Apple class. This class will handle actions, such as collision detection, updating the score, and removing the apple from the scene.
To get a reference to the score text we use the Find method. This method searches the active game objects and returns the object we're looking for, the score GUI Text in this case.
With the scoreReference variable set, we are now able to increase its value when a fruit is sliced.
Step 3: Destroy When Offstage
In the Update method, we check if the fruit is no longer visible on the screen by accessing its y position and removing it if true. This helps us release memory by destroying unused game objects.
void Update()
{
/* Remove fruit if out of view */
if (gameObject.transform.position.y < -36)
{
Destroy(gameObject);
}
}
Step 4: Handle Collisions
The next code uses the OnCollisionEnter method to detect when the fruit is sliced by the player. When this happens, we play the cut sound and remove the fruit. Next, we create a new instance of the splash prefab and update the score.
throwForce: the force used to push the fruits upwards
Step 2: Invoke Spawn
In the next lines of code, we call the InvokeRepeating method to invoke the SpawnFruit method every six seconds. This will add new fruits to the scene every six seconds, giving the player time to slice them before the fruit drops to the bottom of the scene.
The SpawnFruit method creates the fruits and pushes them upwards for the player to cut. We use a for statement to instantiate the fruits, position them randomly on the scene and apply a physics force using the addForce method.
void SpawnFruit()
{
for (byte i = 0; i < 4; i++)
{
GameObject fruit = Instantiate(appleReference, new Vector3(Random.Range(10, 30), Random.Range(-25, -35), -32), Quaternion.identity) as GameObject;
fruit.rigidbody.AddForce(throwForce, ForceMode.Impulse);
}
}
This is the complete FruitSpawner class.
using UnityEngine;
using System.Collections;
public class FruitSpawner : MonoBehaviour
{
[SerializeField]
private GameObject appleReference;
private Vector3 throwForce = new Vector3(0, 18, 0);
void Start()
{
InvokeRepeating("SpawnFruit", 0.5f, 6);
}
void SpawnFruit()
{
for (byte i = 0; i < 4; i++)
{
GameObject fruit = Instantiate(appleReference, new Vector3(Random.Range(10, 30), Random.Range(-25, -35), -32), Quaternion.identity) as GameObject;
fruit.rigidbody.AddForce(throwForce, ForceMode.Impulse);
}
}
}
15. Touch Controls
Let's now implement the touch controls. The player will be able to use the touch screen to cut the fruits. We'll visualize this by drawing a line using the LineRenderer class and then checking if the fruit collides with the player's swipe gesture.
Step 1: Declare Variables
We start by creating some variables.
c1, c2: these variables set the color of the line
lineGO: this game object will hold the line renderer
lineRenderer: the line renderer instance
i: an int value used to set the size and index of the line
public Color c1 = Color.yellow;
public Color c2 = Color.red;
private GameObject lineGO;
private LineRenderer lineRenderer;
private int i = 0;
Step 2: Setup
In the Start method, we set up the the necessary objects and properties for the line. We begin by creating a new GameObject instance containing the LineRenderer. We then use some of the line renderer methods to set the way it's going to look.
Most of the properties set in this block of code are easy to understand, SetColor changes the color of the line and SetWidth sets its width. Pay special attention to the SetVertexCount line. This method specifies the number of points of the line. By calling this method with a higher number of points, we can increase the size of the line. This will become clearer in the next step.
Step 3: Create Line
The line is created in the Update method. We first test if the player is touching the screen by retrieving the touchCount property of the Input class. If the property is greater that 0, it means there is at least one finger on the device's screen.
We keep a reference to the Touch object for easier access and check which phase it's currently in. We need it to be in the Moved phase to be able to create the line.
If the player is moving their finger across the screen, we can begin to create a line segment at that position. We invoke the SetVertexCount method again to increase the maximum number of segments of the line.
With the line in place, we add a collider to it to help us detect a collision with any of the fruits. The following code snippet creates and adds a box collider to the line using the AddComponent method and sets its position to the lineRenderer's current position. The last line of code changes the default size of the collider to match the line's size.
BoxCollider bc = lineGO.AddComponent<BoxCollider>();
bc.transform.position = lineRenderer.transform.position;
bc.size = new Vector3(0.1f, 0.1f, 0.1f);
Step 5: Remove Line
We remove the line when the player is no longer touching the screen. This prevents any unwanted collisions with the apples.
In the next code snippet, we check if the current phase of the Touch object is Ended and set the vertex count of the lineRenderer to 0. This will remove the current line segments, but it doesn't destroy the object, allowing us to reuse it later. We also reset the i variable to allow for later use.
if(touch.phase == TouchPhase.Ended)
{
/* Remove Line */
lineRenderer.SetVertexCount(0);
i = 0;
}
Step 6: Destroy Colliders
Once the line is removed, we no longer need the box colliders attached to it. We first create an array of BoxCollider objects, storing the box colliders of the line game object. We then loop over the array, destroying each box collider.
/* Remove Line Colliders */
BoxCollider[] lineColliders = lineGO.GetComponents<BoxCollider>();
foreach(BoxCollider b in lineColliders)
{
Destroy(b);
}
Let's take a look the the complete implementation of the LinesHandler class.
using UnityEngine;
using System.Collections;
public class LinesHandler : MonoBehaviour
{
public Color c1 = Color.yellow;
public Color c2 = Color.red;
private GameObject lineGO;
private LineRenderer lineRenderer;
private int i = 0;
void Start()
{
lineGO = new GameObject("Line");
lineGO.AddComponent<LineRenderer>();
lineRenderer = lineGO.GetComponent<LineRenderer>();
lineRenderer.material = new Material(Shader.Find("Mobile/Particles/Additive"));
lineRenderer.SetColors(c1, c2);
lineRenderer.SetWidth(0.3F, 0);
lineRenderer.SetVertexCount(0);
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{
lineRenderer.SetVertexCount(i+1);
Vector3 mPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 15);
lineRenderer.SetPosition(i, Camera.main.ScreenToWorldPoint(mPosition));
i++;
/* Add Collider */
BoxCollider bc = lineGO.AddComponent<BoxCollider>();
bc.transform.position = lineRenderer.transform.position;
bc.size = new Vector3(0.1f, 0.1f, 0.1f);
}
if(touch.phase == TouchPhase.Ended)
{
/* Remove Line */
lineRenderer.SetVertexCount(0);
i = 0;
/* Remove Line Colliders */
BoxCollider[] lineColliders = lineGO.GetComponents<BoxCollider>();
foreach(BoxCollider b in lineColliders)
{
Destroy(b);
}
}
}
}
}
16. Final Steps
Step 1: Testing
It's time to test the game. Press Command-P to play the game in Unity. If everything works as expected, then you're ready for the final steps.
Step 2: Player Settings
When you're happy with your game, it's time to select Build Settings from the File menu and click the Player Settings button. This should bring up the Player Settings in the Inspector panel where you can set the parameters for your application.
These settings are application specific data that includes the creator or company, app resolution and display mode, rendering mode (CPU, GPU), device OS compatibility, etc. Configure the settings according to the devices you're targeting and the store or market where you plan to publish the app.
Step 3: Icons and Splash Images
Using the graphics you created earlier, you can now create a nice icon and a splash image for your game. Unity shows you the required sizes, which depend on the platform you're building for.
Step 4: Build and Play
Once your project is properly configured, it's time to revisit the Build Settings and click the Build Button. That's all it takes to build your game for testing and/or distribution.
Conclusion
In this tutorial, we've learned how to use touch controls, physics forces, GUI Textures, and other aspects of game development in Unity. I encourage you to experiment with the result and customize the game to make it your own. I hope you liked this tutorial and found it helpful.
In this tutorial, you'll learn how to create a mobile 3D game using C# and Unity. The objective of the game is to cut the fruit that appears on the stage using the touch screen.
You will learn about the following aspects of Unity game development in this tutorial:
importing 3D models
swipe gestures
line renderers
physics forces
2D sprites
The user interface of the game is straightforward. The screenshot below gives you an idea of the artwork we'll be using and how the final user interface will end up looking. You can find the artwork and additional resources in the tutorial's source files on GitHub.
1. Project Setup
Step 1: Create a New Unity Project
Open Unity and select New Project from the File menu to open the new project dialog. Tell Unity where you want to save the project and set theSet up defaults for: menu to 3D.
Step 2: Configure Build Settings
In the next step, you're presented with Unity's user interface. Set the project up for mobile development by choosing Build Settings from the File menu and selecting your platform of choice.
Step 3: Artwork
The first thing we need to do after selecting the target platform is choosing the size of the artwork we'll be using in the game. This will help us select a proper size for the 3D textures and 2D GUI without making the artwork blurry or use textures that are too large for the target device. For example, the artwork needs to have a higher resolution if you're targeting an iPad with a retina display than a Lumia 520.
iOS
iPad without Retina: 1024px x 768px
iPad with Retina: 2048px x 1536px
3.5" iPhone/iPod Touch without Retina: 320px x 480px
3.5" iPhone/iPod with Retina: 960px x 640px
4" iPhone/iPod Touch: 1136px x 640px
Android
Because Android is an open platform, there's a wide range of devices, screen resolutions, and pixel densities. A few of the more common ones are listed below.
Asus Nexus 7 Tablet: 800px x 1280px, 216 ppi
Motorola Droid X: 854px x 480px, 228 ppi
Samsung Galaxy SIII: 720px x 1280px, 306 ppi
Windows Phone & BlackBerry
Blackberry Z10: 720px x 1280px, 355 ppi
Nokia Lumia 520: 400px x 800px, 233 ppi
Nokia Lumia 1520: 1080px x 1920px, 367 ppi
Note that the code we'll write in this tutorial can be used to target any of the platforms.
Step 4: Export Graphics
Depending on the devices you're targeting, you may need to convert the artwork to the recommended size and pixel density. You can do this in your favorite image editor. I've used the Adjust Size... function under the Tools menu in OS X's Preview application.
Step 5: Configure Unity's User Interface
Before we get started, make sure the 2D button in the Scene panel is not highlighted. You can also modify the resolution that's being displayed in the Game panel.
You're then presented with the workspace panels, which we'll also use in this tutorial. Take a moment to look at the main interface panels, such as the Scene, Game, Hierarchy, Project, Assets, and Inspector. We'll use them frequently in this tutorial.
Step 6: Programming Language
You can use one of three programming languages when using Unity, C#, UnityScript, a variation of JavaScript, and Boo. Each programming language has its pros and cons, and it's up to you to decide which one you prefer. My personal preference goes to the C# programming language so that's the language I'll be using in this tutorial.
If you decide to use another programming language, then make sure to take a look at Unity's Script Reference for examples.
2. Resources
Sound Effects
I'll use a number of sounds to improve the audial experience of the game. The sound effects used in this tutorial were obtained from PlayOnLoop and Freesound.
3D Models
To create the game, we first need to get a few 3D models. I recommend 3docean for high quality models and textures, but if you're testing or learning, then free models will work just as fine. The models in this tutorial were downloaded from SketchUp 3D Warehouse where you can find a wide variety of 3D models.
Because Unity doesn't recognize the SketchUp file format, we need to convert it to something Unity can import. We first need to download the free version of SketchUp, which is called SketchUp Make.
Open the 3D model in SketchUp Make, select Export > 3D Model from the File menu, and choose Collada (*.dae). Choose a name and location, and click Save. This will create a file and a folder for the 3D model. The file contains the data for the 3D object while the folder contains the model's textures. In the next step, we'll import the model into Unity.
3. Import Assets
Before we start coding, we need to add the assets to the Unity project. You can do this one of several ways:
select Import New Asset from the Assets menu
drag and drop the assets in the project window
add the items to the project's assets folder
After completing this step, you should see the assets in your project's Assets folder in the Project panel.
4. Setting Up Camera & Lighting
Step 1: Setting Up the Camera
In this step, we position the main camera to create the view we want. Select the main camera from the Hierarchy panel and adjust the Transform values in the Inspector to match the ones shown below.
Don't worry if you don't see any changes. We haven't created anything for the camera to see yet.
Step 2: Setting Up the Light
For our objects to be visible in the 3D world, we need to add light to the scene. Select Create Other from the GameObject menu and select Directional Light. This will create an object that produces a beam of light. Change its Transform values as shown in the following screenshot to make it illuminate the scene.
The light should be visible on the scene as shown in the following screenshot.
5. Add Background
We'll use a Sprite texture as our background. By default, images imported to the Assets folder are converted to Texture instances that can be applied to 3D objects. We need to change these Texture instances to Sprite Texture instances for the image we want to use as the background.
Select the image you want to convert in the Assets panel and open the Inspector. Select Sprite from the Texture Type menu.
Drag and drop the background into the Hierarchy panel. It should automatically appear in the Scene panel. Adjust the Transform values in the Inspector as shown in the next screenshot.
6. Create the Score GUI
To display the game's score, we'll use Unity's GUI Text and an imported 3D model.
Step 1: Adding the Apple Model
Select the imported 3D model of your choice from the Assets panel and drag and drop it on the Scene. I'm going to use an apple model. Adjust the Transform values in the Inspector to match the ones shown below.
This will place the apple at the top left of the screen.
Step 2: Adding the GUI Text
Along with the apple model, we'll display a number indicating the player's score. This is the number of fruits the player has cut.
Select Create Other > GUI Text from the GameObject menu to create a text object, place it on the right of the apple model, and change the text in the Inspector panel to 0.
You can embed a custom font by importing it in the Assets folder and changing the Font property of the text in the Inspector.
7. Create the Timer GUI
We'll use a timer to indicate when the game is over. It's composed of a GUI Texture showing an icon and a GUI Text displaying the remaining time.
Step 1: Adding the Clock Icon
To add the clock icon, select the image you want to use in the Assets panel and open the Inspector. Select GUI from the Texture Type menu to convert it to a GUI Texture. Drag and drop the image to the Scene and change its transform values to the ones shown below.
The scene should now look like this.
Step 2: Adding the GUI Text
Repeat the steps for adding the score text to add the timer text. Don't forget to set the text to the correct time.
8. Alert Prefab
The alert is a GUI Texture that we'll show when the timer reaches 0. It will display a game over message at the center of the screen.
To create the alert, convert your alert image to a GUI Texture using the Inspector. Drag it from the Hierarchy panel to the Assets panel to convert it to a Prefab.
9.Timer Class
Let's now implement the Timer class. Select the Time GUI Text, click the Add Component button in the Inspector panel, and choose New Script. Name the script Timer and don't forget to change the language to C#. Open the newly created file and follow the next steps.
Step 1: Declare Variables
We start by creating a number of variables that we'll use in the Timer class.
private GUIText timeTF;
public GameObject alertReference
Let's take a look at each of the variables.
timeTF: a reference to the Time GUI Text
alertReference: a reference to the alert prefab
We'll use these references to access the time and alert game objects and change their values. Set the alert prefab in the Inspector.
Step 2: Setup
With the variables declared, we set the timeTF value by accessing the guiText property of the current game object. This will let us modify the text value later.
We also call the InvokeRepeating method, which will invoke the ReduceTime method every second.
The ReduceTime method is in charge of updating the timer text and displaying the alert message. The game is over when the time reaches 0. Add the following code block to the Timer class.
We start by testing if the time is about to end. If true, we pause the game by changing the timeScale property to 0, create an instance of the alert, and play the game over sound.
If the time is not about to end, we simply reduce its value by 1. To do this, we use the int.Parse method to convert the time string to a number, subtract 1, and call ToString on it to convert the result back to a string.
Step 4: Reload Method
This is the last part of the Timer class. In the Reload method, we call LoadLevel on the Application class and reload the current level, resetting every object and variable to its initial state.
This is what the complete class should look like when finished.
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour
{
private GUIText timeTF;
public GameObject alertReference;
void Start()
{
timeTF = gameObject.guiText;
InvokeRepeating("ReduceTime", 1, 1);
}
void ReduceTime()
{
if (timeTF.text == "1")
{
/* Alert */
Time.timeScale = 0;
Instantiate(alertReference, new Vector3(0.5f, 0.5f, 0), transform.rotation);
audio.Play();
GameObject.Find("AppleGUI").GetComponent<AudioSource>().Stop();
}
timeTF.text = (int.Parse(timeTF.text) - 1).ToString();
}
void Reload()
{
Application.LoadLevel (Application.loadedLevel);
}
}
10. Apple Prefab
The apple is one of the most important elements of the game and it is one of the interactive objects of the screen. The player is able to use the device's touch screen to cut the apple, increasing their score.
Drag the apple from the Assets panel to the Scene. Don't worry about its position, because we'll convert it to a Prefab in a moment and remove it from the Hierarchy.
Step 1: Add Rigidbody
To detect a collision with the apple, we need to add a Rigidbody to it. To add one, select Add Component from the Inspector panel and choose Physics > Rigidbody. You can leave the settings at their defaults.
Step 2: Add Box Collider
We also need to add a box collider to the apple to detect collisions. This collider will define the apple's hit area. Click the Add Component button in the Inspector panel, choose Physics > Box Collider, and change its values as shown in the screenshot below.
In the Scene panel, a green box should appear around the apple, representing the box collider we just added.
11. Splash Prefab
The splash prefab will be used as a visual effect for when the fruit is sliced by the player. It will appear on the stage for every fruit the player cuts and vanishes slowly over time. Convert the image to a Sprite as described earlier and add it to the Scene.
Add a script to it and drag it back to the Assets panel to create a Prefab. Open the newly created class.
12.Splash Class
The Splash class handles the images created when the fruit is sliced.
Step 1: Declare Variables
These variables are used to calculate and set an alpha value to the splash prefab. By changing its alpha property we can fade the prefab as time passes.
private Color randomAlpha;
private float currentAlpha;
Step 2: Setup
In this method we calculate a random alpha value from 0.3 to 0.5 and store that value in the randomAlpha variable. We then set the resulting alpha to the color property of the game object.
In the last line of code we invoke the method that will decrease that value every 300 milliseconds, creating a fading effect.
To reduce the alpha, we first need to obtain the current value. The currentAlpha variable stores this value. We then subtract 0.1 from that value and reassign the new alpha to the game object. The image is removed when it's almost invisible.
using UnityEngine;
using System.Collections;
public class Splash : MonoBehaviour
{
private Color randomAlpha;
private float currentAlpha;
void Start()
{
randomAlpha = new Color(1, 1, 1, Random.Range(0.3f, 0.5f));
gameObject.renderer.material.color = randomAlpha;
InvokeRepeating("ReduceAlpha", 0.3f, 0.3f);
}
void ReduceAlpha()
{
currentAlpha = gameObject.renderer.material.color.a;
if (gameObject.renderer.material.color.a <= 0.1f)
{
Destroy(gameObject);
} else
{
gameObject.renderer.material.color = new Color(1, 1, 1, currentAlpha - 0.1f);
}
}
}
13.Apple Class
With our splash prefab created, we can now continue with the Apple class. This class will handle actions, such as collision detection, updating the score, and removing the apple from the scene.
To get a reference to the score text we use the Find method. This method searches the active game objects and returns the object we're looking for, the score GUI Text in this case.
With the scoreReference variable set, we are now able to increase its value when a fruit is sliced.
Step 3: Destroy When Offstage
In the Update method, we check if the fruit is no longer visible on the screen by accessing its y position and removing it if true. This helps us release memory by destroying unused game objects.
void Update()
{
/* Remove fruit if out of view */
if (gameObject.transform.position.y < -36)
{
Destroy(gameObject);
}
}
Step 4: Handle Collisions
The next code uses the OnCollisionEnter method to detect when the fruit is sliced by the player. When this happens, we play the cut sound and remove the fruit. Next, we create a new instance of the splash prefab and update the score.
throwForce: the force used to push the fruits upwards
Step 2: Invoke Spawn
In the next lines of code, we call the InvokeRepeating method to invoke the SpawnFruit method every six seconds. This will add new fruits to the scene every six seconds, giving the player time to slice them before the fruit drops to the bottom of the scene.
The SpawnFruit method creates the fruits and pushes them upwards for the player to cut. We use a for statement to instantiate the fruits, position them randomly on the scene and apply a physics force using the addForce method.
void SpawnFruit()
{
for (byte i = 0; i < 4; i++)
{
GameObject fruit = Instantiate(appleReference, new Vector3(Random.Range(10, 30), Random.Range(-25, -35), -32), Quaternion.identity) as GameObject;
fruit.rigidbody.AddForce(throwForce, ForceMode.Impulse);
}
}
This is the complete FruitSpawner class.
using UnityEngine;
using System.Collections;
public class FruitSpawner : MonoBehaviour
{
[SerializeField]
private GameObject appleReference;
private Vector3 throwForce = new Vector3(0, 18, 0);
void Start()
{
InvokeRepeating("SpawnFruit", 0.5f, 6);
}
void SpawnFruit()
{
for (byte i = 0; i < 4; i++)
{
GameObject fruit = Instantiate(appleReference, new Vector3(Random.Range(10, 30), Random.Range(-25, -35), -32), Quaternion.identity) as GameObject;
fruit.rigidbody.AddForce(throwForce, ForceMode.Impulse);
}
}
}
15. Touch Controls
Let's now implement the touch controls. The player will be able to use the touch screen to cut the fruits. We'll visualize this by drawing a line using the LineRenderer class and then checking if the fruit collides with the player's swipe gesture.
Step 1: Declare Variables
We start by creating some variables.
c1, c2: these variables set the color of the line
lineGO: this game object will hold the line renderer
lineRenderer: the line renderer instance
i: an int value used to set the size and index of the line
public Color c1 = Color.yellow;
public Color c2 = Color.red;
private GameObject lineGO;
private LineRenderer lineRenderer;
private int i = 0;
Step 2: Setup
In the Start method, we set up the the necessary objects and properties for the line. We begin by creating a new GameObject instance containing the LineRenderer. We then use some of the line renderer methods to set the way it's going to look.
Most of the properties set in this block of code are easy to understand, SetColor changes the color of the line and SetWidth sets its width. Pay special attention to the SetVertexCount line. This method specifies the number of points of the line. By calling this method with a higher number of points, we can increase the size of the line. This will become clearer in the next step.
Step 3: Create Line
The line is created in the Update method. We first test if the player is touching the screen by retrieving the touchCount property of the Input class. If the property is greater that 0, it means there is at least one finger on the device's screen.
We keep a reference to the Touch object for easier access and check which phase it's currently in. We need it to be in the Moved phase to be able to create the line.
If the player is moving their finger across the screen, we can begin to create a line segment at that position. We invoke the SetVertexCount method again to increase the maximum number of segments of the line.
With the line in place, we add a collider to it to help us detect a collision with any of the fruits. The following code snippet creates and adds a box collider to the line using the AddComponent method and sets its position to the lineRenderer's current position. The last line of code changes the default size of the collider to match the line's size.
BoxCollider bc = lineGO.AddComponent<BoxCollider>();
bc.transform.position = lineRenderer.transform.position;
bc.size = new Vector3(0.1f, 0.1f, 0.1f);
Step 5: Remove Line
We remove the line when the player is no longer touching the screen. This prevents any unwanted collisions with the apples.
In the next code snippet, we check if the current phase of the Touch object is Ended and set the vertex count of the lineRenderer to 0. This will remove the current line segments, but it doesn't destroy the object, allowing us to reuse it later. We also reset the i variable to allow for later use.
if(touch.phase == TouchPhase.Ended)
{
/* Remove Line */
lineRenderer.SetVertexCount(0);
i = 0;
}
Step 6: Destroy Colliders
Once the line is removed, we no longer need the box colliders attached to it. We first create an array of BoxCollider objects, storing the box colliders of the line game object. We then loop over the array, destroying each box collider.
/* Remove Line Colliders */
BoxCollider[] lineColliders = lineGO.GetComponents<BoxCollider>();
foreach(BoxCollider b in lineColliders)
{
Destroy(b);
}
Let's take a look the the complete implementation of the LinesHandler class.
using UnityEngine;
using System.Collections;
public class LinesHandler : MonoBehaviour
{
public Color c1 = Color.yellow;
public Color c2 = Color.red;
private GameObject lineGO;
private LineRenderer lineRenderer;
private int i = 0;
void Start()
{
lineGO = new GameObject("Line");
lineGO.AddComponent<LineRenderer>();
lineRenderer = lineGO.GetComponent<LineRenderer>();
lineRenderer.material = new Material(Shader.Find("Mobile/Particles/Additive"));
lineRenderer.SetColors(c1, c2);
lineRenderer.SetWidth(0.3F, 0);
lineRenderer.SetVertexCount(0);
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{
lineRenderer.SetVertexCount(i+1);
Vector3 mPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 15);
lineRenderer.SetPosition(i, Camera.main.ScreenToWorldPoint(mPosition));
i++;
/* Add Collider */
BoxCollider bc = lineGO.AddComponent<BoxCollider>();
bc.transform.position = lineRenderer.transform.position;
bc.size = new Vector3(0.1f, 0.1f, 0.1f);
}
if(touch.phase == TouchPhase.Ended)
{
/* Remove Line */
lineRenderer.SetVertexCount(0);
i = 0;
/* Remove Line Colliders */
BoxCollider[] lineColliders = lineGO.GetComponents<BoxCollider>();
foreach(BoxCollider b in lineColliders)
{
Destroy(b);
}
}
}
}
}
16. Final Steps
Step 1: Testing
It's time to test the game. Press Command-P to play the game in Unity. If everything works as expected, then you're ready for the final steps.
Step 2: Player Settings
When you're happy with your game, it's time to select Build Settings from the File menu and click the Player Settings button. This should bring up the Player Settings in the Inspector panel where you can set the parameters for your application.
These settings are application specific data that includes the creator or company, app resolution and display mode, rendering mode (CPU, GPU), device OS compatibility, etc. Configure the settings according to the devices you're targeting and the store or market where you plan to publish the app.
Step 3: Icons and Splash Images
Using the graphics you created earlier, you can now create a nice icon and a splash image for your game. Unity shows you the required sizes, which depend on the platform you're building for.
Step 4: Build and Play
Once your project is properly configured, it's time to revisit the Build Settings and click the Build Button. That's all it takes to build your game for testing and/or distribution.
Conclusion
In this tutorial, we've learned how to use touch controls, physics forces, GUI Textures, and other aspects of game development in Unity. I encourage you to experiment with the result and customize the game to make it your own. I hope you liked this tutorial and found it helpful.
In this quick tip, we take a brief look at the popular Android image library, Picasso. It's a simple and practical library created and maintained by Square. It is great for working with images in your Android projects.
1. Introduction
Picasso is an image library for Android. It's created and maintained by Square, and caters to
image loading and processing. It simplifies the process of displaying images from external locations. In many cases only a few lines of code is required to implement this neat library.
Picasso shines for displaying remote images. The
library handles every stage of the process, from the initial HTTP request to
the caching of the image. This can be quite verbose when writing
code to perform these actions yourself. In this quick tip, we look at a
few common use cases.
2. Installation
Start by downloading the JAR file from Picasso's website. Installing is done the usual manner. If you need help with this step, then take a look at this tutorial by Shane Condor and Lauren Darcey.
If you're using Android Studio, then you can add compile
'com.squareup.picasso:picasso:2.3.3' to the build.gradlefile in the dependency section.
3. Hands-On
Step 1: Create a new project
Create a new project in your IDE of choice. Make sure to select a blank Activity if you're using Android Studio.
Step 2: Image Widget
Open the layout file for the main Activity. We need to add an ImageView to the layout. It doesn't need to be fancy. The following code snippet shows you what I mean.
In the first line, we get a reference to the ImageView instance in the layout file. We then load an image into the image view using the Picasso library. We first specify the context by calling with and passing in the context. We then call the load method and supply it with the location of the image, a URL in this case. Finally, we tell Picasso where it should display the image when it's fetched by calling into and pass in the imageView object.
Your IDE will ask you to import the Picasso library. However, to do this manually add the following import statement at the top of the Activity class.
import com.squareup.picasso.Picasso;
Step 4: Permissions
For Picasso to do its work, make sure to add <uses-permission android:name="android.permission.INTERNET"
/> to your project's manifest.
Step 5: Build and Run
That’s pretty much it. If you build and run the application, you should see the image load on the screen.
4. More Examples
Picasso has much more tricks up its sleeve. In the following example, we use Picasso to fetch a remote image and resize it before displaying it in an image view.
Picasso also supports transformations, such as rotation. In the next code snippet, we fetch a remote image and rotate it 180 degrees before displaying it in an image view.
If your application relies on remote assets, then it's important to add a fallback in the form of a placeholder image. The placeholder image is shown immediately and replaced by the remote image when Picasso has finished fetching it.
Picasso supports two types of placeholder images. We already saw how the placeholder method works, but there's also an error method that accepts a placeholder image. Picasso will try to download the remote image three times and display the error placeholder image if it was unable to fetch the remote asset.
With Picasso being so simple to use, it's definitely worth thirty
minutes of your time. If you're creating an app that frequently loads images, then Picasso could well make your life that little bit simpler.
2014-11-03T15:45:04.000Z2014-11-03T15:45:04.000ZLeif Johnson
In this quick tip, we take a brief look at the popular Android image library, Picasso. It's a simple and practical library created and maintained by Square. It is great for working with images in your Android projects.
1. Introduction
Picasso is an image library for Android. It's created and maintained by Square, and caters to
image loading and processing. It simplifies the process of displaying images from external locations. In many cases only a few lines of code is required to implement this neat library.
Picasso shines for displaying remote images. The
library handles every stage of the process, from the initial HTTP request to
the caching of the image. This can be quite verbose when writing
code to perform these actions yourself. In this quick tip, we look at a
few common use cases.
2. Installation
Start by downloading the JAR file from Picasso's website. Installing is done the usual manner. If you need help with this step, then take a look at this tutorial by Shane Condor and Lauren Darcey.
If you're using Android Studio, then you can add compile
'com.squareup.picasso:picasso:2.3.3' to the build.gradlefile in the dependency section.
3. Hands-On
Step 1: Create a new project
Create a new project in your IDE of choice. Make sure to select a blank Activity if you're using Android Studio.
Step 2: Image Widget
Open the layout file for the main Activity. We need to add an ImageView to the layout. It doesn't need to be fancy. The following code snippet shows you what I mean.
In the first line, we get a reference to the ImageView instance in the layout file. We then load an image into the image view using the Picasso library. We first specify the context by calling with and passing in the context. We then call the load method and supply it with the location of the image, a URL in this case. Finally, we tell Picasso where it should display the image when it's fetched by calling into and pass in the imageView object.
Your IDE will ask you to import the Picasso library. However, to do this manually add the following import statement at the top of the Activity class.
import com.squareup.picasso.Picasso;
Step 4: Permissions
For Picasso to do its work, make sure to add <uses-permission android:name="android.permission.INTERNET"
/> to your project's manifest.
Step 5: Build and Run
That’s pretty much it. If you build and run the application, you should see the image load on the screen.
4. More Examples
Picasso has much more tricks up its sleeve. In the following example, we use Picasso to fetch a remote image and resize it before displaying it in an image view.
Picasso also supports transformations, such as rotation. In the next code snippet, we fetch a remote image and rotate it 180 degrees before displaying it in an image view.
If your application relies on remote assets, then it's important to add a fallback in the form of a placeholder image. The placeholder image is shown immediately and replaced by the remote image when Picasso has finished fetching it.
Picasso supports two types of placeholder images. We already saw how the placeholder method works, but there's also an error method that accepts a placeholder image. Picasso will try to download the remote image three times and display the error placeholder image if it was unable to fetch the remote asset.
With Picasso being so simple to use, it's definitely worth thirty
minutes of your time. If you're creating an app that frequently loads images, then Picasso could well make your life that little bit simpler.
2014-11-03T15:45:04.000Z2014-11-03T15:45:04.000ZLeif Johnson
The Facebook style sliding menu has become a widely used design pattern in mobile applications. In this tutorial, you'll learn how to use the power of HTML5 and Sencha Touch's Menu class to create your own sliding menu.
Introduction
I'm not sure if they were the first, but Facebook has certainly popularised the sliding menu design pattern. You are probably already familiar with the concept, but it looks like this:
The main content slides left or right, revealing a menu. The benefits of this approach include that it frees up more screen real estate—as opposed to having, for example, tabbed buttons at the bottom of the screen—and allows us to add more menu options without running out of space. It has become so ubiquitous that most users will immediately understand how to interact with it.
Given the usefulness and popularity of this approach, naturally Sencha Touch developers would want to include a sliding menu in their applications. People came up with some great solutions and ways to implement a sliding menu in Sencha Touch, but it often involved quite a bit of work.
Fortunately, since version 2.3.0, Sencha Touch supports sliding menus with the Ext.Menu class. In this tutorial, we will be walking through how to add a sliding menu to a newly generated Sencha Touch application.
1. Generate a New Application
I will assume at this point that you already have your environment set up for Sencha Touch development. If not, visit the Sencha Touch website and follow the instructions to get up and running.
Open up the command prompt and change your current directory to your Sencha Touch installation. In my case that is:
cd c:\xampp\htdocs\touch-2.4.0
Next, run the following command to generate a new application called SlidingMenu that will be stored in the htdocs folder:
sencha generate app SlidingMenu ../SlidingMenu
2. Restructuring the Application
The example application automatically generated by Sencha Cmd contains a tabbed navigation view by default, which we don't want. We will have to make a few changes to this before we add our menu. Open up your app/view/Main.js file and go through the following steps.
Step 1
Remove the default items added by Sencha Cmdso that your items config is empty. You should also remove the tabBarPosition configuration. Your config should now look like this:
config: {
items: [
]
}
Step 2
We won't need Ext.TitleBar or Ext.Video so you can remove those and instead add Ext.Menu as shown below.
requires: [
'Ext.Menu'
],
Step 3
We're going to use a card layout for our application. Rather than extending the Ext.tab.Panel class we're going to be extending the more generic Ext.Container class. After making these changes, your Main.js file should look like this:
We have a basic template to work from now and we can begin creating the functional elements of our sliding menu. Before we create the menu itself, we want a toolbar that runs across the top of the application. This toolbar will contain a button the user can tap to open and close the menu. All of the following changes will be made in app/view/Main.js.
Step 1
Add a toolbar as your first item and add a button as an item in the toolbar.
By giving the button an iconClsof list we will get the typical hamburger icon that is generally used for sliding menus. The plain configuration removes additional styling, leaving just the icon. I find this looks better, but feel free to omit that option.
Step 2
Add a handler to the button that will open and close the menu when tapped.
A handler is one of many ways to catch events in Sencha Touch. Every time the button is tapped our handler function will run, toggling the menu in and out as necessary.
It simply checks if the left menu is visible and, if it is, it will hide it. If it isn't visible, it will show it. Although typically on the left, menus can also be added to the top, right, and bottom. If your menu is going to be on a different side, then you should reflect that here.
Step 3
At this point, you can load the application in your browser to see your progress. You should see something like this.
Tapping the menu button will not work yet though. We need to create and add our menu to the application first.
4. Creating the Menu
We are going to create a function that will create the menu for us. This will be created outside of the configsection.
Step 1
Start by adding a createMenu function as shown below.
This function is also added after the config, just like the createMenu function was. The initialize function will automatically run when our view is ready. As soon as the view is ready our menu will be too.
If you load your application in your browser again, you should now be able to tap the list button to reveal the menu. It should look something like this:
To hide the menu, you should be able to tap the list icon again or swipe left on the container that has been pushed off to the right.
5. Listening for Events
There's not much point in creating a menu if the options don't do anything when tapped. We're now going to look at how to listen for button taps and how we might do something useful with those events, for example, changing the view. As we did before, we are going to use handler functions to achieve this.
Add a handler function to each of the buttons. If you tap on either of the menu items, you should see the corresponding line printed out to the console. Although it is out of scope for this tutorial, you could use this handler function in a similar fashion to trigger a switch to a new view.
In this tutorial, we covered how to generate a new Sencha Touch application, create a sliding menu, and allow users to hide and show the menu. The menu currently uses the default Sencha Touch styling so as an extension to this tutorial you may wish to add your own custom styling by editing your app.scss file. If you have any questions, feel free to leave them in the comments.
The Facebook style sliding menu has become a widely used design pattern in mobile applications. In this tutorial, you'll learn how to use the power of HTML5 and Sencha Touch's Menu class to create your own sliding menu.
Introduction
I'm not sure if they were the first, but Facebook has certainly popularised the sliding menu design pattern. You are probably already familiar with the concept, but it looks like this:
The main content slides left or right, revealing a menu. The benefits of this approach include that it frees up more screen real estate—as opposed to having, for example, tabbed buttons at the bottom of the screen—and allows us to add more menu options without running out of space. It has become so ubiquitous that most users will immediately understand how to interact with it.
Given the usefulness and popularity of this approach, naturally Sencha Touch developers would want to include a sliding menu in their applications. People came up with some great solutions and ways to implement a sliding menu in Sencha Touch, but it often involved quite a bit of work.
Fortunately, since version 2.3.0, Sencha Touch supports sliding menus with the Ext.Menu class. In this tutorial, we will be walking through how to add a sliding menu to a newly generated Sencha Touch application.
1. Generate a New Application
I will assume at this point that you already have your environment set up for Sencha Touch development. If not, visit the Sencha Touch website and follow the instructions to get up and running.
Open up the command prompt and change your current directory to your Sencha Touch installation. In my case that is:
cd c:\xampp\htdocs\touch-2.4.0
Next, run the following command to generate a new application called SlidingMenu that will be stored in the htdocs folder:
sencha generate app SlidingMenu ../SlidingMenu
2. Restructuring the Application
The example application automatically generated by Sencha Cmd contains a tabbed navigation view by default, which we don't want. We will have to make a few changes to this before we add our menu. Open up your app/view/Main.js file and go through the following steps.
Step 1
Remove the default items added by Sencha Cmdso that your items config is empty. You should also remove the tabBarPosition configuration. Your config should now look like this:
config: {
items: [
]
}
Step 2
We won't need Ext.TitleBar or Ext.Video so you can remove those and instead add Ext.Menu as shown below.
requires: [
'Ext.Menu'
],
Step 3
We're going to use a card layout for our application. Rather than extending the Ext.tab.Panel class we're going to be extending the more generic Ext.Container class. After making these changes, your Main.js file should look like this:
We have a basic template to work from now and we can begin creating the functional elements of our sliding menu. Before we create the menu itself, we want a toolbar that runs across the top of the application. This toolbar will contain a button the user can tap to open and close the menu. All of the following changes will be made in app/view/Main.js.
Step 1
Add a toolbar as your first item and add a button as an item in the toolbar.
By giving the button an iconClsof list we will get the typical hamburger icon that is generally used for sliding menus. The plain configuration removes additional styling, leaving just the icon. I find this looks better, but feel free to omit that option.
Step 2
Add a handler to the button that will open and close the menu when tapped.
A handler is one of many ways to catch events in Sencha Touch. Every time the button is tapped our handler function will run, toggling the menu in and out as necessary.
It simply checks if the left menu is visible and, if it is, it will hide it. If it isn't visible, it will show it. Although typically on the left, menus can also be added to the top, right, and bottom. If your menu is going to be on a different side, then you should reflect that here.
Step 3
At this point, you can load the application in your browser to see your progress. You should see something like this.
Tapping the menu button will not work yet though. We need to create and add our menu to the application first.
4. Creating the Menu
We are going to create a function that will create the menu for us. This will be created outside of the configsection.
Step 1
Start by adding a createMenu function as shown below.
This function is also added after the config, just like the createMenu function was. The initialize function will automatically run when our view is ready. As soon as the view is ready our menu will be too.
If you load your application in your browser again, you should now be able to tap the list button to reveal the menu. It should look something like this:
To hide the menu, you should be able to tap the list icon again or swipe left on the container that has been pushed off to the right.
5. Listening for Events
There's not much point in creating a menu if the options don't do anything when tapped. We're now going to look at how to listen for button taps and how we might do something useful with those events, for example, changing the view. As we did before, we are going to use handler functions to achieve this.
Add a handler function to each of the buttons. If you tap on either of the menu items, you should see the corresponding line printed out to the console. Although it is out of scope for this tutorial, you could use this handler function in a similar fashion to trigger a switch to a new view.
In this tutorial, we covered how to generate a new Sencha Touch application, create a sliding menu, and allow users to hide and show the menu. The menu currently uses the default Sencha Touch styling so as an extension to this tutorial you may wish to add your own custom styling by editing your app.scss file. If you have any questions, feel free to leave them in the comments.
In the landscape of mobile applications these days there are three main players: iOS, Android, and Windows Phone. While Windows Phone may be in a distant third place at the moment, it is definitely growing in popularity and provides an excellent opportunity for developers to capitalize on their skills.
Our new course, Windows Phone 8 Development, will show you how to get started developing for Windows Phone, and will provide you with a solid foundation of knowledge in XAML, MVVM, and platform-specific features.
Tuts+ instructor Derek Jensen will teach you the basics of what it takes to build mobile applications for the Windows Phone 8.1 platform. You'll learn how to use XAML, how to handle user gestures on the Windows Phone, how to use the Model‑View-ViewModel Pattern, and more.
By the end, you'll be ready to start developing your own mobile applications for the Windows Phone.
Watch the Introduction
Start Learning With a 14 Day Free Trial
You can take our new Windows Phone 8 Development course straight away with a completely free 14 day trial of a Tuts+ subscription. Start your free 14 day trial today, to access this course and hundreds of others.
In the landscape of mobile applications these days there are three main players: iOS, Android, and Windows Phone. While Windows Phone may be in a distant third place at the moment, it is definitely growing in popularity and provides an excellent opportunity for developers to capitalize on their skills.
Our new course, Windows Phone 8 Development, will show you how to get started developing for Windows Phone, and will provide you with a solid foundation of knowledge in XAML, MVVM, and platform-specific features.
Tuts+ instructor Derek Jensen will teach you the basics of what it takes to build mobile applications for the Windows Phone 8.1 platform. You'll learn how to use XAML, how to handle user gestures on the Windows Phone, how to use the Model‑View-ViewModel Pattern, and more.
By the end, you'll be ready to start developing your own mobile applications for the Windows Phone.
Watch the Introduction
Start Learning With a 14 Day Free Trial
You can take our new Windows Phone 8 Development course straight away with a completely free 14 day trial of a Tuts+ subscription. Start your free 14 day trial today, to access this course and hundreds of others.
With the release of iOS 7, Apple introduced a text to speech API that allows developers to add text to speech functionality to an application in a quick and easy way. This can be useful when adding an accessibility layer to an application or to include it as a feature in a learning game. In this tutorial, you'll learn how to implement such a feature using Swift.
1. Introduction
In this tutorial, you'll learn how to create a mobile application using Swift and Xcode 6. Whether you're familiar with Xcode or not, this tutorial will help you get comfortable with Apple's IDE and the Swift programming language. With the application, the user will be able to initialize the text to speech functionality by tapping a button on the screen. The user can edit the target text in a text view.
In this tutorial, you'll learn about the following aspects of iOS development:
creating a new project in Xcode 6
create a user interface in Interface Builder
connect the user interface elements using outlets
trigger methods in the user interface using actions
2. Project Setup
Step 1: Project Template
Open Xcode and select New > Project... from the File menu. Choose Single View Application from the list of iOS Application templates and click Next.
Step 2: Project Configuration
Name your project, enter your organization's name and identifier. Choose iPhone from the Devices list, click Next, and choose a location to save the project. Don't forget to change the language to Swift.
3. User Interface
The user interface of the app is straightforward. The screenshot below gives you an idea of the artwork we'll be using and how the final user interface will end up looking. You can find the artwork and additional resources in the tutorial's source files on GitHub.
Step 1: Add Text View
Let's create the text view that will contain the text the application will convert to audio. Open Main.storyboard and drag a UITextView object from the Object Library onto the view controller's view. You can change the text view's default text or leave it blank.
Step 2: Add Button
A button in the user interface will trigger the text to speech functionality. Drag and drop a UIButton object from the Object Library onto the view controller's view. You can change the button's title or change its appearance by adding an image in the Attributes Inspector.
4. Import AVFoundation
To use the text to speech API, we'll need access to the AVSpeechSynthesizer class, which is part of the AVFoundation framework. Select your project in Xcode and go to the Linked Frameworks and Libraries section at the bottom of the General tab. Click the plus button and select the AVFoundation framework from the list.
Open ViewController.swift and add the following code just below the import UIKit line.
import AVFoundation
This will make the classes of the AVFoundation framework available in the ViewController class, giving us access to the AVSpeechSynthesizer class that we need in a few moments.
5. Text View Outlet
To access the text view in the ViewController class, we need to create an outlet and wire it up in Interface Builder. An outlet is a property that you can set in Interface Builder.
Open the Assistant Editor by choosing Assistant Editor from the View menu. It lets us view the user interface of the ViewController class on the left and its implementation on the right. Be sure Xcode displays the ViewController.swift file on the right.
In Interface Builder, create an outlet for the text view by control-dragging from the text view to the code editor on the right. You'll notice a blue line, indicating where Xcode will insert the outlet for the text view.
When you release the mouse button, Xcode will show you a dialog in which you can set the name for the outlet. Name your outlet textView and click Connect.
You can recognize outlets by the @IBOutlet compiler directive. This tells the compiler that textView is a reference to the UITextView object we created in Interface Builder. This means that any change we make to textView is reflected in the UITextView object in the user interface.
@IBOutlet weak var textView: UITextView!
You'll notice two keywords following the compiler directive, weak and var. The weak keyword is an attribute used for references that don't need retention. This is commonly used for outlets since they are retained by their superview, the view controller's view in this case.
The second keyword, var, indicates that textView is a variable as opposed to a constant. The variable name is followed by a colon and the variable's type.
6. Speech Variables
Below the textView outlet, we declare a constant, synth, and a variable, myUtterance. The let keyword indicates that synth is declared as a constant. This means that the value of synth cannot be changed.
let synth = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: "")
The synth constant holds a reference to an AVSpeechSynthesizer instance. The myUtterance variable holds the string that we'll convert to speech a bit later.
7. Adding an Action
The button in the user interface should trigger a method named textToSpeech. To accomplish this, we need to create an action using the @IBAction type qualifier. By using the @IBAction type qualifier, the method will show up in Interface Builder as an action. Let's see how this works.
Open the Assistant Editor and make sure the XIB file is shown on the left and the ViewController class on the right. Select the button in Interface Builder and control-drag from the button to the ViewController class on the right as shown below.
Xcode will show you a similar dialog. This time, however, the connection type is Action. Name the action textToSpeech, make sure Event is set to Touch Up Inside, and click Connect.
As a result, Xcode will create a function or method or action for you that looks like the one shown below. The action is invoked when the user taps the button.
@IBAction func textToSpeech(sender: UIButton)
{
}
The func keyword declares a function or method. In this case, the name of the function is textToSpeech. You'll also notice a sender parameter of type UIButton, which references the UIButton we created in Interface Builder.
8. Implementing textToSpeech
The next block of code handles the text to speech conversion when the user taps the button.
We first create an AVSpeechUtterance instance by passing in the text of the textView object in the constructor. In the next line, we set the rate or speed at which the utterance will be spoken. The lower the rate, the slower the speech will be. Finally, we call the speakUtterance method on the AVSpeechSynthesizer instance, passing in the myUtterance object. This will start the text to speech.
This is what the complete the ViewController class should like.
import UIKit
import AVFoundation
class ViewController: UIViewController
{
@IBOutlet weak var textView: UITextView!
let synth = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: "")
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func textToSpeech(sender: UIButton)
{
myUtterance = AVSpeechUtterance(string: textView.text)
myUtterance.rate = 0.3
synth.speakUtterance(myUtterance)
}
}
9. Testing in the Simulator
It's time to test our application in the iOS Simulator. Press Command-R or press the play button in the top-left to run the application. Test the app by entering a string in the text view and tapping the button at the bottom.
Conclusion
In this tutorial, we've learned how to implement text to speech on iOS, use Interface Builder, create outlets and actions. I encourage you to experiment with the result and customize the app to make it your own. I hope you liked this tutorial and found it helpful.
With the release of iOS 7, Apple introduced a text to speech API that allows developers to add text to speech functionality to an application in a quick and easy way. This can be useful when adding an accessibility layer to an application or to include it as a feature in a learning game. In this tutorial, you'll learn how to implement such a feature using Swift.
1. Introduction
In this tutorial, you'll learn how to create a mobile application using Swift and Xcode 6. Whether you're familiar with Xcode or not, this tutorial will help you get comfortable with Apple's IDE and the Swift programming language. With the application, the user will be able to initialize the text to speech functionality by tapping a button on the screen. The user can edit the target text in a text view.
In this tutorial, you'll learn about the following aspects of iOS development:
creating a new project in Xcode 6
create a user interface in Interface Builder
connect the user interface elements using outlets
trigger methods in the user interface using actions
2. Project Setup
Step 1: Project Template
Open Xcode and select New > Project... from the File menu. Choose Single View Application from the list of iOS Application templates and click Next.
Step 2: Project Configuration
Name your project, enter your organization's name and identifier. Choose iPhone from the Devices list, click Next, and choose a location to save the project. Don't forget to change the language to Swift.
3. User Interface
The user interface of the app is straightforward. The screenshot below gives you an idea of the artwork we'll be using and how the final user interface will end up looking. You can find the artwork and additional resources in the tutorial's source files on GitHub.
Step 1: Add Text View
Let's create the text view that will contain the text the application will convert to audio. Open Main.storyboard and drag a UITextView object from the Object Library onto the view controller's view. You can change the text view's default text or leave it blank.
Step 2: Add Button
A button in the user interface will trigger the text to speech functionality. Drag and drop a UIButton object from the Object Library onto the view controller's view. You can change the button's title or change its appearance by adding an image in the Attributes Inspector.
4. Import AVFoundation
To use the text to speech API, we'll need access to the AVSpeechSynthesizer class, which is part of the AVFoundation framework. Select your project in Xcode and go to the Linked Frameworks and Libraries section at the bottom of the General tab. Click the plus button and select the AVFoundation framework from the list.
Open ViewController.swift and add the following code just below the import UIKit line.
import AVFoundation
This will make the classes of the AVFoundation framework available in the ViewController class, giving us access to the AVSpeechSynthesizer class that we need in a few moments.
5. Text View Outlet
To access the text view in the ViewController class, we need to create an outlet and wire it up in Interface Builder. An outlet is a property that you can set in Interface Builder.
Open the Assistant Editor by choosing Assistant Editor from the View menu. It lets us view the user interface of the ViewController class on the left and its implementation on the right. Be sure Xcode displays the ViewController.swift file on the right.
In Interface Builder, create an outlet for the text view by control-dragging from the text view to the code editor on the right. You'll notice a blue line, indicating where Xcode will insert the outlet for the text view.
When you release the mouse button, Xcode will show you a dialog in which you can set the name for the outlet. Name your outlet textView and click Connect.
You can recognize outlets by the @IBOutlet compiler directive. This tells the compiler that textView is a reference to the UITextView object we created in Interface Builder. This means that any change we make to textView is reflected in the UITextView object in the user interface.
@IBOutlet weak var textView: UITextView!
You'll notice two keywords following the compiler directive, weak and var. The weak keyword is an attribute used for references that don't need retention. This is commonly used for outlets since they are retained by their superview, the view controller's view in this case.
The second keyword, var, indicates that textView is a variable as opposed to a constant. The variable name is followed by a colon and the variable's type.
6. Speech Variables
Below the textView outlet, we declare a constant, synth, and a variable, myUtterance. The let keyword indicates that synth is declared as a constant. This means that the value of synth cannot be changed.
let synth = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: "")
The synth constant holds a reference to an AVSpeechSynthesizer instance. The myUtterance variable holds the string that we'll convert to speech a bit later.
7. Adding an Action
The button in the user interface should trigger a method named textToSpeech. To accomplish this, we need to create an action using the @IBAction type qualifier. By using the @IBAction type qualifier, the method will show up in Interface Builder as an action. Let's see how this works.
Open the Assistant Editor and make sure the XIB file is shown on the left and the ViewController class on the right. Select the button in Interface Builder and control-drag from the button to the ViewController class on the right as shown below.
Xcode will show you a similar dialog. This time, however, the connection type is Action. Name the action textToSpeech, make sure Event is set to Touch Up Inside, and click Connect.
As a result, Xcode will create a function or method or action for you that looks like the one shown below. The action is invoked when the user taps the button.
@IBAction func textToSpeech(sender: UIButton)
{
}
The func keyword declares a function or method. In this case, the name of the function is textToSpeech. You'll also notice a sender parameter of type UIButton, which references the UIButton we created in Interface Builder.
8. Implementing textToSpeech
The next block of code handles the text to speech conversion when the user taps the button.
We first create an AVSpeechUtterance instance by passing in the text of the textView object in the constructor. In the next line, we set the rate or speed at which the utterance will be spoken. The lower the rate, the slower the speech will be. Finally, we call the speakUtterance method on the AVSpeechSynthesizer instance, passing in the myUtterance object. This will start the text to speech.
This is what the complete the ViewController class should like.
import UIKit
import AVFoundation
class ViewController: UIViewController
{
@IBOutlet weak var textView: UITextView!
let synth = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: "")
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func textToSpeech(sender: UIButton)
{
myUtterance = AVSpeechUtterance(string: textView.text)
myUtterance.rate = 0.3
synth.speakUtterance(myUtterance)
}
}
9. Testing in the Simulator
It's time to test our application in the iOS Simulator. Press Command-R or press the play button in the top-left to run the application. Test the app by entering a string in the text view and tapping the button at the bottom.
Conclusion
In this tutorial, we've learned how to implement text to speech on iOS, use Interface Builder, create outlets and actions. I encourage you to experiment with the result and customize the app to make it your own. I hope you liked this tutorial and found it helpful.
Apps with interfaces that make use of voice have a unique appeal. They tend to make their users feel that they are using something futuristic. Since its early days, Android has had very robust text-to-speech (TTS) functionality. This year, Google has added a lot of high-quality voices to its TTS engine and that's all the more reason for developers to use it in their apps.
In this tutorial, you'll learn how to create a simple app—with a minimalist user interface—that can receive text messages and read them to the user.
Prerequisites
Ensure that you have the Eclipse ADT Bundle set up. You can download it at the Android Developer website. For best results, you are also going to need a real Android device and some friends who can send you text messages.
1. Create a New Project
Start Eclipse, and create a new Android application. Call this application SMSReader. If you think you are going to publish this app to Google Play to share it with your friends, then make sure you use a unique package name. Set the Minimum Required SDK to Android 2.2 and set the Target SDK to Android 4.4.
This app will have one Activity. Select Create Activity and choose Empty Activity.
Name it MainActivity and click Finish.
2. Edit the Manifest
This app needs three permissions:
RECEIVE_SMS to know that the device has received an SMS
READ_SMS to read that SMS
READ_CONTACTS to map the phone number of the sender to a name (if possible)
Add the following lines to your AndroidManifest.xml.
This app is going to have only one screen orientation, portrait. Therefore, edit the activity tag and add the following attribute to it:
android:screenOrientation="portrait"
The manifest is now complete.
3. Edit strings.xml
It is not absolutely necessary, but storing all strings that the application uses in the res/values/strings.xml file is a good practice. Edit this file so that it has the following contents:
<?xml version="1.0" encoding="utf-8"?><resources><string name="app_name">SMSReader</string><string name="sms_label">Latest SMS</string><string name="none">None</string><string name="speech_toggle_on">START SPEAKING</string><string name="speech_toggle_off">STOP SPEAKING</string><string name="start_speaking">Okay! I will read your messages out loud for you now.</string><string name="stop_speaking">Okay! I will stay silent now.</string></resources>
Most of these strings are used in the next step.
4. Edit the Layout
Edit res/layout/activity_main.xml to add the following:
a TextView to display the name of the person who sent the latest SMS
a TextView to display the contents of the latest SMS
a ToggleButton to toggle speech output on and off
After adding code for positioning and styling these elements, your file should have the following contents:
We're now going to create a helper class for the TTS engine. Create a new Java class and call it Speaker.java. This class is used to avoid calling the TTS API directly from the Activity.
This class implements the OnInitListener interface so that it knows when the TTS engine is ready. We store this ready state in a boolean variable named ready. We use another boolean variable named allowed whose value is true only if the user has allowed the TTS engine to speak. We also add methods to get and set the value of this variable. At this point, Speaker.java should have the following contents:
public class Speaker implements OnInitListener {
private TextToSpeech tts;
private boolean ready = false;
private boolean allowed = false;
public Speaker(Context context){
tts = new TextToSpeech(context, this);
}
public boolean isAllowed(){
return allowed;
}
public void allow(boolean allowed){
this.allowed = allowed;
}
}
The OnInitListener interface has only one method, onInit. This method is called when the TTS engine has been initialized. The status parameter lets us know if the initialization was successful. Once we know that the initialization was successful, we set the language of the TTS engine. This is important to produce speech that is comprehensible. Add the following code:
@Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
// Change this to match your
// locale
tts.setLanguage(Locale.US);
ready = true;
}else{
ready = false;
}
}
Next, we add a method named speak, which uses the engine to read out any text that is passed to it. Before doing so, it checks if both the allowed and the ready values are true. The speech it generates is placed in the notification stream.
public void speak(String text){
// Speak only if the TTS is ready
// and the user has allowed speech
if(ready && allowed) {
HashMap<String, String> hash = new HashMap<String,String>();
hash.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_NOTIFICATION));
tts.speak(text, TextToSpeech.QUEUE_ADD, hash);
}
}
We then add a method that plays silence for a specified duration. Using this method, we can add pauses to the speech to make it sound a little clearer. Add the following code to the implementation:
public void pause(int duration){
tts.playSilence(duration, TextToSpeech.QUEUE_ADD, null);
}
Finally, add a method to free up resources when the TTS engine is no longer needed.
// Free up resources
public void destroy(){
tts.shutdown();
}
6. Edit the Activity Class
Edit MainActivity.java and declare all the views that we mentioned in the layout. Declare two integers, LONG_DURATION and SHORT_DURATION. These are merely values that are passed to the Speaker's pause method.
Also declare a CHECK_CODE integer. It's value isn't important. It is passed to the startActivityforResult method and then used to identify the result.
Lastly, declare a Speaker object and a BroadcastReceiver object.
At this point, your class should look like this:
public class MainActivity extends Activity {
private final int CHECK_CODE = 0x1;
private final int LONG_DURATION = 5000;
private final int SHORT_DURATION = 1200;
private Speaker speaker;
private ToggleButton toggle;
private OnCheckedChangeListener toggleListener;
private TextView smsText;
private TextView smsSender;
private BroadcastReceiver smsReceiver;
}
Add a method to check if a TTS engine is installed on the device. The check is performed by making use of the result of another Activity.
When the result of startActivityForResult arrives, the onActivityResult method is called. Therefore, we need to override it. In this method, if the result is positive, we initialize the Speaker object. If no TTS engine is installed, we redirect the user to install it.
It is now time to create our BroadcastReceiver to deal with the messages that the device is receiving. Whenever there are new messages, its onReceive method is called. We parse the messages, which arrive as byte arrays, using the SmsMessage class. Once the message is parsed, we use methods like getDisplayMessageBody and getOriginatingAddress to extract meaningful information out of it.
With this information, we generate the text that the TTS engine should read out. We pause for LONG_DURATION before reading out a new SMS and for SHORT_DURATION between the utterances of the SMS sender's name and the SMS's body.
Add the following code to the implementation:
private void initializeSMSReceiver(){
smsReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle!=null){
Object[] pdus = (Object[])bundle.get("pdus");
for(int i=0;i<pdus.length;i++){
byte[] pdu = (byte[])pdus[i];
SmsMessage message = SmsMessage.createFromPdu(pdu);
String text = message.getDisplayMessageBody();
String sender = getContactName(message.getOriginatingAddress());
speaker.pause(LONG_DURATION);
speaker.speak("You have a new message from" + sender + "!");
speaker.pause(SHORT_DURATION);
speaker.speak(text);
smsSender.setText("Message from " + sender);
smsText.setText(text);
}
}
}
};
}
We can only extract the phone number of the sender from the message. To map this number to a contact's name, we have to make use of the user's contacts. The following method queries the contacts data. If the phone number is not available in the user's contacts, then it simply returns the string unknown number:
Before the BroadcastReceiver can be used, it has to be registered. In the following method, we create an IntentFilter for incoming text messages and then register our smsReceiver for it:
Next, we create the onCreate method. Here's where we initialize all the objects we declared. We initialize the toggleListener to set the value of allowed in the Speaker class.
After these initializations, we call the checkTTS, initializeSMSReceiver, and registerSMSReceiver methods.
The app is now ready to be tested. Compile and run it on a physical Android device. Tap the toggle button to enable voice and send yourself an SMS from another phone or ask one of your friends to do so. You should soon be able to hear your phone read out the SMS for you.
Here is a sample of the speech generated by the TTS engine:
Conclusion
In this tutorial, you have learnt to not only use the text-to-speech API, but also to use broadcast receivers and to make sense out of raw SMS data. You can now go on to further customize this app to you needs.
Apps with interfaces that make use of voice have a unique appeal. They tend to make their users feel that they are using something futuristic. Since its early days, Android has had very robust text-to-speech (TTS) functionality. This year, Google has added a lot of high-quality voices to its TTS engine and that's all the more reason for developers to use it in their apps.
In this tutorial, you'll learn how to create a simple app—with a minimalist user interface—that can receive text messages and read them to the user.
Prerequisites
Ensure that you have the Eclipse ADT Bundle set up. You can download it at the Android Developer website. For best results, you are also going to need a real Android device and some friends who can send you text messages.
1. Create a New Project
Start Eclipse, and create a new Android application. Call this application SMSReader. If you think you are going to publish this app to Google Play to share it with your friends, then make sure you use a unique package name. Set the Minimum Required SDK to Android 2.2 and set the Target SDK to Android 4.4.
This app will have one Activity. Select Create Activity and choose Empty Activity.
Name it MainActivity and click Finish.
2. Edit the Manifest
This app needs three permissions:
RECEIVE_SMS to know that the device has received an SMS
READ_SMS to read that SMS
READ_CONTACTS to map the phone number of the sender to a name (if possible)
Add the following lines to your AndroidManifest.xml.
This app is going to have only one screen orientation, portrait. Therefore, edit the activity tag and add the following attribute to it:
android:screenOrientation="portrait"
The manifest is now complete.
3. Edit strings.xml
It is not absolutely necessary, but storing all strings that the application uses in the res/values/strings.xml file is a good practice. Edit this file so that it has the following contents:
<?xml version="1.0" encoding="utf-8"?><resources><string name="app_name">SMSReader</string><string name="sms_label">Latest SMS</string><string name="none">None</string><string name="speech_toggle_on">START SPEAKING</string><string name="speech_toggle_off">STOP SPEAKING</string><string name="start_speaking">Okay! I will read your messages out loud for you now.</string><string name="stop_speaking">Okay! I will stay silent now.</string></resources>
Most of these strings are used in the next step.
4. Edit the Layout
Edit res/layout/activity_main.xml to add the following:
a TextView to display the name of the person who sent the latest SMS
a TextView to display the contents of the latest SMS
a ToggleButton to toggle speech output on and off
After adding code for positioning and styling these elements, your file should have the following contents:
We're now going to create a helper class for the TTS engine. Create a new Java class and call it Speaker.java. This class is used to avoid calling the TTS API directly from the Activity.
This class implements the OnInitListener interface so that it knows when the TTS engine is ready. We store this ready state in a boolean variable named ready. We use another boolean variable named allowed whose value is true only if the user has allowed the TTS engine to speak. We also add methods to get and set the value of this variable. At this point, Speaker.java should have the following contents:
public class Speaker implements OnInitListener {
private TextToSpeech tts;
private boolean ready = false;
private boolean allowed = false;
public Speaker(Context context){
tts = new TextToSpeech(context, this);
}
public boolean isAllowed(){
return allowed;
}
public void allow(boolean allowed){
this.allowed = allowed;
}
}
The OnInitListener interface has only one method, onInit. This method is called when the TTS engine has been initialized. The status parameter lets us know if the initialization was successful. Once we know that the initialization was successful, we set the language of the TTS engine. This is important to produce speech that is comprehensible. Add the following code:
@Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
// Change this to match your
// locale
tts.setLanguage(Locale.US);
ready = true;
}else{
ready = false;
}
}
Next, we add a method named speak, which uses the engine to read out any text that is passed to it. Before doing so, it checks if both the allowed and the ready values are true. The speech it generates is placed in the notification stream.
public void speak(String text){
// Speak only if the TTS is ready
// and the user has allowed speech
if(ready && allowed) {
HashMap<String, String> hash = new HashMap<String,String>();
hash.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_NOTIFICATION));
tts.speak(text, TextToSpeech.QUEUE_ADD, hash);
}
}
We then add a method that plays silence for a specified duration. Using this method, we can add pauses to the speech to make it sound a little clearer. Add the following code to the implementation:
public void pause(int duration){
tts.playSilence(duration, TextToSpeech.QUEUE_ADD, null);
}
Finally, add a method to free up resources when the TTS engine is no longer needed.
// Free up resources
public void destroy(){
tts.shutdown();
}
6. Edit the Activity Class
Edit MainActivity.java and declare all the views that we mentioned in the layout. Declare two integers, LONG_DURATION and SHORT_DURATION. These are merely values that are passed to the Speaker's pause method.
Also declare a CHECK_CODE integer. It's value isn't important. It is passed to the startActivityforResult method and then used to identify the result.
Lastly, declare a Speaker object and a BroadcastReceiver object.
At this point, your class should look like this:
public class MainActivity extends Activity {
private final int CHECK_CODE = 0x1;
private final int LONG_DURATION = 5000;
private final int SHORT_DURATION = 1200;
private Speaker speaker;
private ToggleButton toggle;
private OnCheckedChangeListener toggleListener;
private TextView smsText;
private TextView smsSender;
private BroadcastReceiver smsReceiver;
}
Add a method to check if a TTS engine is installed on the device. The check is performed by making use of the result of another Activity.
When the result of startActivityForResult arrives, the onActivityResult method is called. Therefore, we need to override it. In this method, if the result is positive, we initialize the Speaker object. If no TTS engine is installed, we redirect the user to install it.
It is now time to create our BroadcastReceiver to deal with the messages that the device is receiving. Whenever there are new messages, its onReceive method is called. We parse the messages, which arrive as byte arrays, using the SmsMessage class. Once the message is parsed, we use methods like getDisplayMessageBody and getOriginatingAddress to extract meaningful information out of it.
With this information, we generate the text that the TTS engine should read out. We pause for LONG_DURATION before reading out a new SMS and for SHORT_DURATION between the utterances of the SMS sender's name and the SMS's body.
Add the following code to the implementation:
private void initializeSMSReceiver(){
smsReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle!=null){
Object[] pdus = (Object[])bundle.get("pdus");
for(int i=0;i<pdus.length;i++){
byte[] pdu = (byte[])pdus[i];
SmsMessage message = SmsMessage.createFromPdu(pdu);
String text = message.getDisplayMessageBody();
String sender = getContactName(message.getOriginatingAddress());
speaker.pause(LONG_DURATION);
speaker.speak("You have a new message from" + sender + "!");
speaker.pause(SHORT_DURATION);
speaker.speak(text);
smsSender.setText("Message from " + sender);
smsText.setText(text);
}
}
}
};
}
We can only extract the phone number of the sender from the message. To map this number to a contact's name, we have to make use of the user's contacts. The following method queries the contacts data. If the phone number is not available in the user's contacts, then it simply returns the string unknown number:
Before the BroadcastReceiver can be used, it has to be registered. In the following method, we create an IntentFilter for incoming text messages and then register our smsReceiver for it:
Next, we create the onCreate method. Here's where we initialize all the objects we declared. We initialize the toggleListener to set the value of allowed in the Speaker class.
After these initializations, we call the checkTTS, initializeSMSReceiver, and registerSMSReceiver methods.
The app is now ready to be tested. Compile and run it on a physical Android device. Tap the toggle button to enable voice and send yourself an SMS from another phone or ask one of your friends to do so. You should soon be able to hear your phone read out the SMS for you.
Here is a sample of the speech generated by the TTS engine:
Conclusion
In this tutorial, you have learnt to not only use the text-to-speech API, but also to use broadcast receivers and to make sense out of raw SMS data. You can now go on to further customize this app to you needs.
Mobile development with web technologies is nothing new. Thanks to tools like PhoneGap and Appcelerator Titanium, web developers can create hybrid apps that have access to the device's hardware. A new solution for HTML5/CSS/JavaScript development is Intel's XDK. In this article, I'll tell you why it's worth giving it a try.
1. What is it?
If you are involved with mobile development, you've probably heard of or used tools such as PhoneGap or Appcelerator Titanium. These tools allow web developers to use their web development skills to create hybrid mobile apps.
Last year, Intel purchased appMobi and packaged their development tools into the Intel XDK. This streamlined, unified product is a complete toolset for mobile development. A developer can go from the first lines of code to a fully compiled application in with just one set of tools. And best of all, the XDK is free to download.
2. Features
The first thing you'll notice about the XDK is how easy it is to install. PhoneGap requires extensive configuration and Titanium has specific requirements with regards to installed libraries. To get up and running with the XDK, you download it and install it.
The beauty of XDK is that you can build applications for any platform. With other tools, you are limited to the platform you are developing on. Since Apple won't let Xcode tools run on anything but a machine running OS X, you must have a Mac to develop for iOS.
Intel XDK lets you develop on any platform, because compiling is done in the cloud. PhoneGap offers a similar service for cross platform development, but it's limited. And with the XDK you aren't limited to mobile platforms. Do you plan to build Chrome, Facebook, Amazon, or Nook apps? The XDK can build for those targets as well as the option to compile with XDK or Cordova (PhoneGap) API's.
The XDK ships with the open source Brackets editor from Adobe. Titanium has a decent editor, but I prefer the XDK solution. Additionally, you have access to some of the extensions available to Brackets. The only drawback is that you can't update the Brackets editor that's integrated with the XDK. However, it's still a step up from Titanium, and PhoneGap doesn't even come with an editor.
The XDK also includes a graphical editor, which is sorely missing in all of the HTML5 mobile platforms. It stands to reason using HTML components would benefit from a WYSIWYG editor. It also supports frameworks such as Bootstrap and jQuery Mobile. These user interface components allow you to quickly build out the interface of your app.
Once your app is created, you need a way to test out its functionality. Intel XDK includes the best emulator for mobile devices I've seen to date. It includes the capability to test on real devices and profile performance without having to install anything.
3. Build a Mobile App with Intel XDK
Step 1: Download and install
Go to the Intel XDK download page and get the latest version of XDK. After downloading the package, install it with the default options.
Step 2: Create a New Project
We're going to build a small picture app. Start the XDK and choose Start a New Project. Some of the options you have are:
Start with a Demo: This option allows you to use one of the many demo projects Intel offers. This is good to help understand how to develop with the XDK.
Start with a Template: This option offers a number of templates for various user interface styles. It also has a blank Cordova template to get you started.
Import an Existing HTML5 Project: With this option, you can import a project made outside the XDK, such as a PhoneGap project coded in your editor of choice. It also lets you import XDK projects.
Use App Starter/Start with App Designer: App Starter can be considered App Designer Lite. Both are graphical interfaces to go along with the Brackets editor. App Starter uses App Framework. App Designer adds options for the Bootstrap, jQuery Mobile, and Topcoat user interface frameworks.
Start with a Blank Project: As the name implies, this option gives us a blank project with a template to get us started. This is the option we will choose for this tutorial.
Give your project a name and click Create. The XDK will create your project as well as a folder structure.
Step 3: Project Structure
Even though we started a blank project, the XDK includes some files to get you started. We are going to edit these files for our project.
init-dev.js
This file is used to detect ready events from the various libraries in use. This file will be used as is. It includes many log statements for debugging purposes and to better understand how the file works. The part we are most concerned with starts at line 106.
The first line creates a new event object. We initialize this object with the value "app.ready". The last line dispatches the event to the DOM.
init-app.js
I've deleted most of this file's contents, except for the part we need. We make sure that the libraries we need have been loaded and that the device is ready before we execute any of our code. Remember the app.ready event from the previous file?
The initEvents function does two things. First, it binds a click event listener to a button using jQuery. Second, it adds an event listener for the XDK intel.xdk.camera.picture.add event.
app.js
This file contains the meat of our app and contains the functions that runs our app. The replacer function uses jQuery to replace the image on the page with the most recent picture taken.
function replacer(pic) {
$("img").replaceWith(pic);
}
The name of the takePic function says it all. It uses the XDK framework to take a picture.
function takePic() {
intel.xdk.camera.takePicture(50,false,"jpg");
}
The onSuccess function fires when a intel.xdk.camera.picture.add event is detected. If a picture was successfully taken, it will replace the current image on the page using the replacer function we saw earlier. If the app was not able to take a picture, it will display an error message.
function onSuccess(evt) {
if (evt.success == true) {
var image = document.createElement('img');
image.src=intel.xdk.camera.getPictureURL(evt.filename);
image.setAttribute ("style","width:100%;height:200px;");
image.id=evt.filename;
replacer(image);
}
else {
if (evt.message != undefined) {
alert(evt.message);
}
else
{
alert("error capturing picture");
}
}
}
index.html
This file contains the main page of our app. It's a simple HTML file in which we pull in jQuery and jQuery Mobile.
We also import a few stylesheets to style the app. The custom stylesheet, app.css, has very little in the way of styling. That is because I use the jQuery Mobile theme roller to style the app.
The page itself is a standard jQuery Mobile page with a header, content, and footer section. Notice the image inside the div#info tag. This is the image that's replaced by the picture taken by the camera.
We also import a number of key scripts that make the app tick, such as Cordova and Intel XDK, and app.js.
<script src="intelxdk.js"></script> <!-- phantom library, needed for XDK api calls --><script src="cordova.js"></script> <!-- phantom library, needed for Cordova api calls --><script src="xhr.js"></script> <!-- phantom library, needed for XDK CORS --><script src="js/app.js"></script><script src="js/init-dev.js"></script><script src="js/init-app.js"></script>
4. Enabling Plugins
We're going to be using the Intel XDK API to take pictures. To make this work, we have to enable a few plugins. Open the Projects tab and, in the middle, you'll see CORDOVA 3.X HYBRID MOBILE APP SETTINGS. Click the plus button next to plugins and permissions. On the right, under Intel XDK Plugins, check Camera.
5. Using the Emulator
Click the Emulate tab and try out the functionality of the app. When you click on the Take Selfi button, it should bring up the picture window. After taking a picture, the picture should replace the placeholder image.
6. Testing the App
Download and install the Intel App Preview app from Google Play or Apple's App Store. Go to the Test tabs and copy the weinre script tag if you want to perform debugging with App Preview. Click on the PUSH FILES button to upload your app to Intel's servers. Log on to App Preview with your credentials from the Intel XDK and choose the app you uploaded.
7. Building the App
Now that we have tested the app, the last task is to build it for distribution. Click on the Build tab to display your options. As you can see, we have a wide range of targets to build for.
Since we used the Camera API, which is Legacy, we will choose the Legacy Hybrid app. This brings us to the build page as shown below.
Clicking on Details shows you options for in-app billing, streaming audio, etc.
After choosing the options for your app, click on the build button. After a few moments, the file is built and you will get a dialog that lets you download your app.
Conclusion
I hope you agree that it's easy to create an app with Intel XDK. Whether you're a veteran, full stack web developer or just starting to get into development, Intel XDK has an entry point for you. It's easy to pick up and I encourage you to give the Intel XDK a try.
tag:code.tutsplus.com,2005:PostPresenter/cms-22205Mobile development with web technologies is nothing new. Thanks to tools like PhoneGap and Appcelerator Titanium, web developers can create hybrid apps that have access to the device's hardware. A new solution for HTML5/CSS/JavaScript development is Intel's XDK. In this article, I'll tell you why it's worth giving it a try.
1. What is it?
If you are involved with mobile development, you've probably heard of or used tools such as PhoneGap or Appcelerator Titanium. These tools allow web developers to use their web development skills to create hybrid mobile apps.
Last year, Intel purchased appMobi and packaged their development tools into the Intel XDK. This streamlined, unified product is a complete toolset for mobile development. A developer can go from the first lines of code to a fully compiled application in with just one set of tools. And best of all, the XDK is free to download.
2. Features
The first thing you'll notice about the XDK is how easy it is to install. PhoneGap requires extensive configuration and Titanium has specific requirements with regards to installed libraries. To get up and running with the XDK, you download it and install it.
The beauty of XDK is that you can build applications for any platform. With other tools, you are limited to the platform you are developing on. Since Apple won't let Xcode tools run on anything but a machine running OS X, you must have a Mac to develop for iOS.
Intel XDK lets you develop on any platform, because compiling is done in the cloud. PhoneGap offers a similar service for cross platform development, but it's limited. And with the XDK you aren't limited to mobile platforms. Do you plan to build Chrome, Facebook, Amazon, or Nook apps? The XDK can build for those targets as well as the option to compile with XDK or Cordova (PhoneGap) API's.
The XDK ships with the open source Brackets editor from Adobe. Titanium has a decent editor, but I prefer the XDK solution. Additionally, you have access to some of the extensions available to Brackets. The only drawback is that you can't update the Brackets editor that's integrated with the XDK. However, it's still a step up from Titanium, and PhoneGap doesn't even come with an editor.
The XDK also includes a graphical editor, which is sorely missing in all of the HTML5 mobile platforms. It stands to reason using HTML components would benefit from a WYSIWYG editor. It also supports frameworks such as Bootstrap and jQuery Mobile. These user interface components allow you to quickly build out the interface of your app.
Once your app is created, you need a way to test out its functionality. Intel XDK includes the best emulator for mobile devices I've seen to date. It includes the capability to test on real devices and profile performance without having to install anything.
3. Build a Mobile App with Intel XDK
Step 1: Download and install
Go to the Intel XDK download page and get the latest version of XDK. After downloading the package, install it with the default options.
Step 2: Create a New Project
We're going to build a small picture app. Start the XDK and choose Start a New Project. Some of the options you have are:
Start with a Demo: This option allows you to use one of the many demo projects Intel offers. This is good to help understand how to develop with the XDK.
Start with a Template: This option offers a number of templates for various user interface styles. It also has a blank Cordova template to get you started.
Import an Existing HTML5 Project: With this option, you can import a project made outside the XDK, such as a PhoneGap project coded in your editor of choice. It also lets you import XDK projects.
Use App Starter/Start with App Designer: App Starter can be considered App Designer Lite. Both are graphical interfaces to go along with the Brackets editor. App Starter uses App Framework. App Designer adds options for the Bootstrap, jQuery Mobile, and Topcoat user interface frameworks.
Start with a Blank Project: As the name implies, this option gives us a blank project with a template to get us started. This is the option we will choose for this tutorial.
Give your project a name and click Create. The XDK will create your project as well as a folder structure.
Step 3: Project Structure
Even though we started a blank project, the XDK includes some files to get you started. We are going to edit these files for our project.
init-dev.js
This file is used to detect ready events from the various libraries in use. This file will be used as is. It includes many log statements for debugging purposes and to better understand how the file works. The part we are most concerned with starts at line 106.
The first line creates a new event object. We initialize this object with the value "app.ready". The last line dispatches the event to the DOM.
init-app.js
I've deleted most of this file's contents, except for the part we need. We make sure that the libraries we need have been loaded and that the device is ready before we execute any of our code. Remember the app.ready event from the previous file?
The initEvents function does two things. First, it binds a click event listener to a button using jQuery. Second, it adds an event listener for the XDK intel.xdk.camera.picture.add event.
app.js
This file contains the meat of our app and contains the functions that runs our app. The replacer function uses jQuery to replace the image on the page with the most recent picture taken.
function replacer(pic) {
$("img").replaceWith(pic);
}
The name of the takePic function says it all. It uses the XDK framework to take a picture.
function takePic() {
intel.xdk.camera.takePicture(50,false,"jpg");
}
The onSuccess function fires when a intel.xdk.camera.picture.add event is detected. If a picture was successfully taken, it will replace the current image on the page using the replacer function we saw earlier. If the app was not able to take a picture, it will display an error message.
function onSuccess(evt) {
if (evt.success == true) {
var image = document.createElement('img');
image.src=intel.xdk.camera.getPictureURL(evt.filename);
image.setAttribute ("style","width:100%;height:200px;");
image.id=evt.filename;
replacer(image);
}
else {
if (evt.message != undefined) {
alert(evt.message);
}
else
{
alert("error capturing picture");
}
}
}
index.html
This file contains the main page of our app. It's a simple HTML file in which we pull in jQuery and jQuery Mobile.
We also import a few stylesheets to style the app. The custom stylesheet, app.css, has very little in the way of styling. That is because I use the jQuery Mobile theme roller to style the app.
The page itself is a standard jQuery Mobile page with a header, content, and footer section. Notice the image inside the div#info tag. This is the image that's replaced by the picture taken by the camera.
We also import a number of key scripts that make the app tick, such as Cordova and Intel XDK, and app.js.
<script src="intelxdk.js"></script> <!-- phantom library, needed for XDK api calls --><script src="cordova.js"></script> <!-- phantom library, needed for Cordova api calls --><script src="xhr.js"></script> <!-- phantom library, needed for XDK CORS --><script src="js/app.js"></script><script src="js/init-dev.js"></script><script src="js/init-app.js"></script>
4. Enabling Plugins
We're going to be using the Intel XDK API to take pictures. To make this work, we have to enable a few plugins. Open the Projects tab and, in the middle, you'll see CORDOVA 3.X HYBRID MOBILE APP SETTINGS. Click the plus button next to plugins and permissions. On the right, under Intel XDK Plugins, check Camera.
5. Using the Emulator
Click the Emulate tab and try out the functionality of the app. When you click on the Take Selfi button, it should bring up the picture window. After taking a picture, the picture should replace the placeholder image.
6. Testing the App
Download and install the Intel App Preview app from Google Play or Apple's App Store. Go to the Test tabs and copy the weinre script tag if you want to perform debugging with App Preview. Click on the PUSH FILES button to upload your app to Intel's servers. Log on to App Preview with your credentials from the Intel XDK and choose the app you uploaded.
7. Building the App
Now that we have tested the app, the last task is to build it for distribution. Click on the Build tab to display your options. As you can see, we have a wide range of targets to build for.
Since we used the Camera API, which is Legacy, we will choose the Legacy Hybrid app. This brings us to the build page as shown below.
Clicking on Details shows you options for in-app billing, streaming audio, etc.
After choosing the options for your app, click on the build button. After a few moments, the file is built and you will get a dialog that lets you download your app.
Conclusion
I hope you agree that it's easy to create an app with Intel XDK. Whether you're a veteran, full stack web developer or just starting to get into development, Intel XDK has an entry point for you. It's easy to pick up and I encourage you to give the Intel XDK a try.
Xcode 6 brings a number of significant improvements. One of the more notable advances is view debugging. Often times, an app's user interface will not behave the way it's expected to. Views may not be shown or, if they do show, they may display incorrectly. This tutorial outlines how to use Xcode's new view debugging features to easily identify and fix issues in an app's user interface.
1. Demo Project
To get us started, download the sample project from GitHub and open ViewDebugging.xcodeproj. The project contains a simple tabbed application with a few view controllers, an application delegate, and a storyboard. This app was designed for the iPhone, but it will display fine on any device since it uses adaptive layout, introduced in iOS 8.
The purpose of the app is to make a simple to-do list. It includes a summary screen to view other information, such as the number of items in the to-do list, the user's avatar, and their Twitter handle. Run the app in the iOS Simulator by clickingbuild and runin the top left.
Right away, you may notice an issue with the user interface. The table view doesn't seem to be displaying any data. Open up FirstViewController.swift and locate the following line of code.
var mockNotesDataSource: [String] = ["Do some laundry", "Finish homework", "Walk the dog", "Learn about view debugging"]
{
didSet
{
self.tableView.reloadData()
}
}
The mockNotesDataSource variable serves as the table view's data source. We use Swift's property observer capabilities. As a result, the table view is automatically reloaded whenever the data source changes. By looking at the above code snippet, four items should be displayed in the to-do list. It appears that something else is wrong.
2. Enable View Debugging
The issue seems to be related to the user interface. While the app is running, press the Debug View Hierarchy button at the bottom. Alternatively, navigating to Debug > View Debugging > Capture View Hierarchy also enables view debugging.
When view debugging is enabled, Xcode takes a snapshot of the application's view hierarchy and presents a three-dimensional, exploded view of the user interface. It shows the application's view hierarchy, the position, order, and size of each view as well as how the views are interacting with one another.
Looking at the three-dimensional render, we can see that the to-do list is loading fine, but the table view cells are too wide.
Stop debugging the application and navigate to Main.Storyboard to fix the issue. Click on the table view and select Editor > Resolve Auto Layout Issues > Reset to Suggested Constraints.
Build and run the application once more to confirm that the user interface is displaying correctly. Click the Debug View Hierarchy button to take a closer look at some of the other features of view debugging.
3. View Debugging Features
Click and drag anywhere inside the three-dimensional render to tilt and pan the user interface. Tilt it to the left or right to select the table view.
Once a view is selected, Xcode highlights the view and populates the Object and Size inspectors on the right. To confirm that you've selected the table view, look at the jump bar at the top and verify that UITableView is the last item on the right.
The Object and Size inspectors include a wealth of helpful information. In the past, developers had to rely on log statements or breakpoints to inspect a view's configuration.
Open up the Size inspector on the right and, in the Auto Layout section, notice that the correct constraints are now applied to the view. In the Object inspector, you can inspect the attributes of the selected view.
Right above the debugging area in Xcode, there are nine buttons and sliders used for view debugging.
This is what each of these controls does, from left to right:
adjust spacing between views: adjusts how much space is shown between views
show clipped content: shows clipped content on the view currently displayed
show constraints: shows only the constraints of the selected view
reset the viewing area: sets the 3D render perspective back to its default
adjust the view mode: display the 3D render with just the content, wireframes, or a combination of the two
zoom out: zooms the 3D render out
actual size: resets the 3D render back its default
zoom in: zooms the 3D render in
adjust the range of visible views: hides views, starting from the back of the 3D render, sliding the slider from right to left has the opposite effect
Take a few minutes to play with these controls to properly understand what each of them does.
4. Sorting Through View Layers
Build and run the application again and tap the More tab at the bottom of the app's user interface. At first glance, the user interface looks okay, but it isn't behaving exactly how it should. A blur effect on top of the picture isn't displaying. Debug the view hierarchy to better identify the problem.
Start by panning to the left or right to view everything at an angle. Next, drag the view spacing slider towards the right.
With the user interface pulled apart, it becomes clear that there is another view hidden beneath the image. Select it to confirm it's the missing visual effect view.
Open Main.storyboard and navigate to Second View Controller Scene. In the document outline pane on the left, expand the Second View Controller's View object to see how its subviews are ordered.
Xcode layers views in ascending order within the document outline. In other words, the ones at the top of the list are the foundation of the view hierarchy.
Fixing our issue is simple. Blur Effect View will be beneath Sky Image at runtime, because it's the first view in the view hierarchy. Click and drag the Blur Effect View underneath Sky Image in the document outline. The result should now look like the screenshot below.
If you run the app again, the blur effect should be visible. The app's user interface now looks as it was designed. Let's look at some of the iOS Simulator's debugging features to see what else can be improved.
5. iOS Simulator Debugging Features
Build and run the app in the iOS Simulator. With the iOS Simulator selected, select Color Blended Layers from the Debug menu.
The app's user interface is overlaid with a mix of green and red. These are cues to show which layers have blending enabled and which ones are opaque. Blending layers is computationally intensive. It is therefore recommended to use opaque layers whenever possible.
Apple notes in their documentation to try and use opaque layers when dealing with table views. One of the main causes of poor performance when scrolling is due to blended content. When the content's background is opaque, scrolling will generally become smoother.
For this app, if a user has hundreds of items in their to do list they may experience choppy or inconsistent scrolling performance. The table view cells are currently using blended layers. Since the view controller's view background is already white, the end user won't see any difference if the table view cells are blended or opaque with a white background.
Open Main.storyboard and select the table view cell prototype in the To Do list Scene. In the Attributes Inspector. Scroll down to the Drawing section and check Opaque.
Build and run the app with coloring blended layers enabled. Since the table view cells are now opaque, they are overlaid with a green color, indicating that they're opaque.
Aside from flagging layers, there are a handful of other features that can aid in debugging in the iOS Simulator. Here are some of the ones I find most useful:
Toggle Slow Animations in Frontmost App: This feature causes all animations in the app to run slower, which is helpful when debugging complex animations that aren't behaving as expected. You can also enable this options by pressing Command-T.
Color Copied Images: This options adds a blue overlay to each copied image using Core Animation.
Color Misaligned Images: This features colors images with a magenta overlay if the bounds are not perfectly aligned with the destination pixels. A yellow overlay is added if used if the image is drawn using a scale factor.
Color Off Screen Rendered: This option add a yellow overlay to content that is rendered off screen.
Something overlooked by many developers is the impact of the status bar on your app if a call is in progress. You can easily test this by toggling the in-call status bar. You do this by selecting Toggle In-Call Status Bar from the Hardware menu in the iOS Simulator.
To see how your app responds to such an event, press Command-T, to enable slow animations, and press Command-Y to display the in-call status bar. If your app uses a navigation bar, then the operating system takes care of this for you.
Aside from coloring views, keep in mind that the iOS Simulator can also debug Core Location issues. You can simulate a device at a specific latitude and longitude and there are even a number of sample locations included to test with. If your app is using iCloud to manage data, then you can also manually trigger a synchronization event.
Conclusion
While the demo app included is very simple, using the techniques mentioned in this article can shave hours off of future projects. View debugging can help you correct many problems that come up in the user interface.
Outside of Xcode and interface builder, using the iOS Simulator's debugging features can help boost performance and identify bottlenecks. Apple's own human interface guidelines stress the importance of responsive apps that are easy to use and navigate. With the improvements made to interface builder, it's never been easier to do just that.
2014-11-14T17:10:31.000Z2014-11-14T17:10:31.000ZJordan Morgan
Xcode 6 brings a number of significant improvements. One of the more notable advances is view debugging. Often times, an app's user interface will not behave the way it's expected to. Views may not be shown or, if they do show, they may display incorrectly. This tutorial outlines how to use Xcode's new view debugging features to easily identify and fix issues in an app's user interface.
1. Demo Project
To get us started, download the sample project from GitHub and open ViewDebugging.xcodeproj. The project contains a simple tabbed application with a few view controllers, an application delegate, and a storyboard. This app was designed for the iPhone, but it will display fine on any device since it uses adaptive layout, introduced in iOS 8.
The purpose of the app is to make a simple to-do list. It includes a summary screen to view other information, such as the number of items in the to-do list, the user's avatar, and their Twitter handle. Run the app in the iOS Simulator by clickingbuild and runin the top left.
Right away, you may notice an issue with the user interface. The table view doesn't seem to be displaying any data. Open up FirstViewController.swift and locate the following line of code.
var mockNotesDataSource: [String] = ["Do some laundry", "Finish homework", "Walk the dog", "Learn about view debugging"]
{
didSet
{
self.tableView.reloadData()
}
}
The mockNotesDataSource variable serves as the table view's data source. We use Swift's property observer capabilities. As a result, the table view is automatically reloaded whenever the data source changes. By looking at the above code snippet, four items should be displayed in the to-do list. It appears that something else is wrong.
2. Enable View Debugging
The issue seems to be related to the user interface. While the app is running, press the Debug View Hierarchy button at the bottom. Alternatively, navigating to Debug > View Debugging > Capture View Hierarchy also enables view debugging.
When view debugging is enabled, Xcode takes a snapshot of the application's view hierarchy and presents a three-dimensional, exploded view of the user interface. It shows the application's view hierarchy, the position, order, and size of each view as well as how the views are interacting with one another.
Looking at the three-dimensional render, we can see that the to-do list is loading fine, but the table view cells are too wide.
Stop debugging the application and navigate to Main.Storyboard to fix the issue. Click on the table view and select Editor > Resolve Auto Layout Issues > Reset to Suggested Constraints.
Build and run the application once more to confirm that the user interface is displaying correctly. Click the Debug View Hierarchy button to take a closer look at some of the other features of view debugging.
3. View Debugging Features
Click and drag anywhere inside the three-dimensional render to tilt and pan the user interface. Tilt it to the left or right to select the table view.
Once a view is selected, Xcode highlights the view and populates the Object and Size inspectors on the right. To confirm that you've selected the table view, look at the jump bar at the top and verify that UITableView is the last item on the right.
The Object and Size inspectors include a wealth of helpful information. In the past, developers had to rely on log statements or breakpoints to inspect a view's configuration.
Open up the Size inspector on the right and, in the Auto Layout section, notice that the correct constraints are now applied to the view. In the Object inspector, you can inspect the attributes of the selected view.
Right above the debugging area in Xcode, there are nine buttons and sliders used for view debugging.
This is what each of these controls does, from left to right:
adjust spacing between views: adjusts how much space is shown between views
show clipped content: shows clipped content on the view currently displayed
show constraints: shows only the constraints of the selected view
reset the viewing area: sets the 3D render perspective back to its default
adjust the view mode: display the 3D render with just the content, wireframes, or a combination of the two
zoom out: zooms the 3D render out
actual size: resets the 3D render back its default
zoom in: zooms the 3D render in
adjust the range of visible views: hides views, starting from the back of the 3D render, sliding the slider from right to left has the opposite effect
Take a few minutes to play with these controls to properly understand what each of them does.
4. Sorting Through View Layers
Build and run the application again and tap the More tab at the bottom of the app's user interface. At first glance, the user interface looks okay, but it isn't behaving exactly how it should. A blur effect on top of the picture isn't displaying. Debug the view hierarchy to better identify the problem.
Start by panning to the left or right to view everything at an angle. Next, drag the view spacing slider towards the right.
With the user interface pulled apart, it becomes clear that there is another view hidden beneath the image. Select it to confirm it's the missing visual effect view.
Open Main.storyboard and navigate to Second View Controller Scene. In the document outline pane on the left, expand the Second View Controller's View object to see how its subviews are ordered.
Xcode layers views in ascending order within the document outline. In other words, the ones at the top of the list are the foundation of the view hierarchy.
Fixing our issue is simple. Blur Effect View will be beneath Sky Image at runtime, because it's the first view in the view hierarchy. Click and drag the Blur Effect View underneath Sky Image in the document outline. The result should now look like the screenshot below.
If you run the app again, the blur effect should be visible. The app's user interface now looks as it was designed. Let's look at some of the iOS Simulator's debugging features to see what else can be improved.
5. iOS Simulator Debugging Features
Build and run the app in the iOS Simulator. With the iOS Simulator selected, select Color Blended Layers from the Debug menu.
The app's user interface is overlaid with a mix of green and red. These are cues to show which layers have blending enabled and which ones are opaque. Blending layers is computationally intensive. It is therefore recommended to use opaque layers whenever possible.
Apple notes in their documentation to try and use opaque layers when dealing with table views. One of the main causes of poor performance when scrolling is due to blended content. When the content's background is opaque, scrolling will generally become smoother.
For this app, if a user has hundreds of items in their to do list they may experience choppy or inconsistent scrolling performance. The table view cells are currently using blended layers. Since the view controller's view background is already white, the end user won't see any difference if the table view cells are blended or opaque with a white background.
Open Main.storyboard and select the table view cell prototype in the To Do list Scene. In the Attributes Inspector. Scroll down to the Drawing section and check Opaque.
Build and run the app with coloring blended layers enabled. Since the table view cells are now opaque, they are overlaid with a green color, indicating that they're opaque.
Aside from flagging layers, there are a handful of other features that can aid in debugging in the iOS Simulator. Here are some of the ones I find most useful:
Toggle Slow Animations in Frontmost App: This feature causes all animations in the app to run slower, which is helpful when debugging complex animations that aren't behaving as expected. You can also enable this options by pressing Command-T.
Color Copied Images: This options adds a blue overlay to each copied image using Core Animation.
Color Misaligned Images: This features colors images with a magenta overlay if the bounds are not perfectly aligned with the destination pixels. A yellow overlay is added if used if the image is drawn using a scale factor.
Color Off Screen Rendered: This option add a yellow overlay to content that is rendered off screen.
Something overlooked by many developers is the impact of the status bar on your app if a call is in progress. You can easily test this by toggling the in-call status bar. You do this by selecting Toggle In-Call Status Bar from the Hardware menu in the iOS Simulator.
To see how your app responds to such an event, press Command-T, to enable slow animations, and press Command-Y to display the in-call status bar. If your app uses a navigation bar, then the operating system takes care of this for you.
Aside from coloring views, keep in mind that the iOS Simulator can also debug Core Location issues. You can simulate a device at a specific latitude and longitude and there are even a number of sample locations included to test with. If your app is using iCloud to manage data, then you can also manually trigger a synchronization event.
Conclusion
While the demo app included is very simple, using the techniques mentioned in this article can shave hours off of future projects. View debugging can help you correct many problems that come up in the user interface.
Outside of Xcode and interface builder, using the iOS Simulator's debugging features can help boost performance and identify bottlenecks. Apple's own human interface guidelines stress the importance of responsive apps that are easy to use and navigate. With the improvements made to interface builder, it's never been easier to do just that.
2014-11-14T17:10:31.000Z2014-11-14T17:10:31.000ZJordan Morgan
In-app purchases are an excellent way to increase revenue for your Windows Phone app. In this tutorial, I'll be showing you how to implement in-app purchases in a Windows Phone 8 Silverlight application.
To test your application, you'll need to create a product to test with. This means that you'll need an active Windows Phone developer account if you want to follow along.
Introduction
Windows Phone 8 provides a convenient purchase
experience, reliable payouts, geo-distributed services, and product management
tools to achieve meaningful commerce in your app. You can choose between
in-app purchases and other payment options (for example PayPal), but in-app
purchases give you more flexibility as they provide:
management of products using the Windows Phone developer portal
geo-distributed services and payouts in more than 190 countries
consistent purchase experience for users across all apps on the phone and proof of authenticity through secure receipts
1. Get an App ID
In the Windows Phone developer portal's dashboard,
browse to the Details tab of your app
and make a note of the App ID.
Also grab your Publisher GUID from
the developer portal. You're going to need these details later to update the
application manifest file.
If you are developing a new app, then go to the dashboard and
click on Submit App to start the
submission process and reserve a name for your app. Save these details and you
can skip submitting the XAP file for now. Just note the App ID from the App
properties section.
2. Add a
Product to Your App
Under application details, there is
a Products tab where you can add and
manage in-app products for your app. For the purpose of this demonstration, we have created a product named Premium App.
In the Windows Phone developer portal, you need to add your in-app product's properties and description. You can optionally set custom pricing in different markets for your product.
You need to fill in the properties of your in-app product as shown in the following screenshot. Remember the Product Identifier as you will need it for listing in-app products in your app.
Here are a few things worth remembering while adding an in-app product:
You can have multiple products for
an app. Each product can be consumable or durable. Durable products can only be bought once.
Universal apps can share in-app
products, letting users buy once and use anywhere. Your in-app product
category can differ, but the product name and identity should match for this to
work.
You can define custom pricing for your products in different
countries.
The description section requires you to add a product title, description, and image for the in-app product as shown in the screenshot below.
Note that it may take
one or two hours to process your submission before the product is published.
3. Update Application Manifest
It's time to update the application manifest by adding the App ID
and Publisher GUID, which you copied from the Windows Phone developer portal. Using the Solution
Explorer of your project, browse to Propertiesand locate WMAppManifest.xml.
Visual Studio assigns a random Product
ID and Publisher ID when you create a new project, which you need to change
by going to the Packaging tab. If
you are targeting only Windows Phone 8.1, then you need to update Package.appmanifest in addition to WMAppManifest.xml.
4. List In-App Products in Your App
The app uses the in-app purchase
API available in the Windows Phone SDK to fetch products and list them. The
user now has an option to purchase these products from within the app.
Depending on the application you are building, you may want to list specific
products in different places, but for the purpose of the demonstration let's
display all the products associated with the app and handle the purchase flow.
We need an ItemsControl to hold the products. The following code snippet
shows how you can define the data template of your ItemsControl and bind the products
to it. Notice that the buybutton is
visible only if the user hasn't purchased the product. Feel free to play with
the data template to make it more attractive.
The public class ProductItemstores all the information
related to a particular product. There is an ObservableCollection of type ProductItem
named picItems, which stores all the
products.
public class ProductItem
{
public string imgLink { get; set; }
public string Status { get; set; }
public string Name { get; set; }
public string key { get; set; }
public System.Windows.Visibility BuyNowButtonVisible { get; set; }
}
The next step is to add a function RenderStoreItemsin the code behind to list all the products for
the application. This function makes an
asynchronous call to LoadListingInformationAsyncto render the products for the current application. The function then
iterates through every product, checking its license information and adding it
to the list. We bind the name, purchase status, and price to the list box, and
display it to the user.
ListingInformation li = await Windows.ApplicationModel.Store.CurrentApp.LoadListingInformationAsync();
foreach (string key in li.ProductListings.Keys)
{
ProductListing pListing = li.ProductListings[key];
System.Diagnostics.Debug.WriteLine(key);
string status = Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.ProductLicenses[key].IsActive ? "Purchased" : pListing.FormattedPrice;
string imageLink = string.Empty;
//picItems is an observable collection with global scope to MainPage.xaml
picItems.Add(
new ProductItem
{
imgLink = key.Equals("PremiumVersion") ? "Images/block-ads.png" : "Images/block-ads.png",
Name = pListing.Name,
Status = status,
key = key,
BuyNowButtonVisible = Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.ProductLicenses[key].IsActive ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible
}
);
}
pics.ItemsSource = picItems;
Note that you need to enter a correct App ID, Publisher ID, and Product ID before you can deploy the sample project with this tutorial.
Next, you need to add the click
event handler for the buy button. The function ButtonBuyNow_Clickedinitiates the purchase. The user is presented with a purchase experience
that's part of the Windows Phone 8 platform. When the purchase is complete, you
can enable a locked feature or let the user download additional content. This is entirely up to you.
Button btn = sender as Button;
string key = btn.Tag.ToString();
if (!Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.ProductLicenses[key].IsActive)
{
ListingInformation li = await Windows.ApplicationModel.Store.CurrentApp.LoadListingInformationAsync();
string pID = li.ProductListings[key].ProductId;
string receipt = await Windows.ApplicationModel.Store.CurrentApp.RequestProductPurchaseAsync(pID, false);
}
5. After the Purchase
You can use the in-app purchase
API to enumerate the licenses the user has for the products in your app
when the app is launched or resumed, or after a purchase. This lets you determine whether the user already owns the product he or she licensed, or whether its fulfillment
is still pending. You can also retrieve receipts for the products purchased
by the user to verify if the transaction took place using the GetProductReceiptAsync function.
Check whether LicenseInformation.IsActivereturns true for a product before
fulfilling a purchase. However, the call to this function is resource intensive so it is advisable not to call it at app launch or resume.
When you think a
product purchase has completed, first verify that a license exists for that
product ID and then check to see whether IsActive is true on that license. If
the license is active then the purchase should be fulfilled immediately.
A possible scenario where in-app
purchases can be useful is when you want to distribute your app for free with
ads and allow the user to remove them through an in-app
purchase. Here's an article on implementing a "block ads" feature using the in-app purchase API. The same technique can be used to implement a trial. The advantage is that your app is listed in the freecategory in the store and will as a result get you more downloads.
In the case of consumable products, it's the responsibility of
the app to track consumption. The CurrentApp.LicenseInformationonly provides information about the license, not the state.
6. Testing In-App Purchases
If you test your app in the emulator, in-app purchases are free and no financial transactions take place. Each
time you reinstall the app in the emulator, previously stored license
information is cleared.
There are three main techniques
for testing in-app purchases:
create a Dev Center beta app and add beta in-app products
add the mock in-app purchase mock library to your solution
set up an in-app purchase mock service using Microsoft Internet Information Services (IIS)
Conclusion
In this tutorial, you have learned how
to list in-app products and enable an app feature when the user purchases a
product. There are lots of customizations possible with in-app purchases and they can be used in a variety of scenarios.
In-app purchases are an excellent way to increase revenue for your Windows Phone app. In this tutorial, I'll be showing you how to implement in-app purchases in a Windows Phone 8 Silverlight application.
To test your application, you'll need to create a product to test with. This means that you'll need an active Windows Phone developer account if you want to follow along.
Introduction
Windows Phone 8 provides a convenient purchase
experience, reliable payouts, geo-distributed services, and product management
tools to achieve meaningful commerce in your app. You can choose between
in-app purchases and other payment options (for example PayPal), but in-app
purchases give you more flexibility as they provide:
management of products using the Windows Phone developer portal
geo-distributed services and payouts in more than 190 countries
consistent purchase experience for users across all apps on the phone and proof of authenticity through secure receipts
1. Get an App ID
In the Windows Phone developer portal's dashboard,
browse to the Details tab of your app
and make a note of the App ID.
Also grab your Publisher GUID from
the developer portal. You're going to need these details later to update the
application manifest file.
If you are developing a new app, then go to the dashboard and
click on Submit App to start the
submission process and reserve a name for your app. Save these details and you
can skip submitting the XAP file for now. Just note the App ID from the App
properties section.
2. Add a
Product to Your App
Under application details, there is
a Products tab where you can add and
manage in-app products for your app. For the purpose of this demonstration, we have created a product named Premium App.
In the Windows Phone developer portal, you need to add your in-app product's properties and description. You can optionally set custom pricing in different markets for your product.
You need to fill in the properties of your in-app product as shown in the following screenshot. Remember the Product Identifier as you will need it for listing in-app products in your app.
Here are a few things worth remembering while adding an in-app product:
You can have multiple products for
an app. Each product can be consumable or durable. Durable products can only be bought once.
Universal apps can share in-app
products, letting users buy once and use anywhere. Your in-app product
category can differ, but the product name and identity should match for this to
work.
You can define custom pricing for your products in different
countries.
The description section requires you to add a product title, description, and image for the in-app product as shown in the screenshot below.
Note that it may take
one or two hours to process your submission before the product is published.
3. Update Application Manifest
It's time to update the application manifest by adding the App ID
and Publisher GUID, which you copied from the Windows Phone developer portal. Using the Solution
Explorer of your project, browse to Propertiesand locate WMAppManifest.xml.
Visual Studio assigns a random Product
ID and Publisher ID when you create a new project, which you need to change
by going to the Packaging tab. If
you are targeting only Windows Phone 8.1, then you need to update Package.appmanifest in addition to WMAppManifest.xml.
4. List In-App Products in Your App
The app uses the in-app purchase
API available in the Windows Phone SDK to fetch products and list them. The
user now has an option to purchase these products from within the app.
Depending on the application you are building, you may want to list specific
products in different places, but for the purpose of the demonstration let's
display all the products associated with the app and handle the purchase flow.
We need an ItemsControl to hold the products. The following code snippet
shows how you can define the data template of your ItemsControl and bind the products
to it. Notice that the buybutton is
visible only if the user hasn't purchased the product. Feel free to play with
the data template to make it more attractive.
The public class ProductItemstores all the information
related to a particular product. There is an ObservableCollection of type ProductItem
named picItems, which stores all the
products.
public class ProductItem
{
public string imgLink { get; set; }
public string Status { get; set; }
public string Name { get; set; }
public string key { get; set; }
public System.Windows.Visibility BuyNowButtonVisible { get; set; }
}
The next step is to add a function RenderStoreItemsin the code behind to list all the products for
the application. This function makes an
asynchronous call to LoadListingInformationAsyncto render the products for the current application. The function then
iterates through every product, checking its license information and adding it
to the list. We bind the name, purchase status, and price to the list box, and
display it to the user.
ListingInformation li = await Windows.ApplicationModel.Store.CurrentApp.LoadListingInformationAsync();
foreach (string key in li.ProductListings.Keys)
{
ProductListing pListing = li.ProductListings[key];
System.Diagnostics.Debug.WriteLine(key);
string status = Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.ProductLicenses[key].IsActive ? "Purchased" : pListing.FormattedPrice;
string imageLink = string.Empty;
//picItems is an observable collection with global scope to MainPage.xaml
picItems.Add(
new ProductItem
{
imgLink = key.Equals("PremiumVersion") ? "Images/block-ads.png" : "Images/block-ads.png",
Name = pListing.Name,
Status = status,
key = key,
BuyNowButtonVisible = Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.ProductLicenses[key].IsActive ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible
}
);
}
pics.ItemsSource = picItems;
Note that you need to enter a correct App ID, Publisher ID, and Product ID before you can deploy the sample project with this tutorial.
Next, you need to add the click
event handler for the buy button. The function ButtonBuyNow_Clickedinitiates the purchase. The user is presented with a purchase experience
that's part of the Windows Phone 8 platform. When the purchase is complete, you
can enable a locked feature or let the user download additional content. This is entirely up to you.
Button btn = sender as Button;
string key = btn.Tag.ToString();
if (!Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.ProductLicenses[key].IsActive)
{
ListingInformation li = await Windows.ApplicationModel.Store.CurrentApp.LoadListingInformationAsync();
string pID = li.ProductListings[key].ProductId;
string receipt = await Windows.ApplicationModel.Store.CurrentApp.RequestProductPurchaseAsync(pID, false);
}
5. After the Purchase
You can use the in-app purchase
API to enumerate the licenses the user has for the products in your app
when the app is launched or resumed, or after a purchase. This lets you determine whether the user already owns the product he or she licensed, or whether its fulfillment
is still pending. You can also retrieve receipts for the products purchased
by the user to verify if the transaction took place using the GetProductReceiptAsync function.
Check whether LicenseInformation.IsActivereturns true for a product before
fulfilling a purchase. However, the call to this function is resource intensive so it is advisable not to call it at app launch or resume.
When you think a
product purchase has completed, first verify that a license exists for that
product ID and then check to see whether IsActive is true on that license. If
the license is active then the purchase should be fulfilled immediately.
A possible scenario where in-app
purchases can be useful is when you want to distribute your app for free with
ads and allow the user to remove them through an in-app
purchase. Here's an article on implementing a "block ads" feature using the in-app purchase API. The same technique can be used to implement a trial. The advantage is that your app is listed in the freecategory in the store and will as a result get you more downloads.
In the case of consumable products, it's the responsibility of
the app to track consumption. The CurrentApp.LicenseInformationonly provides information about the license, not the state.
6. Testing In-App Purchases
If you test your app in the emulator, in-app purchases are free and no financial transactions take place. Each
time you reinstall the app in the emulator, previously stored license
information is cleared.
There are three main techniques
for testing in-app purchases:
create a Dev Center beta app and add beta in-app products
add the mock in-app purchase mock library to your solution
set up an in-app purchase mock service using Microsoft Internet Information Services (IIS)
Conclusion
In this tutorial, you have learned how
to list in-app products and enable an app feature when the user purchases a
product. There are lots of customizations possible with in-app purchases and they can be used in a variety of scenarios.