Have a great idea for an iOS game but are turned off by the
hours of tedious work involved in bringing your concept to life? Well, that’s
what templates are for. Why waste time reinventing the wheel when CodeCanyon is
filled with a brilliant range of iOS
game templates that will help you cut through the drudgery and focus on the
best parts of creating your own game?
To get you started, we’ve scoured through the almost 300 iOS
game templates we have available and found the ten best and most current we have
available today.
One of the top
sellers at CodeCanyon, FIVES
challenges players to create as many five-letter words as they can before the
game’s timer runs out. Every time players match a word the timer decreases its
time a little, to give them a bit of a reward. Players also have the option of
sharing their best scores on Facebook and Twitter.
The FIVES template uses Xcode 8.x and Swift. It
supports internationalization to multiple languages and comes with a comprehensive PDF User Guide to help
you customise the game to suit your interests and tastes.
Users have commented on the template's “excellent code”, “good documentation” and “great support follow up”.
A great app for
priming the memory and deepening concentration, the aim of Brain Teaser is
for players to remember and draw connections between faces, shapes or words displayed.
The template is designed to be edited with Xcode. It's easy to reskin and supports AdMob out of the box.
Designed to increase
concentration and enhance problem-solving skills and information-processing
speeds, iMath
is a fun app that challenges children and adults alike to complete basic
addition, subtraction, multiplication and division equations under time
constraints.
The app is easy to reskin and supports monetisation with Chartboost and AdMob ads. It also includes Yahoo Flurry Analytics so that you can track every aspect of your app's performance. This template is written in Objective-C.
Sudoku
is a popular puzzle game that initially displays a partially filled grid. The
aim of the game is to fill each square with a number from 1 to 9. Each number
can only appear once in the same column, row or 3 x 3 box. This app comes in five levels—from easy to expert—and once begun a level can be saved to continue
playing later.
Written in
Objective-C, the template supports AdMob and is easy to reskin.
Following on the huge popularity of Pokemon Go, the goal of Catch
The Monsters is for the player to find monsters in their area or an area they're visiting. When the
app locates a monster, the player needs to get within at least 50 meters of them
in order to catch them, earn points and move up the Top 10 Leaderboard. Players
can also share their stats on social media, by mail or SMS.
The Catch The
Monsters template comes with an admin interface, using the Parse SDK on back4app, that allows an administrator to name the monsters and
place them in anywhere in the world. The app comes with a
PDF User Guide and PSD icons included.
It's one of the best
rated apps in its category on CodeCanyon, and users comment that Catch The Monsters
has “easy code, great design, excellent customer support”.
The 2048 Rounded
game is a spin-off of the classic 2048 number puzzle game. The aim of the game
is to get one tile to the number 2048 as quickly as possible by swiping the
numbered tiles up, down, left or right so that matching tiles merge and are
added together.
The template is written in Swift and can be edited with Xcode. AdMob is supported for easy monetization.
Tap the screen to
fly the Flappy
Clumsy Dragon, avoid obstacles, and fight with enemy birds. The best score is displayed on the leaderboard, and players can share results on Facebook and Twitter.
Graphics aren’t
included with this template, so you'll need to reskin it with your own assets. The developer has created a reskinning tutorial to make it easy for you to create your own version of the game.
The template is made with the Lua language and the Corona SDK, so it will be easy to create an Android version too, if you want. The template also allows admins to include a popup window to encourage ratings. If you want to see how it works, you can try the demo right now on the Apple App Store.
Made with Cocos2dx and Objective-C, the aim of the Rush Hero Game
is to move the hero to the left or right out of the path of falling rocks which will crush him. The template includes some fun graphics and great sound effects that are triggered when the hero gets hit.
The game comes with layered PSD files for all the assets, which makes it easy to reskin.
Some of its outstanding features are the best score and game rating social features, as well as support for monetization through ad networks and AdMob banners. It is also Game Centre
integrated and comes with detailed instructions for customisation.
With the Dragon
Jump template, the player is a knight defending the kingdom from dragons
flying overhead. The player can jump on the dragons to kill them or can kill them with a spear. Players may share their scores on various social media.
This template is integrated with Game Centre, so users can share their highscores, as well as with Google Analytics, ad networks, and AdMob banner ads for easy tracking and monetization. The template
also comes with
complete documentation to guide users through customisation.
One of the newest iOS games in CodeCanyon, this
template for the classic Tic Tac Toe game
allows players to play against the phone or against another player on the same phone.
Coded with Swift 3 and the latest version of Xcode, the game interface is fully customizable through Storyboard. Detailed instructions for reskinning and customising are included.
The app will auto resize for various screen sizes and
supports AdMob. Users have found that “the app functions really well.”
Conclusion
This is just a small selection of hundreds of iOS
game templates we have available at CodeCanyon, so if none of these featured templates quite fits
your needs, there are plenty of other great options to choose from.
And if you
want to improve your skills building iOS games, head on over to the site
and check out some of the ever so useful mobile development tutorials and courses we have on offer.
Have a great idea for an iOS game but are turned off by the
hours of tedious work involved in bringing your concept to life? Well, that’s
what templates are for. Why waste time reinventing the wheel when CodeCanyon is
filled with a brilliant range of iOS
game templates that will help you cut through the drudgery and focus on the
best parts of creating your own game?
To get you started, we’ve scoured through the almost 300 iOS
game templates we have available and found the ten best and most current we have
available today.
One of the top
sellers at CodeCanyon, FIVES
challenges players to create as many five-letter words as they can before the
game’s timer runs out. Every time players match a word the timer decreases its
time a little, to give them a bit of a reward. Players also have the option of
sharing their best scores on Facebook and Twitter.
The FIVES template uses Xcode 8.x and Swift. It
supports internationalization to multiple languages and comes with a comprehensive PDF User Guide to help
you customise the game to suit your interests and tastes.
Users have commented on the template's “excellent code”, “good documentation” and “great support follow up”.
A great app for
priming the memory and deepening concentration, the aim of Brain Teaser is
for players to remember and draw connections between faces, shapes or words displayed.
The template is designed to be edited with Xcode. It's easy to reskin and supports AdMob out of the box.
Designed to increase
concentration and enhance problem-solving skills and information-processing
speeds, iMath
is a fun app that challenges children and adults alike to complete basic
addition, subtraction, multiplication and division equations under time
constraints.
The app is easy to reskin and supports monetisation with Chartboost and AdMob ads. It also includes Yahoo Flurry Analytics so that you can track every aspect of your app's performance. This template is written in Objective-C.
Sudoku
is a popular puzzle game that initially displays a partially filled grid. The
aim of the game is to fill each square with a number from 1 to 9. Each number
can only appear once in the same column, row or 3 x 3 box. This app comes in five levels—from easy to expert—and once begun a level can be saved to continue
playing later.
Written in
Objective-C, the template supports AdMob and is easy to reskin.
Following on the huge popularity of Pokemon Go, the goal of Catch
The Monsters is for the player to find monsters in their area or an area they're visiting. When the
app locates a monster, the player needs to get within at least 50 meters of them
in order to catch them, earn points and move up the Top 10 Leaderboard. Players
can also share their stats on social media, by mail or SMS.
The Catch The
Monsters template comes with an admin interface, using the Parse SDK on back4app, that allows an administrator to name the monsters and
place them in anywhere in the world. The app comes with a
PDF User Guide and PSD icons included.
It's one of the best
rated apps in its category on CodeCanyon, and users comment that Catch The Monsters
has “easy code, great design, excellent customer support”.
The 2048 Rounded
game is a spin-off of the classic 2048 number puzzle game. The aim of the game
is to get one tile to the number 2048 as quickly as possible by swiping the
numbered tiles up, down, left or right so that matching tiles merge and are
added together.
The template is written in Swift and can be edited with Xcode. AdMob is supported for easy monetization.
Tap the screen to
fly the Flappy
Clumsy Dragon, avoid obstacles, and fight with enemy birds. The best score is displayed on the leaderboard, and players can share results on Facebook and Twitter.
Graphics aren’t
included with this template, so you'll need to reskin it with your own assets. The developer has created a reskinning tutorial to make it easy for you to create your own version of the game.
The template is made with the Lua language and the Corona SDK, so it will be easy to create an Android version too, if you want. The template also allows admins to include a popup window to encourage ratings. If you want to see how it works, you can try the demo right now on the Apple App Store.
Made with Cocos2dx and Objective-C, the aim of the Rush Hero Game
is to move the hero to the left or right out of the path of falling rocks which will crush him. The template includes some fun graphics and great sound effects that are triggered when the hero gets hit.
The game comes with layered PSD files for all the assets, which makes it easy to reskin.
Some of its outstanding features are the best score and game rating social features, as well as support for monetization through ad networks and AdMob banners. It is also Game Centre
integrated and comes with detailed instructions for customisation.
With the Dragon
Jump template, the player is a knight defending the kingdom from dragons
flying overhead. The player can jump on the dragons to kill them or can kill them with a spear. Players may share their scores on various social media.
This template is integrated with Game Centre, so users can share their highscores, as well as with Google Analytics, ad networks, and AdMob banner ads for easy tracking and monetization. The template
also comes with
complete documentation to guide users through customisation.
One of the newest iOS games in CodeCanyon, this
template for the classic Tic Tac Toe game
allows players to play against the phone or against another player on the same phone.
Coded with Swift 3 and the latest version of Xcode, the game interface is fully customizable through Storyboard. Detailed instructions for reskinning and customising are included.
The app will auto resize for various screen sizes and
supports AdMob. Users have found that “the app functions really well.”
Conclusion
This is just a small selection of hundreds of iOS
game templates we have available at CodeCanyon, so if none of these featured templates quite fits
your needs, there are plenty of other great options to choose from.
And if you
want to improve your skills building iOS games, head on over to the site
and check out some of the ever so useful mobile development tutorials and courses we have on offer.
The Meteor project is an open-source web app development platform that enables you to create apps written entirely in JavaScript.
Meteor provides development tools for essential web app needs, making it naturally suitable for start-ups and new projects in general. It offers features such as deployment to many devices from one code base (iOS, Android, Desktop), with hot push updates supported out of the box.
This means that you can update the app on the user's device, without waiting for App Store approval. The wealth of packages available via npm and its own Atmosphere library make Meteor an interesting tool to work with.
Rapid Development in Meteor
One of the main reasons I started using Meteor, three years ago now, was the rapid ability it has to deliver a working web app within hours. It enabled me to deliver for my clients' high expectations and their pre-first-round funding budget.
Finally, with this web framework that can accommodate big ideas with humble beginnings, top-quality reactive mobile web apps are within the reach of a single-person development team.
NPM + Atmosphere Packages
Any package from npm is available in Meteor, so if you like using tools like Grunt, Browserify, Webpack, Bootstrap, React, jQuery and Angular, you will have no issues using these in Meteor.
Running this command will update your package.json with the dependency, and also download the package into your app’s local node_modules/ directory.
Version Control
An important note: For portability, I recommend you don’t commit the node_modules/ into git, and on passing to a new developer instead ask them to run meteor npm install, which will install all of the packages required.
User Accounts
The accounts-ui package enables users to log in and register for the app, and it also gives oAuth support, interfacing it with Meteor Accounts.
For brand and communication purposes, customizing the email verification (sendVerificationEmail) or invitations (sendEnrollmentEmail) to fit the overall theme of the app is a common request.
A great way to do HTML email in Meteor is to use the pretty emails package by yogiben.
meteor add yogiben:pretty-email
Now you can change the verification email with just a few lines:
PrettyEmail.defaults.verifyEmail =
heading: 'Yo - You Need to activate your account on mega mushrooms'
buttonText: 'Activate'
...
For your company information, you can configure PrettyEmail.options like so:
If you want to add a template, you can do so by customizing the following options:
PrettyEmail.send 'call-to-action',
to: 'myuser@myuser.com'
subject: 'You got new message'
heading: 'Your friend sent you a message'
message: 'Click the button below to read the message'
buttonText: 'Read message'
buttonUrl: 'http://mycompany.com/messages/2314'
messageAfterButton: "I come after the button!"
Here is an example of the activation email the user will receive in their email client.
Pretty email has a whole ton more options for social, back links, the header and footer and so on—read more on the manual page.
Ratchet, Materialize and Bootstrap Support
There are also user accounts packages for each of these popular front-end libraries, as well as Ionic. Each can be fully configured to meet your needs.
Similar to the user accounts, there are packages available for popular front-end libraries like Bootstrap, Angular, React and the Blaze template engine, along with many others such as Semantic UI.
Searching on atmosphere yields many results; here are some of my favorites:
If you are using Iron Router then you can utilise the meteor-transitioner package. Working on your Blaze template, add the following handlebars around your {{yield}}:
For more information on transitions, check the README.
Mongo
For editing your mongo database in the web browser, the Mongol tool is one of the best I have used. Once you have installed Mongol with:
$ meteor add msavin:mongol
Just press Control-M and you will have access to your collections with full in-browser CRUD support.
I find using Mongol very useful when debugging new apps or data changes to existing ones.
Browser Extensions
For users who are working in Chrome, there is a Mongo plugin available called MiniMongo which will enable you to browse the Meteor database in the developer tools pane.
The MiniMongo Explorer project is available on GitHub if you want to build the source yourself.
Deployment
Using the excellent free tool mup, you can deploy a site to a Digital Ocean VPN within minutes.
The configuration is very simple, and you will only need to have your app, SSH credentials, and maybe an SSL certificate if you would like to enable HTTPS.
To set up mup, start by making a directory for deployment:
$ cd meteor-app
$ mkdir .deploy
$ cd .deploy
Install mup:
$ npm install -g mup
Initialize the directory:
$ mup init
Now you need to configure the deployment by setting up the mup.js file that has been created via the previous step.
module.exports = {
servers: {
one: {
host: '1.2.3.4',
username: 'root',
// pem: '/home/user/.ssh/id_rsa',
// password: 'password',
// or leave blank to authenticate using ssh-agent
opts: {
port: 22,
},
}
},
meteor: {
name: 'app',
path: '../app',
// lets you add docker volumes (optional)
volumes: {
// passed as '-v /host/path:/container/path' to the docker run command
'/host/path': '/container/path',
'/second/host/path': '/second/container/path'
},
docker: {
// Change the image to 'kadirahq/meteord' if you
// are using Meteor 1.3 or older
image: 'abernix/meteord:base' , // (optional)
imagePort: 80, // (optional, default: 80)
// lets you add/overwrite any parameter on
// the docker run command (optional)
args: [
'--link=myCustomMongoDB:myCustomMongoDB', // linking example
'--memory-reservation 200M' // memory reservation example
],
// (optional) Only used if using your own ssl certificates.
// Default is "meteorhacks/mup-frontend-server"
imageFrontendServer: 'meteorhacks/mup-frontend-server',
// lets you bind the docker container to a
// specific network interface (optional)
bind: '127.0.0.1',
// lets you add network connections to perform after run
// (runs docker network connect <net name> for each network listed here)
networks: [
'net1'
]
},
// list of servers to deploy, from the 'servers' list
servers: {
one: {}, two: {}, three: {}
},
buildOptions: {
// skip building mobile apps, but still build the web.cordova architecture
serverOnly: true,
debug: true,
cleanAfterBuild: true, // default
buildLocation: '/my/build/folder', // defaults to /tmp/<uuid>
// set serverOnly: false if want to build mobile apps when deploying
// Remove this property for mobileSettings to use your settings.json
// (optional)
mobileSettings: {
yourMobileSetting: 'setting value'
},
server: 'http://app.com', // your app url for mobile app access (optional)
// adds --allow-incompatible-updates arg to build command (optional)
allowIncompatibleUpdates: true,
},
env: {
// PORT: 8000, // useful when deploying multiple instances (optional)
ROOT_URL: 'http://app.com', // If you are using ssl, this needs to start with https
MONGO_URL: 'mongodb://localhost/meteor'
},
log: { // (optional)
driver: 'syslog',
opts: {
'syslog-address': 'udp://syslogserverurl.com:1234'
}
},
ssl: {
// Enables let's encrypt (optional)
autogenerate: {
email: 'email.address@domain.com',
domains: 'website.com,www.website.com' // comma separated list of domains
}
},
deployCheckWaitTime: 60, // default 10
// lets you define which port to check after the deploy process, if it
// differs from the meteor port you are serving
// (like meteor behind a proxy/firewall) (optional)
deployCheckPort: 80,
// Shows progress bar while uploading bundle to server (optional)
// You might need to disable it on CI servers
enableUploadProgressBar: true // default false.
},
mongo: { // (optional)
port: 27017,
version: '3.4.1', // (optional), default is 3.4.1
servers: {
one: {},
},
},
};
Now set up the server:
$ mup setup
And deploy:
$ mup deploy
You will see confirmation of each step of the process in your terminal. Once the deployment has finished, the app is now live on your server, and you can check it out in your browser.
For more information on configuration with SSL, please refer to this guide.
Caching
Meteor comes with appcache, which will cache the app after the first load, but not for offline usage.
If you would like to cache offline then you will need to use GroundMeteor. This is a client-side only storage which works on LocalCollection.
For an example, we can monitor a collection and store it locally:
local = new Ground.Collection('offlineCache');
local.observeSource(Data.find());
Meteor.setTimeout(() => {
// Stop observing - keeping all documents as is
local.stopObserver();
}, 1000);
Here, the contents of the Data.find() publication will be cached into an offline Ground Collection.
Key Stores Caches
For memory keystore caching, you can use the memcache package or redis package to enable you to access data caching on the server.
The package assumes the memcache or redis server is already running, and then a key can be stored in memcache.
var memcached = new Memcached( [ 'localhost:11211', 'localhost:11212'] );
memcached.set( "key", "value", 2, function (err, res) {
console.log("memcached set action response", err, res);
});
Or in Redis Collection:
var redisCollection = new Meteor.RedisCollection("redis");
Meteor.publish("movies", function () {
return redisCollection.matching("movies-*");
});
The redis implementation is very nice as it can be used to broadcast via the publish/subscribe architecture of Meteor.
Development Tools
Besides the tools already mentioned, the Firebug-like browser extensions available in Chrome for Meteor make debugging a lot easier. You can monitor the data being passed from the server to the client easily inside the DDP tab and review your Blaze template via the Blaze inspector.
IDE Tools
For development in Sublime text editor, a custom version of the Tern.js package provides autocompletion for Meteor. Download it on GitHub.
JetBrains provides automatic integration of Meteor projects with syntax highlighting and debugging. Atom also provides several packages for syntax, code snippets, and autocomplete.
Boiler Plates
If you just want to get going quickly with an app that's already set up, you can look at yogiben's starter. The Meteor chef also has an excellent base starter. If you want to use React, you can look at this Yeoman generator for a starting point.
For further help in starting your app, Meteor Kitchen will provide a GUI for routes and configuration.
Admin Panels
If you are using Yogiben's Meteor Starter, you can also be sure the admin panel he has created will work fine in conjunction. Almost all other projects that are using mongo and blaze should be suitable for this, although React Router apps may have a conflict with Iron Router.
The theme for the admin panel is extensibly modifiable, and you can read the documentation.
Meteor From Meteorites
Before we wrap up here, let me give you some background on the Meteor project. Meteor was publicly released in January 2012, the results of a Y Combinator incubator project which received $11.2 million in funding from venture capitalist firm Andreessen Horowitz.
It initially launched with a package manager named Meteorite (mrt on the cli), and extendability has always been a core element to Meteor. With the release of Meteor 0.9, things changed for good with the inception of Atmosphere packages.
Adding packages to Meteor apps became as simple as meteor add mrt:moment.
As momentum for the project continued, it garnered public interest and was adopted by a wide range of developers old and new. One of the core drivers for this, I believe, was the flexibility of being able to work fully in JavaScript—client and server.
Initially, npm packages were not available, until Meteor released version 1.3, which marked a serious milestone in the development cycle so far.
Working in JavaScript fully throughout meant Meteor had the ability to interface with the vast library of existing JS and Node libraries now with the integration of npm. This gave Meteor a cutting edge as a framework.
It gives perspective of our progress in web development certainly to think of the sheer magnitude of power that Meteor, npm and its atmosphere packages deliver to your fingertips. This is a big change from how we used to do it, with a large development workforce, in the pre-jQuery, pre-npm, pre-Bower days of Flash, NotePad/Dreamweaver and PHP 3. I have worked on teams of over ten employees to produce works which, without sounding ridiculous, can be literally finished in weeks in Meteor by one or two developers.
With these tools at your disposal, there has never been a better time to be a technically minded web entrepreneur. Building your dream apps yourself is certainly within reach.
For an example, earlier today I put together a database-backed CMS with a complete user system and admin back office with Facebook and Google+ oAuth logins. I deployed it to a new server to share with people to debug, and I could see the data being changed in real time.
Meteor is really that fast to work with. Form validation is done and proper data entry work can begin tomorrow, after just eight hours development time.
Conclusion
Meteor is a robust and powerful web application engine that will give you a head start in app development.
Hopefully the packages and advice mentioned here will enable you to make your app in no time at all. For me, realizing my app ideas in a short time span can mean creativity flourishes and innovation is easier.
You can speed through development with ease as in Meteor there is practically a package for everything, and more of the focus is on configuration, which makes the development experience much nicer.
To get support with issues on a specific project, you may wish to search the project on GitHub and make an issue on the repository for the developers to deal with.
If you are looking for more advice on Meteor, the official forums are always a good place to ask.
The Meteor project is an open-source web app development platform that enables you to create apps written entirely in JavaScript.
Meteor provides development tools for essential web app needs, making it naturally suitable for start-ups and new projects in general. It offers features such as deployment to many devices from one code base (iOS, Android, Desktop), with hot push updates supported out of the box.
This means that you can update the app on the user's device, without waiting for App Store approval. The wealth of packages available via npm and its own Atmosphere library make Meteor an interesting tool to work with.
Rapid Development in Meteor
One of the main reasons I started using Meteor, three years ago now, was the rapid ability it has to deliver a working web app within hours. It enabled me to deliver for my clients' high expectations and their pre-first-round funding budget.
Finally, with this web framework that can accommodate big ideas with humble beginnings, top-quality reactive mobile web apps are within the reach of a single-person development team.
NPM + Atmosphere Packages
Any package from npm is available in Meteor, so if you like using tools like Grunt, Browserify, Webpack, Bootstrap, React, jQuery and Angular, you will have no issues using these in Meteor.
Running this command will update your package.json with the dependency, and also download the package into your app’s local node_modules/ directory.
Version Control
An important note: For portability, I recommend you don’t commit the node_modules/ into git, and on passing to a new developer instead ask them to run meteor npm install, which will install all of the packages required.
User Accounts
The accounts-ui package enables users to log in and register for the app, and it also gives oAuth support, interfacing it with Meteor Accounts.
For brand and communication purposes, customizing the email verification (sendVerificationEmail) or invitations (sendEnrollmentEmail) to fit the overall theme of the app is a common request.
A great way to do HTML email in Meteor is to use the pretty emails package by yogiben.
meteor add yogiben:pretty-email
Now you can change the verification email with just a few lines:
PrettyEmail.defaults.verifyEmail =
heading: 'Yo - You Need to activate your account on mega mushrooms'
buttonText: 'Activate'
...
For your company information, you can configure PrettyEmail.options like so:
If you want to add a template, you can do so by customizing the following options:
PrettyEmail.send 'call-to-action',
to: 'myuser@myuser.com'
subject: 'You got new message'
heading: 'Your friend sent you a message'
message: 'Click the button below to read the message'
buttonText: 'Read message'
buttonUrl: 'http://mycompany.com/messages/2314'
messageAfterButton: "I come after the button!"
Here is an example of the activation email the user will receive in their email client.
Pretty email has a whole ton more options for social, back links, the header and footer and so on—read more on the manual page.
Ratchet, Materialize and Bootstrap Support
There are also user accounts packages for each of these popular front-end libraries, as well as Ionic. Each can be fully configured to meet your needs.
Similar to the user accounts, there are packages available for popular front-end libraries like Bootstrap, Angular, React and the Blaze template engine, along with many others such as Semantic UI.
Searching on atmosphere yields many results; here are some of my favorites:
If you are using Iron Router then you can utilise the meteor-transitioner package. Working on your Blaze template, add the following handlebars around your {{yield}}:
For more information on transitions, check the README.
Mongo
For editing your mongo database in the web browser, the Mongol tool is one of the best I have used. Once you have installed Mongol with:
$ meteor add msavin:mongol
Just press Control-M and you will have access to your collections with full in-browser CRUD support.
I find using Mongol very useful when debugging new apps or data changes to existing ones.
Browser Extensions
For users who are working in Chrome, there is a Mongo plugin available called MiniMongo which will enable you to browse the Meteor database in the developer tools pane.
The MiniMongo Explorer project is available on GitHub if you want to build the source yourself.
Deployment
Using the excellent free tool mup, you can deploy a site to a Digital Ocean VPN within minutes.
The configuration is very simple, and you will only need to have your app, SSH credentials, and maybe an SSL certificate if you would like to enable HTTPS.
To set up mup, start by making a directory for deployment:
$ cd meteor-app
$ mkdir .deploy
$ cd .deploy
Install mup:
$ npm install -g mup
Initialize the directory:
$ mup init
Now you need to configure the deployment by setting up the mup.js file that has been created via the previous step.
module.exports = {
servers: {
one: {
host: '1.2.3.4',
username: 'root',
// pem: '/home/user/.ssh/id_rsa',
// password: 'password',
// or leave blank to authenticate using ssh-agent
opts: {
port: 22,
},
}
},
meteor: {
name: 'app',
path: '../app',
// lets you add docker volumes (optional)
volumes: {
// passed as '-v /host/path:/container/path' to the docker run command
'/host/path': '/container/path',
'/second/host/path': '/second/container/path'
},
docker: {
// Change the image to 'kadirahq/meteord' if you
// are using Meteor 1.3 or older
image: 'abernix/meteord:base' , // (optional)
imagePort: 80, // (optional, default: 80)
// lets you add/overwrite any parameter on
// the docker run command (optional)
args: [
'--link=myCustomMongoDB:myCustomMongoDB', // linking example
'--memory-reservation 200M' // memory reservation example
],
// (optional) Only used if using your own ssl certificates.
// Default is "meteorhacks/mup-frontend-server"
imageFrontendServer: 'meteorhacks/mup-frontend-server',
// lets you bind the docker container to a
// specific network interface (optional)
bind: '127.0.0.1',
// lets you add network connections to perform after run
// (runs docker network connect <net name> for each network listed here)
networks: [
'net1'
]
},
// list of servers to deploy, from the 'servers' list
servers: {
one: {}, two: {}, three: {}
},
buildOptions: {
// skip building mobile apps, but still build the web.cordova architecture
serverOnly: true,
debug: true,
cleanAfterBuild: true, // default
buildLocation: '/my/build/folder', // defaults to /tmp/<uuid>
// set serverOnly: false if want to build mobile apps when deploying
// Remove this property for mobileSettings to use your settings.json
// (optional)
mobileSettings: {
yourMobileSetting: 'setting value'
},
server: 'http://app.com', // your app url for mobile app access (optional)
// adds --allow-incompatible-updates arg to build command (optional)
allowIncompatibleUpdates: true,
},
env: {
// PORT: 8000, // useful when deploying multiple instances (optional)
ROOT_URL: 'http://app.com', // If you are using ssl, this needs to start with https
MONGO_URL: 'mongodb://localhost/meteor'
},
log: { // (optional)
driver: 'syslog',
opts: {
'syslog-address': 'udp://syslogserverurl.com:1234'
}
},
ssl: {
// Enables let's encrypt (optional)
autogenerate: {
email: 'email.address@domain.com',
domains: 'website.com,www.website.com' // comma separated list of domains
}
},
deployCheckWaitTime: 60, // default 10
// lets you define which port to check after the deploy process, if it
// differs from the meteor port you are serving
// (like meteor behind a proxy/firewall) (optional)
deployCheckPort: 80,
// Shows progress bar while uploading bundle to server (optional)
// You might need to disable it on CI servers
enableUploadProgressBar: true // default false.
},
mongo: { // (optional)
port: 27017,
version: '3.4.1', // (optional), default is 3.4.1
servers: {
one: {},
},
},
};
Now set up the server:
$ mup setup
And deploy:
$ mup deploy
You will see confirmation of each step of the process in your terminal. Once the deployment has finished, the app is now live on your server, and you can check it out in your browser.
For more information on configuration with SSL, please refer to this guide.
Caching
Meteor comes with appcache, which will cache the app after the first load, but not for offline usage.
If you would like to cache offline then you will need to use GroundMeteor. This is a client-side only storage which works on LocalCollection.
For an example, we can monitor a collection and store it locally:
local = new Ground.Collection('offlineCache');
local.observeSource(Data.find());
Meteor.setTimeout(() => {
// Stop observing - keeping all documents as is
local.stopObserver();
}, 1000);
Here, the contents of the Data.find() publication will be cached into an offline Ground Collection.
Key Stores Caches
For memory keystore caching, you can use the memcache package or redis package to enable you to access data caching on the server.
The package assumes the memcache or redis server is already running, and then a key can be stored in memcache.
var memcached = new Memcached( [ 'localhost:11211', 'localhost:11212'] );
memcached.set( "key", "value", 2, function (err, res) {
console.log("memcached set action response", err, res);
});
Or in Redis Collection:
var redisCollection = new Meteor.RedisCollection("redis");
Meteor.publish("movies", function () {
return redisCollection.matching("movies-*");
});
The redis implementation is very nice as it can be used to broadcast via the publish/subscribe architecture of Meteor.
Development Tools
Besides the tools already mentioned, the Firebug-like browser extensions available in Chrome for Meteor make debugging a lot easier. You can monitor the data being passed from the server to the client easily inside the DDP tab and review your Blaze template via the Blaze inspector.
IDE Tools
For development in Sublime text editor, a custom version of the Tern.js package provides autocompletion for Meteor. Download it on GitHub.
JetBrains provides automatic integration of Meteor projects with syntax highlighting and debugging. Atom also provides several packages for syntax, code snippets, and autocomplete.
Boiler Plates
If you just want to get going quickly with an app that's already set up, you can look at yogiben's starter. The Meteor chef also has an excellent base starter. If you want to use React, you can look at this Yeoman generator for a starting point.
For further help in starting your app, Meteor Kitchen will provide a GUI for routes and configuration.
Admin Panels
If you are using Yogiben's Meteor Starter, you can also be sure the admin panel he has created will work fine in conjunction. Almost all other projects that are using mongo and blaze should be suitable for this, although React Router apps may have a conflict with Iron Router.
The theme for the admin panel is extensibly modifiable, and you can read the documentation.
Meteor From Meteorites
Before we wrap up here, let me give you some background on the Meteor project. Meteor was publicly released in January 2012, the results of a Y Combinator incubator project which received $11.2 million in funding from venture capitalist firm Andreessen Horowitz.
It initially launched with a package manager named Meteorite (mrt on the cli), and extendability has always been a core element to Meteor. With the release of Meteor 0.9, things changed for good with the inception of Atmosphere packages.
Adding packages to Meteor apps became as simple as meteor add mrt:moment.
As momentum for the project continued, it garnered public interest and was adopted by a wide range of developers old and new. One of the core drivers for this, I believe, was the flexibility of being able to work fully in JavaScript—client and server.
Initially, npm packages were not available, until Meteor released version 1.3, which marked a serious milestone in the development cycle so far.
Working in JavaScript fully throughout meant Meteor had the ability to interface with the vast library of existing JS and Node libraries now with the integration of npm. This gave Meteor a cutting edge as a framework.
It gives perspective of our progress in web development certainly to think of the sheer magnitude of power that Meteor, npm and its atmosphere packages deliver to your fingertips. This is a big change from how we used to do it, with a large development workforce, in the pre-jQuery, pre-npm, pre-Bower days of Flash, NotePad/Dreamweaver and PHP 3. I have worked on teams of over ten employees to produce works which, without sounding ridiculous, can be literally finished in weeks in Meteor by one or two developers.
With these tools at your disposal, there has never been a better time to be a technically minded web entrepreneur. Building your dream apps yourself is certainly within reach.
For an example, earlier today I put together a database-backed CMS with a complete user system and admin back office with Facebook and Google+ oAuth logins. I deployed it to a new server to share with people to debug, and I could see the data being changed in real time.
Meteor is really that fast to work with. Form validation is done and proper data entry work can begin tomorrow, after just eight hours development time.
Conclusion
Meteor is a robust and powerful web application engine that will give you a head start in app development.
Hopefully the packages and advice mentioned here will enable you to make your app in no time at all. For me, realizing my app ideas in a short time span can mean creativity flourishes and innovation is easier.
You can speed through development with ease as in Meteor there is practically a package for everything, and more of the focus is on configuration, which makes the development experience much nicer.
To get support with issues on a specific project, you may wish to search the project on GitHub and make an issue on the repository for the developers to deal with.
If you are looking for more advice on Meteor, the official forums are always a good place to ask.
Building an app used to be the domain of hardcore developers
only, but with over 1,400 app templates for sale at CodeCanyon,
even complete beginners to coding can build an app.
But what is an app template, you might ask. Well,
essentially, it’s an app with core functions already implemented for you so
that you can customise it easily and add the elements you most prefer to the app's
code to create the product you want.
Many beginners use app templates as a learning tool to
improve their coding skills, while others choose to upload their new app
creations to iTunes for approval and inclusion in the app store.
Whatever your needs, get started by taking a look at the 15
best iOS app templates available at CodeCanyon. You may just find exactly what you’re looking for.
The magic of the Universal for iOS app template is that it lets users create just about any app they want
by pulling in unlimited content from blogs, timelines, feeds, channels, playlists,
webpages, etc., and easily combining them in one customisable app.
One of the best-selling iOS app templates at CodeCanyon, Universal
for iOS supports most popular web
resources, like WordPress, YouTube, Facebook, RSS, etc. It also supports AdMob and
gives your users the option of removing banners and interstitial ads with an
easy in-app purchase.
The app is
completely based on Objective-C and designed for the latest version of iOS. It
comes with step-by-step instructions and video tutorials on how to configure
your template from scratch and is suitable for both professionals and beginners
as no code knowledge is required.
Customers say
Universal for iOS is a “very good app” with “no crashes”.
There are a large
number of users out there with a content-rich website that they want to
convert into a gorgeous app, allowing their visitors to access the key
features of the site easily and seamlessly. That’s what the BeoNews
app template does.
One of the best-rated templates in this category, BeoNews will allow users to convert any of
the content of their WordPress site, including video, photos and blog, into a mobile
app. How cool is that?
The app stores user data on Firebase and synchronises across
devices.
Customers have praised the app’s design quality and the
support offered.
Another app that allows you to convert your website content
into an app, WebViewGold app template’s key difference from BeoNews is
that it enables users to turn their entire site into an app. It does so by using
a Swift Xcode package to wrap the URL or local HTML into an iOS app. The real
genius of this app template, though, is that it does its work in just a few
clicks. So no coding knowledge is required!
One customer, zyn, said:
“The script is awesome + the team
is incredible …. They helped me integrate exactly what I need.”
With so many businesses selling products and services online
these days, the MStore Pro app template is an easy favourite among developers. The e-commerce app
allows users to convert their existing online shop to a mobile store app so
that they can more easily target busy shoppers who’re trying to make the most
of their time by doing their shopping while commuting or waiting in a queue.
The template requires no coding skills and is very easy to
customise. It is fully integrated with WordPress and WooCommerce, supports
PayPal, Stripe and COD, and allows users to log in with their Facebook account.
What more could you ask for?
Mokets, which stands for mobile markets, is another e-commerce app template targeting
today’s busy shoppers. The app template distinguishes itself with a gorgeous Pinterest-type
grid that displays items for sale with all relevant information. It features
user registration and login, shopping cart with checkout, transaction history,
Apple push notification, user feedback, analytics which track customer
interests, and so much more.
Customer, Simorq,
said:
“Apple approved my app just 5 mins ago. The app is really
great and works well.”
As sustainable living becomes more and more critical, apps
that allow users to buy and sell used items and handcrafted items have grown in
popularity. woopy is an app template that allows developers to create listing apps that
facilitate such buying and selling online. Users can browse by keyword or
category. They can also chat with sellers or potential buyers and give feedback
on each transaction.
One of the app’s
outstanding features for sellers is the ability to add a 10-second video to
their listings. Another is the app’s optional email verification system that
gives buyers and sellers extra assurance by posting a verification symbol next
to the user’s name.
Customer Kaya09
said:
“Great support, well designed and code is perfect and no issue with iTunes,
approve in a few hours.”
Though we all know that online shopping is becoming more and
more popular, most seasoned shoppers will admit that shopping in person gives a
certain sensory pleasure that online shopping cannot emulate.
When you need to find a specific item or store, however, and
don’t want to spend all day driving from one end of town to the other or doing
laps around the mall, a store finder app is a lifesaver. Enter the Store Finder v1.9 app
template, a developer’s dream, with a long list of must-have features like
call, email and SMS integration, Google directions, social media logins, pinch
and zoom function, and so much more.
Customer reviewer larrybird1 said about the app:
“This is a fine code, from a fine developer … oh, and the
support is pretty good.”
Restaurant finder apps are always popular because they solve
a common problem: how to find a good place to eat when you’re in a
neighbourhood you don’t know. The Restaurant Finder v1.5 app template allows you to create your own
app to help users looking for restaurants in a specific area.
The template uses
an XML/JSON file for restaurant data, so you have full control over the
restaurants you want to include as well as the amount of information you want
to include about each restaurant.
This Objective-C-based
app template supports AdMob.
If you’re passionate
about photography (and really, who isn’t these days?), you’re always on the lookout
for photo editing apps that make your photos look even better than they already
do when you post them to Instagram, Facebook, or your preferred social media
site.
The PhotoGram app template requires no configuration and is easy to customise.
Some of its selling features that will keep users happy are its filters, tonal adjustments, resizing, and cropping.
Users can also add text to their images and share them directly from the
app on Facebook, Instagram, Twitter, etc. The app supports both iAd and AdMob.
Customers confirm
that PhotoGram is indeed “easy to customise” with “clean code.”
Owing to the popularity of photo editing apps, we’re
featuring not just one but two photo app templates in our best of 2017 roundup. The PikLab app template has fewer bells and whistles than the previous PhotoGram app
template, and that is its main selling point. It will appeal to users who prize
simplicity and ease of use and are looking for a photo editing app that allows
for a bit more creative play by using features such as collage frames, stickers,
borders, textures, and custom fonts. Users can also share their pictures directly
to Facebook, Twitter, Instagram, WhatsApp, etc.
The app is AdMob ready, and includes PSD graphics and a PDF
user guide.
One happy customer, tunebaco, said:
“Code, Design,
Documentation, support! Everything is perfect with this guy!”
Cooking shows,
cooking competitions, cooking websites, Instagram food porn. In the last decade
or so, we’ve become positively obsessed with food and how to prepare it well.
So of course recipe apps have gained in popularity as well, and developers will
love the iOS Recipe App template.
iOS Recipe App
allows users to organize their recipes into categories, which are accessible
both from the home screen and the menu. Users can build their own favourite
category and add both video and images to each recipe. Other features include push
notification, search, shopping list, and the ability to share recipes. The app also supports AdMob.
Another thing that has proliferated in the past ten years is the
number of blogs and online independent and alternative news sources we have
access to—so much so that it is impossible to keep track of our favourites
without a good RSS feed reader. Feedews is a highly customisable RSS feed reader app template that allows
users to get all their articles and news in one place.
Users can organise their
sources into categories and can share articles with their social networks or
via email. The template also supports the translation of the app into other
languages.
Many users say the app is “well designed and documented”.
If you accept that good organisation is key to high
productivity, then a to-do app is an indispensable tool for you. The ToDo List and Task Reminder is one
of the newest iOS app templates on CodeCanyon and has a few cool features that
will interest developers in the market for an organising app.
The app allows users to set tasks according to their
priority from high to low and displays either a progress wheel of their task or
a pie chart based on the priority you’ve assigned it. It includes a map feature which allows users
to mark the place where the task is taking place.
Users can also include an image with a task
and set reminders using their favourite ringtone or set each reminder with a
different tone or talking alarm. Best of
all, users can create secret lists that they can keep hidden from prying eyes. These are just a few of the great features
that set this app apart from other to-do list apps already on the market.
Love Instagram? Want
to create your own Instagram-type app? We have just the thing for you. The Mustage app template allows developers to create a photo and video sharing app
in the vein of Instagram where users can follow, like, comment and share photos.
The app allows users to log in with their email, Google or Facebook accounts
and supports monetisation with AdMob. It also supports push notifications
and comes with built-in Analytics to
monitor performance.
Customers have not only been
impressed with the template itself, but have also commented on the high
quality of support offered to customers. One such customer, birdiesawyer, said:
“This template is AWESOME and as a person
learning Swift I can see how things were structured and why they were
structured that way. The support has been outstanding and every question I had
was answered to my satisfaction.”
Our roundup of the 15 best iOS app templates wouldn’t be
complete without including a game, and our choice to round out the list is the
highly rated Four
Dots game template.
This game is made up of a cluster of four circles, each of a
different colour, at the bottom of the screen. Once the game begins, dots are randomly generated from the top of the
screen and fall down the screen towards the cluster. The player must rotate the
cluster of circles at the bottom of the screen by tapping the screen quickly so
that the circle facing the falling dot matches it in colour. For every correct
match, the player gains a point.
Give it
a whirl. I dare you to not get addicted. The template supports AdMob and comes
with PSD files and a comprehensive user guide.
Conclusion
These 15 best iOS app templates of 2017 are just a small selection
of the hundreds of iOS
app templates we have available at CodeCanyon, so if none of them quite
fits your needs, there are plenty of other great options to choose from.
And if you want to improve your skills building iOS apps and
templates, then check out some of the ever-so-useful iOS tutorials we have on offer!
Building an app used to be the domain of hardcore developers
only, but with over 1,400 app templates for sale at CodeCanyon,
even complete beginners to coding can build an app.
But what is an app template, you might ask. Well,
essentially, it’s an app with core functions already implemented for you so
that you can customise it easily and add the elements you most prefer to the app's
code to create the product you want.
Many beginners use app templates as a learning tool to
improve their coding skills, while others choose to upload their new app
creations to iTunes for approval and inclusion in the app store.
Whatever your needs, get started by taking a look at the 15
best iOS app templates available at CodeCanyon. You may just find exactly what you’re looking for.
The magic of the Universal for iOS app template is that it lets users create just about any app they want
by pulling in unlimited content from blogs, timelines, feeds, channels, playlists,
webpages, etc., and easily combining them in one customisable app.
One of the best-selling iOS app templates at CodeCanyon, Universal
for iOS supports most popular web
resources, like WordPress, YouTube, Facebook, RSS, etc. It also supports AdMob and
gives your users the option of removing banners and interstitial ads with an
easy in-app purchase.
The app is
completely based on Objective-C and designed for the latest version of iOS. It
comes with step-by-step instructions and video tutorials on how to configure
your template from scratch and is suitable for both professionals and beginners
as no code knowledge is required.
Customers say
Universal for iOS is a “very good app” with “no crashes”.
There are a large
number of users out there with a content-rich website that they want to
convert into a gorgeous app, allowing their visitors to access the key
features of the site easily and seamlessly. That’s what the BeoNews
app template does.
One of the best-rated templates in this category, BeoNews will allow users to convert any of
the content of their WordPress site, including video, photos and blog, into a mobile
app. How cool is that?
The app stores user data on Firebase and synchronises across
devices.
Customers have praised the app’s design quality and the
support offered.
Another app that allows you to convert your website content
into an app, WebViewGold app template’s key difference from BeoNews is
that it enables users to turn their entire site into an app. It does so by using
a Swift Xcode package to wrap the URL or local HTML into an iOS app. The real
genius of this app template, though, is that it does its work in just a few
clicks. So no coding knowledge is required!
One customer, zyn, said:
“The script is awesome + the team
is incredible …. They helped me integrate exactly what I need.”
With so many businesses selling products and services online
these days, the MStore Pro app template is an easy favourite among developers. The e-commerce app
allows users to convert their existing online shop to a mobile store app so
that they can more easily target busy shoppers who’re trying to make the most
of their time by doing their shopping while commuting or waiting in a queue.
The template requires no coding skills and is very easy to
customise. It is fully integrated with WordPress and WooCommerce, supports
PayPal, Stripe and COD, and allows users to log in with their Facebook account.
What more could you ask for?
Mokets, which stands for mobile markets, is another e-commerce app template targeting
today’s busy shoppers. The app template distinguishes itself with a gorgeous Pinterest-type
grid that displays items for sale with all relevant information. It features
user registration and login, shopping cart with checkout, transaction history,
Apple push notification, user feedback, analytics which track customer
interests, and so much more.
Customer, Simorq,
said:
“Apple approved my app just 5 mins ago. The app is really
great and works well.”
As sustainable living becomes more and more critical, apps
that allow users to buy and sell used items and handcrafted items have grown in
popularity. woopy is an app template that allows developers to create listing apps that
facilitate such buying and selling online. Users can browse by keyword or
category. They can also chat with sellers or potential buyers and give feedback
on each transaction.
One of the app’s
outstanding features for sellers is the ability to add a 10-second video to
their listings. Another is the app’s optional email verification system that
gives buyers and sellers extra assurance by posting a verification symbol next
to the user’s name.
Customer Kaya09
said:
“Great support, well designed and code is perfect and no issue with iTunes,
approve in a few hours.”
Though we all know that online shopping is becoming more and
more popular, most seasoned shoppers will admit that shopping in person gives a
certain sensory pleasure that online shopping cannot emulate.
When you need to find a specific item or store, however, and
don’t want to spend all day driving from one end of town to the other or doing
laps around the mall, a store finder app is a lifesaver. Enter the Store Finder v1.9 app
template, a developer’s dream, with a long list of must-have features like
call, email and SMS integration, Google directions, social media logins, pinch
and zoom function, and so much more.
Customer reviewer larrybird1 said about the app:
“This is a fine code, from a fine developer … oh, and the
support is pretty good.”
Restaurant finder apps are always popular because they solve
a common problem: how to find a good place to eat when you’re in a
neighbourhood you don’t know. The Restaurant Finder v1.5 app template allows you to create your own
app to help users looking for restaurants in a specific area.
The template uses
an XML/JSON file for restaurant data, so you have full control over the
restaurants you want to include as well as the amount of information you want
to include about each restaurant.
This Objective-C-based
app template supports AdMob.
If you’re passionate
about photography (and really, who isn’t these days?), you’re always on the lookout
for photo editing apps that make your photos look even better than they already
do when you post them to Instagram, Facebook, or your preferred social media
site.
The PhotoGram app template requires no configuration and is easy to customise.
Some of its selling features that will keep users happy are its filters, tonal adjustments, resizing, and cropping.
Users can also add text to their images and share them directly from the
app on Facebook, Instagram, Twitter, etc. The app supports both iAd and AdMob.
Customers confirm
that PhotoGram is indeed “easy to customise” with “clean code.”
Owing to the popularity of photo editing apps, we’re
featuring not just one but two photo app templates in our best of 2017 roundup. The PikLab app template has fewer bells and whistles than the previous PhotoGram app
template, and that is its main selling point. It will appeal to users who prize
simplicity and ease of use and are looking for a photo editing app that allows
for a bit more creative play by using features such as collage frames, stickers,
borders, textures, and custom fonts. Users can also share their pictures directly
to Facebook, Twitter, Instagram, WhatsApp, etc.
The app is AdMob ready, and includes PSD graphics and a PDF
user guide.
One happy customer, tunebaco, said:
“Code, Design,
Documentation, support! Everything is perfect with this guy!”
Cooking shows,
cooking competitions, cooking websites, Instagram food porn. In the last decade
or so, we’ve become positively obsessed with food and how to prepare it well.
So of course recipe apps have gained in popularity as well, and developers will
love the iOS Recipe App template.
iOS Recipe App
allows users to organize their recipes into categories, which are accessible
both from the home screen and the menu. Users can build their own favourite
category and add both video and images to each recipe. Other features include push
notification, search, shopping list, and the ability to share recipes. The app also supports AdMob.
Another thing that has proliferated in the past ten years is the
number of blogs and online independent and alternative news sources we have
access to—so much so that it is impossible to keep track of our favourites
without a good RSS feed reader. Feedews is a highly customisable RSS feed reader app template that allows
users to get all their articles and news in one place.
Users can organise their
sources into categories and can share articles with their social networks or
via email. The template also supports the translation of the app into other
languages.
Many users say the app is “well designed and documented”.
If you accept that good organisation is key to high
productivity, then a to-do app is an indispensable tool for you. The ToDo List and Task Reminder is one
of the newest iOS app templates on CodeCanyon and has a few cool features that
will interest developers in the market for an organising app.
The app allows users to set tasks according to their
priority from high to low and displays either a progress wheel of their task or
a pie chart based on the priority you’ve assigned it. It includes a map feature which allows users
to mark the place where the task is taking place.
Users can also include an image with a task
and set reminders using their favourite ringtone or set each reminder with a
different tone or talking alarm. Best of
all, users can create secret lists that they can keep hidden from prying eyes. These are just a few of the great features
that set this app apart from other to-do list apps already on the market.
Love Instagram? Want
to create your own Instagram-type app? We have just the thing for you. The Mustage app template allows developers to create a photo and video sharing app
in the vein of Instagram where users can follow, like, comment and share photos.
The app allows users to log in with their email, Google or Facebook accounts
and supports monetisation with AdMob. It also supports push notifications
and comes with built-in Analytics to
monitor performance.
Customers have not only been
impressed with the template itself, but have also commented on the high
quality of support offered to customers. One such customer, birdiesawyer, said:
“This template is AWESOME and as a person
learning Swift I can see how things were structured and why they were
structured that way. The support has been outstanding and every question I had
was answered to my satisfaction.”
Our roundup of the 15 best iOS app templates wouldn’t be
complete without including a game, and our choice to round out the list is the
highly rated Four
Dots game template.
This game is made up of a cluster of four circles, each of a
different colour, at the bottom of the screen. Once the game begins, dots are randomly generated from the top of the
screen and fall down the screen towards the cluster. The player must rotate the
cluster of circles at the bottom of the screen by tapping the screen quickly so
that the circle facing the falling dot matches it in colour. For every correct
match, the player gains a point.
Give it
a whirl. I dare you to not get addicted. The template supports AdMob and comes
with PSD files and a comprehensive user guide.
Conclusion
These 15 best iOS app templates of 2017 are just a small selection
of the hundreds of iOS
app templates we have available at CodeCanyon, so if none of them quite
fits your needs, there are plenty of other great options to choose from.
And if you want to improve your skills building iOS apps and
templates, then check out some of the ever-so-useful iOS tutorials we have on offer!
If you are developing an Android application that needs to interact with your back-end server, it is important that you take steps to defend it against bots—automated scripts that try to pass for human. Otherwise, your server stands a very real chance of being overrun by them.
CAPTCHAs, short for Completely Automated Public Turing tests for telling Computers and Humans Apart, are currently the most effective defense against bots. As you might already know, they are usually image, voice, or common sense-based tests that are easy for humans, but extremely hard for computers.
In this tutorial, I'll show you how to use the newly released SafetyNet reCAPTCHA API to add CAPTCHAs to your Android apps.
Prerequisites
To be able to follow this tutorial, you'll need the following:
Launch Android Studio and create a new project with an empty activity. In the Configure your new project form, make sure you type in a meaningful package name—you'll be using it while registering your app with the reCAPTCHA service.
Additionally, check the Include Kotlin Support field. Because Kotlin is now an official Android language, we'll be using it instead of Java in this tutorial.
SafetyNet APIs are a part of Google Play services. To be able to use them in your project, add the following implementation dependency to the build.gradle file of the app module:
Additionally, to perform network-related operations, we'll be using the Fuel library, which has a very concise Kotlin-based API. Therefore, add it as another implementation dependency.
Finally, press the Sync Now button to complete the project configuration.
2. Acquiring reCAPTCHA Keys
You'll need two keys before you can use the reCAPTCHA service:
a site key, which must be passed to the service from your Android app
and a secret key, which must be passed to the service from your back-end server
To get the keys, use your Google account and log in to the reCAPTCHA admin console. If you're opening the console for the first time, you'll automatically be presented with a short registration form where you can type in your app's package name.
After you accept the reCAPTCHA terms of service, go ahead and press the Register button to generate both the keys.
You can now add the site key to your Android Studio project by simply mentioning it inside the res/values/strings.xml file:
We'll be working with the secret key only towards the end of this tutorial, so note it down somewhere safe for now.
3. Generating CAPTCHAs
When we hear the word CAPTCHA, we usually think of messy images containing hard-to-read letters and numbers. Such CAPTCHAs, however, thanks to advances in computer vision technologies, are no longer good enough to stop all bots.
CAPTCHAs generated by the reCAPTCHA service are highly advanced, and very interactive too. In fact, solving them is akin to playing simple games. Consequently, you can't directly embed them in your activity's layout. Instead, you must add a button to the layout, which, when pressed, should lead the user to a new screen or dialog containing the CAPTCHAs.
The following code shows you how to add a Button widget to your activity's layout XML file:
<Button
android:id="@+id/are_you_human_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Are you human?" />
Before you start generating CAPTCHAs, you'll have to initialize a client for the SafetyNet API. You can do so by calling the getClient() method of the SafetyNet class. Accordingly, add the following code inside the onCreate() method of your Activity class:
val myClient: SafetyNetClient = SafetyNet.getClient(this)
The CAPTCHAs must be displayed when the user presses the button, so add an on-click event handler to it using the setOnClickListener() method. Inside the handler, all you need to do is call the verifyWithRecaptcha() method and pass your site key as an argument to it in order to open a dialog containing a CAPTCHA.
The return value of the verifyWithRecaptcha() method is a Task object. By attaching an on-success event handler to it, you'll be able to acquire a RecaptchaTokenResponse object containing a token you can use to tell if the user passed or failed the CAPTCHA. Here's how:
are_you_human_button.setOnClickListener {
myClient
.verifyWithRecaptcha(resources.getString(R.string.my_site_key))
.addOnSuccessListener { successEvent ->
val token: String = successEvent.tokenResult
// More code here
}
}
4. Validating CAPTCHA Tokens
The token you got in the previous step must again be passed to the reCAPTCHA service to check if the user passed or failed the test. However, this time, the call to the reCAPTCHA service must be made from your back-end server.
The server, of course, won't have the token unless your Android app sends it to it. Therefore, we must now write code to send tokens from the Android app to the server.
For now, let's assume that our server has an endpoint called validate, which can accept the token as a query string parameter. I'll be using 10.0.2.2 as the server's IP address and 8000 as its port. If you intend to run the server on your own computer and the app on an emulator running on the same computer, you too can use the same IP address.
val serverURL: String = "http://10.0.2.2:8000/validate"
You can now call the httpGet() method offered by the Fuel library to send the token to the server. The method expects a list of query string parameters as its only argument, so I suggest you use the listOf() utility method to create a list containing a single item: the token assigned to a query parameter named user_token.
Because the httpGet() method runs asynchronously, you must call the responseString() method in order to handle its return value. The following code shows you how:
serverURL.httpGet(listOf("user_token" to token))
.responseString { request, response, result ->
// More code here
}
You can see that we now have access to a result object. In case of no errors, it will contain our server's response as a string.
Let's assume that our server returns the string "PASS" if the user passes the test, and "FAIL" otherwise. What you actually do when the user passes or fails the test is, of course, up to you. For now, I suggest you simply display appropriate Toast messages. The following code shows you how to do so concisely:
result.fold({ data ->
if(data.contains("PASS"))
Toast.makeText(baseContext,
"You seem to be a human.",
Toast.LENGTH_LONG).show()
else
Toast.makeText(baseContext,
"You seem to be a bot!",
Toast.LENGTH_LONG).show()
}, { error ->
Log.d("ERROR", "Error connecting to the server")
})
At this point, the app is ready. You can go ahead and deploy it to your emulator or device.
5. Creating the Server
We made a lot of assumptions about our web server in earlier steps. It's now time to create it, making sure that it doesn't deviate from those assumptions.
A quick and easy way to create a fully functional web server is to use the Node.js platform and the Express.js framework. To create a new Node.js project, make a new directory on your computer and run the npm init command inside it.
mkdir my_web_server
cd my_web_server ; npm init -y
To add the Express framework to the project, you can use the npm install command.
npm install --save express
Additionally, we'll be needing the Request package to communicate with the reCAPTCHA service. Therefore, install it as another dependency.
npm install --save request
You can now use your favorite code editor to create a new file called index.js and start writing all the required server-side code.
Start by loading both the express and request modules using the require() function and creating a new Express application by calling the express() function.
Our Express application must have an endpoint called validate, which can be accessed using the HTTP GET method. Therefore, create a new route for it using the get() method:
myApp.get('/validate', function(req, resp) {
// More code here
});
To validate the token generated by the Android app, you must now make a POST request to the reCAPTCHA service. The request must contain your secret key and the token itself. The following code shows you how to build the POST request's body by extracting the token from the query string:
To actually make the POST request, you can call the post() method of the request module. Its response is a short JSON document containing a key called success. As you might expect, its value is true only if the user has passed the test.
The following code shows you how to parse the JSON document, extract the success key, and generate the "PASS" and "FAIL" responses our Android app needs:
request.post({
url: 'https://www.google.com/recaptcha/api/siteverify',
form: postData
}, function(error, response, body) {
jsonData = JSON.parse(body); // Parse the JSON document
if(jsonData.success) { // User passed the test
resp.send('PASS');
} else { // User didn't pass the test
resp.send('FAIL');
}
});
Lastly, you must call the listen() method of the Express application object to allow it to listen for connections.
myApp.listen(8000);
At this point our web server is ready. To start it, return to the terminal and run the following command:
node index.js
If you run your Android app now, press the button, and successfully solve a CAPTCHA, you should see a Toast message telling you that you are human.
Conclusion
You now know how to use the SafetyNet reCAPTCHA API to secure your Android app and back-end infrastructure against bots. You don't have to worry about automated signups, screen scrapers, or bot-generated spam any more.
If you are developing an Android application that needs to interact with your back-end server, it is important that you take steps to defend it against bots—automated scripts that try to pass for human. Otherwise, your server stands a very real chance of being overrun by them.
CAPTCHAs, short for Completely Automated Public Turing tests for telling Computers and Humans Apart, are currently the most effective defense against bots. As you might already know, they are usually image, voice, or common sense-based tests that are easy for humans, but extremely hard for computers.
In this tutorial, I'll show you how to use the newly released SafetyNet reCAPTCHA API to add CAPTCHAs to your Android apps.
Prerequisites
To be able to follow this tutorial, you'll need the following:
Launch Android Studio and create a new project with an empty activity. In the Configure your new project form, make sure you type in a meaningful package name—you'll be using it while registering your app with the reCAPTCHA service.
Additionally, check the Include Kotlin Support field. Because Kotlin is now an official Android language, we'll be using it instead of Java in this tutorial.
SafetyNet APIs are a part of Google Play services. To be able to use them in your project, add the following implementation dependency to the build.gradle file of the app module:
Additionally, to perform network-related operations, we'll be using the Fuel library, which has a very concise Kotlin-based API. Therefore, add it as another implementation dependency.
Finally, press the Sync Now button to complete the project configuration.
2. Acquiring reCAPTCHA Keys
You'll need two keys before you can use the reCAPTCHA service:
a site key, which must be passed to the service from your Android app
and a secret key, which must be passed to the service from your back-end server
To get the keys, use your Google account and log in to the reCAPTCHA admin console. If you're opening the console for the first time, you'll automatically be presented with a short registration form where you can type in your app's package name.
After you accept the reCAPTCHA terms of service, go ahead and press the Register button to generate both the keys.
You can now add the site key to your Android Studio project by simply mentioning it inside the res/values/strings.xml file:
We'll be working with the secret key only towards the end of this tutorial, so note it down somewhere safe for now.
3. Generating CAPTCHAs
When we hear the word CAPTCHA, we usually think of messy images containing hard-to-read letters and numbers. Such CAPTCHAs, however, thanks to advances in computer vision technologies, are no longer good enough to stop all bots.
CAPTCHAs generated by the reCAPTCHA service are highly advanced, and very interactive too. In fact, solving them is akin to playing simple games. Consequently, you can't directly embed them in your activity's layout. Instead, you must add a button to the layout, which, when pressed, should lead the user to a new screen or dialog containing the CAPTCHAs.
The following code shows you how to add a Button widget to your activity's layout XML file:
<Button
android:id="@+id/are_you_human_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Are you human?" />
Before you start generating CAPTCHAs, you'll have to initialize a client for the SafetyNet API. You can do so by calling the getClient() method of the SafetyNet class. Accordingly, add the following code inside the onCreate() method of your Activity class:
val myClient: SafetyNetClient = SafetyNet.getClient(this)
The CAPTCHAs must be displayed when the user presses the button, so add an on-click event handler to it using the setOnClickListener() method. Inside the handler, all you need to do is call the verifyWithRecaptcha() method and pass your site key as an argument to it in order to open a dialog containing a CAPTCHA.
The return value of the verifyWithRecaptcha() method is a Task object. By attaching an on-success event handler to it, you'll be able to acquire a RecaptchaTokenResponse object containing a token you can use to tell if the user passed or failed the CAPTCHA. Here's how:
are_you_human_button.setOnClickListener {
myClient
.verifyWithRecaptcha(resources.getString(R.string.my_site_key))
.addOnSuccessListener { successEvent ->
val token: String = successEvent.tokenResult
// More code here
}
}
4. Validating CAPTCHA Tokens
The token you got in the previous step must again be passed to the reCAPTCHA service to check if the user passed or failed the test. However, this time, the call to the reCAPTCHA service must be made from your back-end server.
The server, of course, won't have the token unless your Android app sends it to it. Therefore, we must now write code to send tokens from the Android app to the server.
For now, let's assume that our server has an endpoint called validate, which can accept the token as a query string parameter. I'll be using 10.0.2.2 as the server's IP address and 8000 as its port. If you intend to run the server on your own computer and the app on an emulator running on the same computer, you too can use the same IP address.
val serverURL: String = "http://10.0.2.2:8000/validate"
You can now call the httpGet() method offered by the Fuel library to send the token to the server. The method expects a list of query string parameters as its only argument, so I suggest you use the listOf() utility method to create a list containing a single item: the token assigned to a query parameter named user_token.
Because the httpGet() method runs asynchronously, you must call the responseString() method in order to handle its return value. The following code shows you how:
serverURL.httpGet(listOf("user_token" to token))
.responseString { request, response, result ->
// More code here
}
You can see that we now have access to a result object. In case of no errors, it will contain our server's response as a string.
Let's assume that our server returns the string "PASS" if the user passes the test, and "FAIL" otherwise. What you actually do when the user passes or fails the test is, of course, up to you. For now, I suggest you simply display appropriate Toast messages. The following code shows you how to do so concisely:
result.fold({ data ->
if(data.contains("PASS"))
Toast.makeText(baseContext,
"You seem to be a human.",
Toast.LENGTH_LONG).show()
else
Toast.makeText(baseContext,
"You seem to be a bot!",
Toast.LENGTH_LONG).show()
}, { error ->
Log.d("ERROR", "Error connecting to the server")
})
At this point, the app is ready. You can go ahead and deploy it to your emulator or device.
5. Creating the Server
We made a lot of assumptions about our web server in earlier steps. It's now time to create it, making sure that it doesn't deviate from those assumptions.
A quick and easy way to create a fully functional web server is to use the Node.js platform and the Express.js framework. To create a new Node.js project, make a new directory on your computer and run the npm init command inside it.
mkdir my_web_server
cd my_web_server ; npm init -y
To add the Express framework to the project, you can use the npm install command.
npm install --save express
Additionally, we'll be needing the Request package to communicate with the reCAPTCHA service. Therefore, install it as another dependency.
npm install --save request
You can now use your favorite code editor to create a new file called index.js and start writing all the required server-side code.
Start by loading both the express and request modules using the require() function and creating a new Express application by calling the express() function.
Our Express application must have an endpoint called validate, which can be accessed using the HTTP GET method. Therefore, create a new route for it using the get() method:
myApp.get('/validate', function(req, resp) {
// More code here
});
To validate the token generated by the Android app, you must now make a POST request to the reCAPTCHA service. The request must contain your secret key and the token itself. The following code shows you how to build the POST request's body by extracting the token from the query string:
To actually make the POST request, you can call the post() method of the request module. Its response is a short JSON document containing a key called success. As you might expect, its value is true only if the user has passed the test.
The following code shows you how to parse the JSON document, extract the success key, and generate the "PASS" and "FAIL" responses our Android app needs:
request.post({
url: 'https://www.google.com/recaptcha/api/siteverify',
form: postData
}, function(error, response, body) {
jsonData = JSON.parse(body); // Parse the JSON document
if(jsonData.success) { // User passed the test
resp.send('PASS');
} else { // User didn't pass the test
resp.send('FAIL');
}
});
Lastly, you must call the listen() method of the Express application object to allow it to listen for connections.
myApp.listen(8000);
At this point our web server is ready. To start it, return to the terminal and run the following command:
node index.js
If you run your Android app now, press the button, and successfully solve a CAPTCHA, you should see a Toast message telling you that you are human.
Conclusion
You now know how to use the SafetyNet reCAPTCHA API to secure your Android app and back-end infrastructure against bots. You don't have to worry about automated signups, screen scrapers, or bot-generated spam any more.
In this post we'll build a simple game from scratch. Along the way, we'll touch on some of the most important aspects of the SpriteKit library.
This post builds on what we've learned earlier in the SpriteKit Basics series. If you want to refresh your SpriteKit knowledge, take a look at some of my other posts.
Open Xcode and start a new project from the menu File> New > Project. Make sure iOS is selected and choose Game as your template.
Give your project a name, and make sure that Language is set to Swift,Game Technology is set to SpriteKit, and Devices is set to iPad.
Planning the Game Scenes
One of the first things I like to do when creating a project is to determine how many scenes I will need for the project. I will usually have at least three scenes: an intro scene, a main game scene, and a scene to show high scores, etc.
For this example, we just need an intro and main gameplay scene since we won't be keeping track of lives, scores, etc. SpriteKit already comes with one scene when you create a new project, so we just need an intro scene.
From Xcode's menu, choose File> New> File. Make sure iOS is selected, and choose Cocoa Touch Class.
Name the class StartGameScene, and make sure that Subclass of is set to SKScene and Language is set to Swift.
Setting Up GameViewController
Open GameViewController.swift. Delete everything in that file and replace it with the following.
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = StartGameScene(size: view.bounds.size)
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = false
scene.scaleMode = .aspectFill
skView.presentScene(scene)
}
override var prefersStatusBarHidden: Bool {
return true
}
}
When you create a new project, GameViewController.swift is set up to load GameScene.sks from disk. GameScene.sks is used along with SpriteKit's built-in scene editor, which allows you to visually lay out your projects. We will not be using GameScene.sks, and will instead create everything from code, so here we initiate a new instance of StartGameScene and present it.
Create the Intro Scene
Add the following to the newly created StartGameScene.swift.
import UIKit
import SpriteKit
class StartGameScene: SKScene {
override func didMove(to view: SKView){
scene?.backgroundColor = .blue
let logo = SKSpriteNode(imageNamed: "bigplane")
logo.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(logo)
let newGameBtn = SKSpriteNode(imageNamed: "newgamebutton")
newGameBtn.position = CGPoint(x: size.width/2, y: size.height/2 - 350)
newGameBtn.name = "newgame"
addChild(newGameBtn)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let touchLocation = touch.location(in: self)
let touchedNode = self.atPoint(touchLocation)
if(touchedNode.name == "newgame"){
let newScene = GameScene(size: size)
newScene.scaleMode = scaleMode
view?.presentScene(newScene)
}
}}
This scene is pretty simple. In the didMove method, we add a logo and a button. Then, in touchesBegan, we detect touches on the new game button and respond by loading the main scene GameScene.
Planning Game Classes
The next thing I like to do when creating a new game is decide which classes I will need. I can tell right away that I will need a Player class and an Enemy class. Both of these classes will extend SKSpriteNode. I think for this project we will just create the player and enemy bullets right from within their respective classes. You could make separate player bullet and enemy bullet classes if you prefer, and I suggest you try to do that as an exercise on your own.
Lastly, there are the islands. These do not have any specific functionality but to move down the screen. In this case, since they're just decorations, I think it's also okay not to create a class, and instead just create them in the main GameScene.
Creating the Player Class
From Xcode's menu, choose File> New> File. Make sure iOS is selected and choose Cocoa Touch Class.
Make sure that Class is set to Player, Subclass of: is set to SKSpriteNode, and Language is set to Swift.
Now add the following to Player.swift.
import UIKit
import SpriteKit
class Player: SKSpriteNode {
private var canFire = true
private var invincible = false
private var lives:Int = 3 {
didSet {
if(lives < 0){
kill()
}else{
respawn()
}
}
}
init() {
let texture = SKTexture(imageNamed: "player")
super.init(texture: texture, color: .clear, size: texture.size())
self.physicsBody = SKPhysicsBody(texture: self.texture!,size:self.size)
self.physicsBody?.isDynamic = true
self.physicsBody?.categoryBitMask = PhysicsCategories.Player
self.physicsBody?.contactTestBitMask = PhysicsCategories.Enemy | PhysicsCategories.EnemyBullet
self.physicsBody?.collisionBitMask = PhysicsCategories.EdgeBody
self.physicsBody?.allowsRotation = false
generateBullets()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func die (){
if(invincible == false){
lives -= 1
}
}
func kill(){
let newScene = StartGameScene(size: self.scene!.size)
newScene.scaleMode = self.scene!.scaleMode
let doorsClose = SKTransition.doorsCloseVertical(withDuration: 2.0)
self.scene!.view?.presentScene(newScene, transition: doorsClose)
}
func respawn(){
invincible = true
let fadeOutAction = SKAction.fadeOut(withDuration: 0.4)
let fadeInAction = SKAction.fadeIn(withDuration: 0.4)
let fadeOutIn = SKAction.sequence([fadeOutAction,fadeInAction])
let fadeOutInAction = SKAction.repeat(fadeOutIn, count: 5)
let setInvicibleFalse = SKAction.run {
self.invincible = false
}
run(SKAction.sequence([fadeOutInAction,setInvicibleFalse]))
}
func generateBullets(){
let fireBulletAction = SKAction.run{ [weak self] in
self?.fireBullet()
}
let waitToFire = SKAction.wait(forDuration: 0.8)
let fireBulletSequence = SKAction.sequence([fireBulletAction,waitToFire])
let fire = SKAction.repeatForever(fireBulletSequence)
run(fire)
}
func fireBullet(){
let bullet = SKSpriteNode(imageNamed: "bullet")
bullet.position.x = self.position.x
bullet.position.y = self.position.y + self.size.height/2
bullet.physicsBody = SKPhysicsBody(rectangleOf: bullet.size)
bullet.physicsBody?.categoryBitMask = PhysicsCategories.PlayerBullet
bullet.physicsBody?.allowsRotation = false
scene?.addChild(bullet)
let moveBulletAction = SKAction.move(to: CGPoint(x:self.position.x,y:(scene?.size.height)! + bullet.size.height), duration: 1.0)
let removeBulletAction = SKAction.removeFromParent()
bullet.run(SKAction.sequence([moveBulletAction,removeBulletAction]))
}
}
Within the init() method, we set up the physicsBody and invoke generateBullets(). The generateBullets method repeatedly calls fireBullet(), which creates a bullet, sets its physicsBody, and moves it down the screen.
When the player loses a life, the respawn() method is invoked. Within the respawn method, we fade the plane in and out five times, during which time the player will be invincible. One the player has exhausted all the lives, the kill() method is invoked. The kill method simply loads the StartGameScene.
Creating the Enemy Class
Choose File> New> File from Xcode's menu. Make sure iOS is selected and choose Cocoa Touch Class.
Make sure that Class is set to Enemy, Subclass of: is set to SKSpriteNode, and Language is set to Swift.
This class is pretty similar to the Player class. We set its physicsBody and invoke generateBullets(). The move() simply moves the enemy down the screen.
Creating the Main Game Scene
Delete everything within GameScene.swift and add the following.
We create an instance of Player and an instance of CMMotionManager. We are using the accelerometer to move the player in this game.
Within the didMove(to:) method we turn off the gravity, set up the contactDelegate, add an edge loop, and set the player's position before adding it to the scene. We then invoke setupAccelerometer(), which sets up the accelerometer, and invoke the addEnemies() and generateIslands() methods.
The addEnemies() method repeatedly calls the generateEnemy() method, which will create an instance of Enemy and add it to the scene.
The generateIslands() method works similarly to the addEnemies() method in that it repeatedly calls createIsland() which creates an SKSpriteNode and adds it to the scene. Within createIsland(), we also create an SKAction that moves the island down the scene.
Within the didBegin(_:) method, we check to see which nodes are making contact and respond by removing the appropriate node from the scene and invoking player.die() if necessary. The createExplosion() method creates an explosion animation and adds it to the scene. Once the explosion is finished, it is removed from the scene.
Conclusion
During this series, we learned some of the most important concepts used in almost all SpriteKit games. We ended the series by showing how simple it is to get a basic game up and running. There are still some improvements that could be made, like a HUB, high scores, and sounds (I included a couple of MP3s you can use for this in the repo). I hope you learned something useful throughout this series, and thanks for reading!
If you want to learn more about game programming with SpriteKit, check out one of our comprehensive video courses! You'll learn how to build a SpriteKit game from A to Z.
In this post we'll build a simple game from scratch. Along the way, we'll touch on some of the most important aspects of the SpriteKit library.
This post builds on what we've learned earlier in the SpriteKit Basics series. If you want to refresh your SpriteKit knowledge, take a look at some of my other posts.
Open Xcode and start a new project from the menu File> New > Project. Make sure iOS is selected and choose Game as your template.
Give your project a name, and make sure that Language is set to Swift,Game Technology is set to SpriteKit, and Devices is set to iPad.
Planning the Game Scenes
One of the first things I like to do when creating a project is to determine how many scenes I will need for the project. I will usually have at least three scenes: an intro scene, a main game scene, and a scene to show high scores, etc.
For this example, we just need an intro and main gameplay scene since we won't be keeping track of lives, scores, etc. SpriteKit already comes with one scene when you create a new project, so we just need an intro scene.
From Xcode's menu, choose File> New> File. Make sure iOS is selected, and choose Cocoa Touch Class.
Name the class StartGameScene, and make sure that Subclass of is set to SKScene and Language is set to Swift.
Setting Up GameViewController
Open GameViewController.swift. Delete everything in that file and replace it with the following.
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = StartGameScene(size: view.bounds.size)
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = false
scene.scaleMode = .aspectFill
skView.presentScene(scene)
}
override var prefersStatusBarHidden: Bool {
return true
}
}
When you create a new project, GameViewController.swift is set up to load GameScene.sks from disk. GameScene.sks is used along with SpriteKit's built-in scene editor, which allows you to visually lay out your projects. We will not be using GameScene.sks, and will instead create everything from code, so here we initiate a new instance of StartGameScene and present it.
Create the Intro Scene
Add the following to the newly created StartGameScene.swift.
import UIKit
import SpriteKit
class StartGameScene: SKScene {
override func didMove(to view: SKView){
scene?.backgroundColor = .blue
let logo = SKSpriteNode(imageNamed: "bigplane")
logo.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(logo)
let newGameBtn = SKSpriteNode(imageNamed: "newgamebutton")
newGameBtn.position = CGPoint(x: size.width/2, y: size.height/2 - 350)
newGameBtn.name = "newgame"
addChild(newGameBtn)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let touchLocation = touch.location(in: self)
let touchedNode = self.atPoint(touchLocation)
if(touchedNode.name == "newgame"){
let newScene = GameScene(size: size)
newScene.scaleMode = scaleMode
view?.presentScene(newScene)
}
}}
This scene is pretty simple. In the didMove method, we add a logo and a button. Then, in touchesBegan, we detect touches on the new game button and respond by loading the main scene GameScene.
Planning Game Classes
The next thing I like to do when creating a new game is decide which classes I will need. I can tell right away that I will need a Player class and an Enemy class. Both of these classes will extend SKSpriteNode. I think for this project we will just create the player and enemy bullets right from within their respective classes. You could make separate player bullet and enemy bullet classes if you prefer, and I suggest you try to do that as an exercise on your own.
Lastly, there are the islands. These do not have any specific functionality but to move down the screen. In this case, since they're just decorations, I think it's also okay not to create a class, and instead just create them in the main GameScene.
Creating the Player Class
From Xcode's menu, choose File> New> File. Make sure iOS is selected and choose Cocoa Touch Class.
Make sure that Class is set to Player, Subclass of: is set to SKSpriteNode, and Language is set to Swift.
Now add the following to Player.swift.
import UIKit
import SpriteKit
class Player: SKSpriteNode {
private var canFire = true
private var invincible = false
private var lives:Int = 3 {
didSet {
if(lives < 0){
kill()
}else{
respawn()
}
}
}
init() {
let texture = SKTexture(imageNamed: "player")
super.init(texture: texture, color: .clear, size: texture.size())
self.physicsBody = SKPhysicsBody(texture: self.texture!,size:self.size)
self.physicsBody?.isDynamic = true
self.physicsBody?.categoryBitMask = PhysicsCategories.Player
self.physicsBody?.contactTestBitMask = PhysicsCategories.Enemy | PhysicsCategories.EnemyBullet
self.physicsBody?.collisionBitMask = PhysicsCategories.EdgeBody
self.physicsBody?.allowsRotation = false
generateBullets()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func die (){
if(invincible == false){
lives -= 1
}
}
func kill(){
let newScene = StartGameScene(size: self.scene!.size)
newScene.scaleMode = self.scene!.scaleMode
let doorsClose = SKTransition.doorsCloseVertical(withDuration: 2.0)
self.scene!.view?.presentScene(newScene, transition: doorsClose)
}
func respawn(){
invincible = true
let fadeOutAction = SKAction.fadeOut(withDuration: 0.4)
let fadeInAction = SKAction.fadeIn(withDuration: 0.4)
let fadeOutIn = SKAction.sequence([fadeOutAction,fadeInAction])
let fadeOutInAction = SKAction.repeat(fadeOutIn, count: 5)
let setInvicibleFalse = SKAction.run {
self.invincible = false
}
run(SKAction.sequence([fadeOutInAction,setInvicibleFalse]))
}
func generateBullets(){
let fireBulletAction = SKAction.run{ [weak self] in
self?.fireBullet()
}
let waitToFire = SKAction.wait(forDuration: 0.8)
let fireBulletSequence = SKAction.sequence([fireBulletAction,waitToFire])
let fire = SKAction.repeatForever(fireBulletSequence)
run(fire)
}
func fireBullet(){
let bullet = SKSpriteNode(imageNamed: "bullet")
bullet.position.x = self.position.x
bullet.position.y = self.position.y + self.size.height/2
bullet.physicsBody = SKPhysicsBody(rectangleOf: bullet.size)
bullet.physicsBody?.categoryBitMask = PhysicsCategories.PlayerBullet
bullet.physicsBody?.allowsRotation = false
scene?.addChild(bullet)
let moveBulletAction = SKAction.move(to: CGPoint(x:self.position.x,y:(scene?.size.height)! + bullet.size.height), duration: 1.0)
let removeBulletAction = SKAction.removeFromParent()
bullet.run(SKAction.sequence([moveBulletAction,removeBulletAction]))
}
}
Within the init() method, we set up the physicsBody and invoke generateBullets(). The generateBullets method repeatedly calls fireBullet(), which creates a bullet, sets its physicsBody, and moves it down the screen.
When the player loses a life, the respawn() method is invoked. Within the respawn method, we fade the plane in and out five times, during which time the player will be invincible. One the player has exhausted all the lives, the kill() method is invoked. The kill method simply loads the StartGameScene.
Creating the Enemy Class
Choose File> New> File from Xcode's menu. Make sure iOS is selected and choose Cocoa Touch Class.
Make sure that Class is set to Enemy, Subclass of: is set to SKSpriteNode, and Language is set to Swift.
This class is pretty similar to the Player class. We set its physicsBody and invoke generateBullets(). The move() simply moves the enemy down the screen.
Creating the Main Game Scene
Delete everything within GameScene.swift and add the following.
We create an instance of Player and an instance of CMMotionManager. We are using the accelerometer to move the player in this game.
Within the didMove(to:) method we turn off the gravity, set up the contactDelegate, add an edge loop, and set the player's position before adding it to the scene. We then invoke setupAccelerometer(), which sets up the accelerometer, and invoke the addEnemies() and generateIslands() methods.
The addEnemies() method repeatedly calls the generateEnemy() method, which will create an instance of Enemy and add it to the scene.
The generateIslands() method works similarly to the addEnemies() method in that it repeatedly calls createIsland() which creates an SKSpriteNode and adds it to the scene. Within createIsland(), we also create an SKAction that moves the island down the scene.
Within the didBegin(_:) method, we check to see which nodes are making contact and respond by removing the appropriate node from the scene and invoking player.die() if necessary. The createExplosion() method creates an explosion animation and adds it to the scene. Once the explosion is finished, it is removed from the scene.
Conclusion
During this series, we learned some of the most important concepts used in almost all SpriteKit games. We ended the series by showing how simple it is to get a basic game up and running. There are still some improvements that could be made, like a HUB, high scores, and sounds (I included a couple of MP3s you can use for this in the repo). I hope you learned something useful throughout this series, and thanks for reading!
If you want to learn more about game programming with SpriteKit, check out one of our comprehensive video courses! You'll learn how to build a SpriteKit game from A to Z.
In this tutorial, you'll learn about the cool new SMS token feature in Android O. You'll learn how to generate an app-specific token that will fire up a pending intent when the device first receives a message containing that token so as to verify the phone number.
Kindly note that as of this writing, the Android O APIs are still in their third developer preview, though they are final. (We still don't know what O stands for yet!)
What Is an SMS Token?
An SMS token or one-time password is a security mechanism used to authenticate or verify a user. The user enters their phone number, and a limited lifespan token is generated specifically for that user. The user then receives the token as an SMS to their phone. In the case of Android O as of this writing, this app-specific token does not expire, but instead becomes invalid when another is generated.
Why Use Android O's SMS Token?
One of the major reasons you might consider using Android O's SMS token mechanism is that it improves the user experience of the app. The user does not need to copy and paste the token from the SMS client to be verified. Instead, the Android device automatically detects the token sent to the user's device and then triggers the app component in the intent associated with your app (we'll get to that shortly).
Even better, this functionality doesn't require the READ_SMS permission or any other. This mechanism also improves the security of your app user, because no other app can read the message containing the token on the device.
In this tutorial, you'll learn how to use this new feature in Android O's SMS API. You'll learn how to generate an SMS token specifically for your app and send it to a device. We'll use the Android Studio emulator to simulate this process.
Prerequisites
To follow along with this tutorial, make sure you have downloaded the Android 8.0 (O) SDK platform on your computer and have an emulator already set up that targets this version.
1. Generate the App-Specific Token
To start off, I'll show you how to generate an app-specific token which is unique to your app on the user's device.
Create a New Android Studio Project
Fire up Android Studio and create a new project with an empty activity called MainActivity.
Modify the build.gradle File
Make the following changes to your app module's build.gradle file.
In the code snippet below, we get the SMSManager class and then call the method createAppSpecificSmsToken(). This does just what it says—it creates the app-specific SMS token. This method requires a PendingIntent which contains the Activity to be fired up when an SMS containing this token (a string 11 characters long) is received by the device.
Be aware that, as stated earlier, the generated token is unique to your app on the user's device. If you create another SMS token, the second one will be a valid token while the first one will be ignored.
Lay Out the Screen
Here's a MainActivity layout file set up to display the SMS token that was generated:
Running the app at this point will show the SMS token generated.
2. Receive the SMS Token
Next, we'll create the activity to be fired up when our device receives a message containing the SMS token. Nothing specific to SMS tokens happens here.
import android.app.Activity;
import android.os.Bundle;
public class SmsTokenResultVerificationActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_token_result);
}
}
Lay Out the Screen
Here we create the layout for the activity we created above that contains just one TextView.
Next, we'll test this functionality using the Android Studio emulator.
3. Test the SMS Token
Set Up the Emulator to Send SMS Messages
You can use your emulator to simulate receiving an SMS message, but you'll need to do a little setup. Open your emulator, click the last button on the right-side navigation bar to open the extended control dialog, and then select the phone control button.
From this interface, you can simulate your device receiving a phone call or SMS from another phone.
Send the Token
Make sure you have set up your emulator that targets Android 8.0 (O). Generate a token and enter a text message that contains it. Then click the Send Message button.
Finally, the activity we specified in the pending intent gets fired up immediately! Try sending the message again and see that this time, it will show up in the device SMS client instead, because it is no longer a valid token.
Using a Server
For a production app, the SMS token will typically be sent by a back-end server. So when using a server, the client (your app) should make a request to the server, including the app generated token and the phone number. Your server will then receive this request and send the unmodified token back as a text message to the user's phone. Your app will then receive this token and fire up the component registered in the pending intent. That component can then let the server know that the phone number verification or user authentication succeeded.
Conclusion
In this tutorial, you learned about the awesome SMS token feature introduced in Android O: what is it, its benefits, and how to use it in an Android app.
To learn more about Android SMS and phone APIs, including how to make calls from your app, check out my related tutorial here on Envato Tuts+.
In this tutorial, you'll learn about the cool new SMS token feature in Android O. You'll learn how to generate an app-specific token that will fire up a pending intent when the device first receives a message containing that token so as to verify the phone number.
Kindly note that as of this writing, the Android O APIs are still in their third developer preview, though they are final. (We still don't know what O stands for yet!)
What Is an SMS Token?
An SMS token or one-time password is a security mechanism used to authenticate or verify a user. The user enters their phone number, and a limited lifespan token is generated specifically for that user. The user then receives the token as an SMS to their phone. In the case of Android O as of this writing, this app-specific token does not expire, but instead becomes invalid when another is generated.
Why Use Android O's SMS Token?
One of the major reasons you might consider using Android O's SMS token mechanism is that it improves the user experience of the app. The user does not need to copy and paste the token from the SMS client to be verified. Instead, the Android device automatically detects the token sent to the user's device and then triggers the app component in the intent associated with your app (we'll get to that shortly).
Even better, this functionality doesn't require the READ_SMS permission or any other. This mechanism also improves the security of your app user, because no other app can read the message containing the token on the device.
In this tutorial, you'll learn how to use this new feature in Android O's SMS API. You'll learn how to generate an SMS token specifically for your app and send it to a device. We'll use the Android Studio emulator to simulate this process.
Prerequisites
To follow along with this tutorial, make sure you have downloaded the Android 8.0 (O) SDK platform on your computer and have an emulator already set up that targets this version.
1. Generate the App-Specific Token
To start off, I'll show you how to generate an app-specific token which is unique to your app on the user's device.
Create a New Android Studio Project
Fire up Android Studio and create a new project with an empty activity called MainActivity.
Modify the build.gradle File
Make the following changes to your app module's build.gradle file.
In the code snippet below, we get the SMSManager class and then call the method createAppSpecificSmsToken(). This does just what it says—it creates the app-specific SMS token. This method requires a PendingIntent which contains the Activity to be fired up when an SMS containing this token (a string 11 characters long) is received by the device.
Be aware that, as stated earlier, the generated token is unique to your app on the user's device. If you create another SMS token, the second one will be a valid token while the first one will be ignored.
Lay Out the Screen
Here's a MainActivity layout file set up to display the SMS token that was generated:
Running the app at this point will show the SMS token generated.
2. Receive the SMS Token
Next, we'll create the activity to be fired up when our device receives a message containing the SMS token. Nothing specific to SMS tokens happens here.
import android.app.Activity;
import android.os.Bundle;
public class SmsTokenResultVerificationActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_token_result);
}
}
Lay Out the Screen
Here we create the layout for the activity we created above that contains just one TextView.
Next, we'll test this functionality using the Android Studio emulator.
3. Test the SMS Token
Set Up the Emulator to Send SMS Messages
You can use your emulator to simulate receiving an SMS message, but you'll need to do a little setup. Open your emulator, click the last button on the right-side navigation bar to open the extended control dialog, and then select the phone control button.
From this interface, you can simulate your device receiving a phone call or SMS from another phone.
Send the Token
Make sure you have set up your emulator that targets Android 8.0 (O). Generate a token and enter a text message that contains it. Then click the Send Message button.
Finally, the activity we specified in the pending intent gets fired up immediately! Try sending the message again and see that this time, it will show up in the device SMS client instead, because it is no longer a valid token.
Using a Server
For a production app, the SMS token will typically be sent by a back-end server. So when using a server, the client (your app) should make a request to the server, including the app generated token and the phone number. Your server will then receive this request and send the unmodified token back as a text message to the user's phone. Your app will then receive this token and fire up the component registered in the pending intent. That component can then let the server know that the phone number verification or user authentication succeeded.
Conclusion
In this tutorial, you learned about the awesome SMS token feature introduced in Android O: what is it, its benefits, and how to use it in an Android app.
To learn more about Android SMS and phone APIs, including how to make calls from your app, check out my related tutorial here on Envato Tuts+.
The Singleton Pattern is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class. Anytime multiple classes or clients request for that class, they get the same instance of the class. This Singleton class may be responsible for instantiating itself, or you can delegate the object creation to a factory class.
Let's use the example of a cellphone and its owner. A phone is typically owned by a single person, while a person can own many phones. Anytime one of these phones rings, the same owner picks it up.
Benefits of the Singleton Pattern
In a typical Android app, there are many objects for which we only need one global instance, whether you are using it directly or simply passing it to another class. Examples include caches, OkHttpClient, HttpLoggingInterceptor, Retrofit, Gson, SharedPreferences, the repository class, etc. If we were to instantiate more than one of these types of objects, we'd run into problems like incorrect app behaviour, resource overuse, and other confusing results.
Implementation
It's quite easy to implement this pattern. The following code snippet shows how a Singleton is created.
public class Singleton {
private static Singleton INSTANCE = null;
// other instance variables can be here
private Singleton() {};
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
// other instance methods can follow
}
In the code above, we have a static variable INSTANCE to hold an instance of the class. We also made the constructor private because we want to enforce noninstantiability—the class can only instantiate itself. The method getInstance() guarantees that the class is instantiated, if it has not been, and that it's returned to the caller.
Example: Creating a Single Instance of Retrofit
Retrofit is a popular library to connect a REST web service by translating the API into Java interfaces. To learn more about it, check out my tutorial here on Envato Tuts+.
In an Android app, you'll need a single global instance of a Retrofit object so that other parts of an app such as a UserProfileActivity or SettingsActivity can use it to execute a network request without the need to create an instance every single time we need it. Creating multiple instances would pollute our app with unused retrofit objects, thereby occupying unnecessary memory on an already memory-constrained mobile device.
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
So anytime client A calls RetrofitClient.getClient(), it creates the instance if it has not been created already, and then when client B calls this method, it checks if the Retrofit instance already exists. If so, it returns the instance to client B instead of creating a new one.
Dealing With Multithreading
In the Android system, you can spin off multiple threads to perform different tasks. These threads can end up executing the same code block simultaneously. In the case of the Singleton class above, this could lead to the creation of multiple object instances, which violates the contract of a Singleton. So our Singleton code snippet method getInstance() is not thread safe. We'll now look at ways to make it thread safe.
Synchronize the getInstance() Method
One of the ways to make the singleton code thread safe is by making the method getInstance() asynchronized one. Doing this only allows one thread to run the method at a time, forcing every other thread to be in a wait or blocked state.
public class Singleton {
private static Singleton INSTANCE = null;
// other instance variables can be here
private Singleton() {};
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
// other instance methods can follow
}
This approach makes our code thread safe, but it is an expensive operation. In other words, this can slow down performance. So you have to investigate and see if the performance cost is worthwhile in your application.
Eagerly Create an Instance
Another approach to deal with multiple threads accessing the singleton is to create the Singleton instance immediately when the class is loaded or initialized (by the Android ClassLoader in the Dalvik VM). This makes the code thread safe. Then the object instance will already be available before any thread accesses the INSTANCE variable.
public class Singleton {
private static Singleton INSTANCE = new Singleton();
// other instance variables can be here
private Singleton() {};
public static Singleton getInstance() {
return(INSTANCE);
}
// other instance methods can follow
}
A drawback to this approach is that you can end up creating an object that might never be used, thereby occupying unnecessary memory. So this approach should typically only be used if you are sure that the singleton will be accessed.
Bonus: Using Dagger 2
A dependency injection library such as Dagger can help you wire up your object dependencies and create singletons by using the @Singleton annotation. This will ensure that the object is only initialized once throughout the application lifecycle.
@Module
public class NetworkModule {
@Provides
@Singleton
public Gson gson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
@Provides
@Singleton
public HttpLoggingInterceptor loggingInterceptor() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(
message -> Timber.i(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return interceptor;
}
@Provides
@Singleton
public Cache cache(File cacheFile) {
return new Cache(cacheFile, 10 * 1000 * 1000); //10MB Cache
}
@Provides
@Singleton
public File cacheFile(@ApplicationContext Context context) {
return new File(context.getCacheDir(), "okhttp_cache");
}
@Provides
@Singleton
public OkHttpClient okHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache) {
return new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.cache(cache)
.build();
}
@Provides
@Singleton
public Retrofit retrofit(OkHttpClient okHttpClient, Gson gson) {
return new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.baseUrl("you/base/url")
.build();
}
}
In the code above, we create a single instance of Gson, Cache, File, OkHttpClient and finally Retrofit types to be provided from the dependency graph generated by Dagger.
To learn more about Dagger 2, check out our tutorial here on Envato Tuts+.
In this short tutorial, you learned about the Singleton pattern in Android: what it is, the benefits of using it, how to implement it by writing your own, and some ways of dealing with multiple threads. I also showed you how to use a third-party library such as Dagger 2.
In the meantime, check out some of our other courses and tutorials on the Java language and Android app development!
The Singleton Pattern is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class. Anytime multiple classes or clients request for that class, they get the same instance of the class. This Singleton class may be responsible for instantiating itself, or you can delegate the object creation to a factory class.
Let's use the example of a cellphone and its owner. A phone is typically owned by a single person, while a person can own many phones. Anytime one of these phones rings, the same owner picks it up.
Benefits of the Singleton Pattern
In a typical Android app, there are many objects for which we only need one global instance, whether you are using it directly or simply passing it to another class. Examples include caches, OkHttpClient, HttpLoggingInterceptor, Retrofit, Gson, SharedPreferences, the repository class, etc. If we were to instantiate more than one of these types of objects, we'd run into problems like incorrect app behaviour, resource overuse, and other confusing results.
Implementation
It's quite easy to implement this pattern. The following code snippet shows how a Singleton is created.
public class Singleton {
private static Singleton INSTANCE = null;
// other instance variables can be here
private Singleton() {};
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
// other instance methods can follow
}
In the code above, we have a static variable INSTANCE to hold an instance of the class. We also made the constructor private because we want to enforce noninstantiability—the class can only instantiate itself. The method getInstance() guarantees that the class is instantiated, if it has not been, and that it's returned to the caller.
Example: Creating a Single Instance of Retrofit
Retrofit is a popular library to connect a REST web service by translating the API into Java interfaces. To learn more about it, check out my tutorial here on Envato Tuts+.
In an Android app, you'll need a single global instance of a Retrofit object so that other parts of an app such as a UserProfileActivity or SettingsActivity can use it to execute a network request without the need to create an instance every single time we need it. Creating multiple instances would pollute our app with unused retrofit objects, thereby occupying unnecessary memory on an already memory-constrained mobile device.
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
So anytime client A calls RetrofitClient.getClient(), it creates the instance if it has not been created already, and then when client B calls this method, it checks if the Retrofit instance already exists. If so, it returns the instance to client B instead of creating a new one.
Dealing With Multithreading
In the Android system, you can spin off multiple threads to perform different tasks. These threads can end up executing the same code block simultaneously. In the case of the Singleton class above, this could lead to the creation of multiple object instances, which violates the contract of a Singleton. So our Singleton code snippet method getInstance() is not thread safe. We'll now look at ways to make it thread safe.
Synchronize the getInstance() Method
One of the ways to make the singleton code thread safe is by making the method getInstance() asynchronized one. Doing this only allows one thread to run the method at a time, forcing every other thread to be in a wait or blocked state.
public class Singleton {
private static Singleton INSTANCE = null;
// other instance variables can be here
private Singleton() {};
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
// other instance methods can follow
}
This approach makes our code thread safe, but it is an expensive operation. In other words, this can slow down performance. So you have to investigate and see if the performance cost is worthwhile in your application.
Eagerly Create an Instance
Another approach to deal with multiple threads accessing the singleton is to create the Singleton instance immediately when the class is loaded or initialized (by the Android ClassLoader in the Dalvik VM). This makes the code thread safe. Then the object instance will already be available before any thread accesses the INSTANCE variable.
public class Singleton {
private static Singleton INSTANCE = new Singleton();
// other instance variables can be here
private Singleton() {};
public static Singleton getInstance() {
return(INSTANCE);
}
// other instance methods can follow
}
A drawback to this approach is that you can end up creating an object that might never be used, thereby occupying unnecessary memory. So this approach should typically only be used if you are sure that the singleton will be accessed.
Bonus: Using Dagger 2
A dependency injection library such as Dagger can help you wire up your object dependencies and create singletons by using the @Singleton annotation. This will ensure that the object is only initialized once throughout the application lifecycle.
@Module
public class NetworkModule {
@Provides
@Singleton
public Gson gson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
@Provides
@Singleton
public HttpLoggingInterceptor loggingInterceptor() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(
message -> Timber.i(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return interceptor;
}
@Provides
@Singleton
public Cache cache(File cacheFile) {
return new Cache(cacheFile, 10 * 1000 * 1000); //10MB Cache
}
@Provides
@Singleton
public File cacheFile(@ApplicationContext Context context) {
return new File(context.getCacheDir(), "okhttp_cache");
}
@Provides
@Singleton
public OkHttpClient okHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache) {
return new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.cache(cache)
.build();
}
@Provides
@Singleton
public Retrofit retrofit(OkHttpClient okHttpClient, Gson gson) {
return new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.baseUrl("you/base/url")
.build();
}
}
In the code above, we create a single instance of Gson, Cache, File, OkHttpClient and finally Retrofit types to be provided from the dependency graph generated by Dagger.
To learn more about Dagger 2, check out our tutorial here on Envato Tuts+.
In this short tutorial, you learned about the Singleton pattern in Android: what it is, the benefits of using it, how to implement it by writing your own, and some ways of dealing with multiple threads. I also showed you how to use a third-party library such as Dagger 2.
In the meantime, check out some of our other courses and tutorials on the Java language and Android app development!
In early 2011, a natural language understanding computer system called IBM Watson was able to beat all human contestants in a quiz-like game show called Jeopardy! It was an historic event and was perhaps the point when the general public started to realize that artificial intelligence was no longer the stuff of science fiction.
Back then, Watson ran on a supercomputer and could do little more than answer trivia questions. Today, however, it has been transformed into a far more versatile system, and a lot of its capabilities are available over the cloud.
In this series of tutorials, I'll show you how to use various services offered by the IBM Watson Developer Cloud in Android apps. In this introductory tutorial, you'll learn how to work with IBM Bluemix, the Watson Java SDK, and the Watson tone analyzer service to create a simple Android app that can identify the emotions present in any piece of text.
and a device or emulator running Android 4.4 or higher
1. Creating a Watson Service
Watson's services can be accessed only through the IBM Bluemix cloud platform. That means you can use them in your application only after you've enabled them in the Bluemix console and acquired the required credentials.
Start by logging in to the console and navigating to Services > Watson.
Next, press the Create Watson service button to see all the Watson services that are available to you.
For now, because we're interested only in analyzing the emotional tone in written text, select the Tone Analyzer service.
On the next screen, change the name of the service to something meaningful and press the Create button.
The tone analyzer service will now be activated for your account, and a set of login credentials will be generated. To see what those credentials are, open the Service credentials tab and select the View credentials action.
Save the contents of the JSON document to a file on your computer. I suggest you name the file credentials.json.
2. Project Setup
The Watson Java SDK makes it very easy for you to communicate with any Watson service. To be able to use it in your project, add it as a compile dependency in the app module's build.gradle file.
For this tutorial, you'll be needing two more libraries: Commons IO, to simplify file IO operations, and Android Design Support, to be able to use a few Material Design widgets. Add them too as compile dependencies.
Finally, press the Sync Now button to complete the project configuration.
3. Initializing the Tone Analyzer
To communicate with Watson's tone analyzer service, you must use the ToneAnalyzer class. Its constructor expects a date string as its argument, which it will use to automatically determine the version of the tone analyzer service to use.
final ToneAnalyzer toneAnalyzer =
new ToneAnalyzer("2017-07-01");
Note that the date should always be a static string. This helps make sure that your app doesn't stop working when a new version of the service introduces breaking changes.
The ToneAnalyzer instance must be configured to use your credentials, so move the credentials.json file, the one you created earlier in this tutorial, to your project's res/raw folder.
Next, you must extract the values of the username and password keys from the JSON file. The following code shows you how to do so quickly using the IOUtils and JSONObject classes:
JSONObject credentials = new JSONObject(IOUtils.toString(
getResources().openRawResource(R.raw.credentials), "UTF-8"
)); // Convert the file into a JSON object
// Extract the two values
String username = credentials.getString("username");
String password = credentials.getString("password");
You can now complete the configuration of the ToneAnalyzer instance by calling the setUsernameAndPassword() method.
Our app needs an interface that will allow the user to type in a few sentences and press a button to begin the tone analysis. In other words, you must now create a simple layout containing an EditText widget and a Button widget.
You can, optionally, also throw in a TextInputLayout container to make sure that the EditText widget conforms to the guidelines of Material Design.
Accordingly, add the following code to your activity's layout XML file:
The tone analysis must start as soon as the user presses the button. Therefore, you need to add an on-click event handler to the Button widget using its setOnClickListener() method. Before you do so, however, don't forget to get a reference to the widget using the findViewById() method.
Button analyzeButton = (Button)findViewById(R.id.analyze_button);
analyzeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// More code here
}
});
Inside the on-click event handler, the first thing you need to do is determine what the user has typed into the EditText widget using its getText() method.
EditText userInput = (EditText)findViewById(R.id.user_input);
final String textToAnalyze = userInput.getText().toString();
Like all Watson services, the tone analyzer service offers a lot of different features. For instance, it can identify emotions, language style, and social tendencies in its input. It can also work with JSON documents, plain text, and HTML. Therefore, to use it efficiently, you must explicitly specify the features you need using a ToneOptions object, which can be easily created using the ToneOptions.Builder class.
For now, we'll be using the service only to list all the emotions that are present in a plain text string. Here's how you create a ToneOptions object saying so:
ToneOptions options = new ToneOptions.Builder()
.addTone(Tone.EMOTION)
.html(false).build();
You can now compose a tone analysis request by calling the getTone() method, which expects a string containing the text to analyze and a ToneOptions object as its only arguments. To actually execute the request asynchronously, you must also call the enqueue() method, which takes a ServiceCallback instance as its argument.
toneAnalyzer.getTone(textToAnalyze, options).enqueue(
new ServiceCallback<ToneAnalysis>() {
@Override
public void onResponse(ToneAnalysis response) {
// More code here
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
}
});
Inside the onResponse() method of the ServiceCallback class, you have access to a ToneAnalysis object. By calling its getDocumentTone() method, you can determine the overall tone of the text you passed to the service.
The return value of the getDocumentTone() method is an ElementTone object containing a list of tone categories. Because we explicitly stated earlier that we're interested only in the emotions category, the list will contain only one element. Accordingly, here's how you extract the scores for all the emotions the service detected:
As you might expect, a ToneScore object represents a single emotion. It has a Double containing the actual score and a String telling you the name of the emotion. If the score is greater than 0.5, it means that there's a good chance the emotion is being expressed in the text.
Let us now pick only those emotions whose scores are greater than 0.5 and use them to create a message that can be displayed to the user using a Toast.
String detectedTones = "";
for(ToneScore score:scores) {
if(score.getScore() > 0.5f) {
detectedTones += score.getName() + " ";
}
}
final String toastMessage =
"The following emotions were detected:\n\n"
+ detectedTones.toUpperCase();
Because the onResponse() method runs on different thread, you must make sure you create and display the Toast only after calling the runOnUiThread() method.
The app is now ready. If you run it, type in a few sentences, and start the analysis, you'll be able to see Watson accurately identify the emotions present in your text.
Conclusion
In this tutorial, you created an Android app that can use IBM Watson's tone analyzer service to perform the complex task of guessing the emotions expressed in a piece of text. You also learned the basics of using the Watson Java SDK and the IBM Bluemix console.
In early 2011, a natural language understanding computer system called IBM Watson was able to beat all human contestants in a quiz-like game show called Jeopardy! It was an historic event and was perhaps the point when the general public started to realize that artificial intelligence was no longer the stuff of science fiction.
Back then, Watson ran on a supercomputer and could do little more than answer trivia questions. Today, however, it has been transformed into a far more versatile system, and a lot of its capabilities are available over the cloud.
In this series of tutorials, I'll show you how to use various services offered by the IBM Watson Developer Cloud in Android apps. In this introductory tutorial, you'll learn how to work with IBM Bluemix, the Watson Java SDK, and the Watson tone analyzer service to create a simple Android app that can identify the emotions present in any piece of text.
and a device or emulator running Android 4.4 or higher
1. Creating a Watson Service
Watson's services can be accessed only through the IBM Bluemix cloud platform. That means you can use them in your application only after you've enabled them in the Bluemix console and acquired the required credentials.
Start by logging in to the console and navigating to Services > Watson.
Next, press the Create Watson service button to see all the Watson services that are available to you.
For now, because we're interested only in analyzing the emotional tone in written text, select the Tone Analyzer service.
On the next screen, change the name of the service to something meaningful and press the Create button.
The tone analyzer service will now be activated for your account, and a set of login credentials will be generated. To see what those credentials are, open the Service credentials tab and select the View credentials action.
Save the contents of the JSON document to a file on your computer. I suggest you name the file credentials.json.
2. Project Setup
The Watson Java SDK makes it very easy for you to communicate with any Watson service. To be able to use it in your project, add it as a compile dependency in the app module's build.gradle file.
For this tutorial, you'll be needing two more libraries: Commons IO, to simplify file IO operations, and Android Design Support, to be able to use a few Material Design widgets. Add them too as compile dependencies.
Finally, press the Sync Now button to complete the project configuration.
3. Initializing the Tone Analyzer
To communicate with Watson's tone analyzer service, you must use the ToneAnalyzer class. Its constructor expects a date string as its argument, which it will use to automatically determine the version of the tone analyzer service to use.
final ToneAnalyzer toneAnalyzer =
new ToneAnalyzer("2017-07-01");
Note that the date should always be a static string. This helps make sure that your app doesn't stop working when a new version of the service introduces breaking changes.
The ToneAnalyzer instance must be configured to use your credentials, so move the credentials.json file, the one you created earlier in this tutorial, to your project's res/raw folder.
Next, you must extract the values of the username and password keys from the JSON file. The following code shows you how to do so quickly using the IOUtils and JSONObject classes:
JSONObject credentials = new JSONObject(IOUtils.toString(
getResources().openRawResource(R.raw.credentials), "UTF-8"
)); // Convert the file into a JSON object
// Extract the two values
String username = credentials.getString("username");
String password = credentials.getString("password");
You can now complete the configuration of the ToneAnalyzer instance by calling the setUsernameAndPassword() method.
Our app needs an interface that will allow the user to type in a few sentences and press a button to begin the tone analysis. In other words, you must now create a simple layout containing an EditText widget and a Button widget.
You can, optionally, also throw in a TextInputLayout container to make sure that the EditText widget conforms to the guidelines of Material Design.
Accordingly, add the following code to your activity's layout XML file:
The tone analysis must start as soon as the user presses the button. Therefore, you need to add an on-click event handler to the Button widget using its setOnClickListener() method. Before you do so, however, don't forget to get a reference to the widget using the findViewById() method.
Button analyzeButton = (Button)findViewById(R.id.analyze_button);
analyzeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// More code here
}
});
Inside the on-click event handler, the first thing you need to do is determine what the user has typed into the EditText widget using its getText() method.
EditText userInput = (EditText)findViewById(R.id.user_input);
final String textToAnalyze = userInput.getText().toString();
Like all Watson services, the tone analyzer service offers a lot of different features. For instance, it can identify emotions, language style, and social tendencies in its input. It can also work with JSON documents, plain text, and HTML. Therefore, to use it efficiently, you must explicitly specify the features you need using a ToneOptions object, which can be easily created using the ToneOptions.Builder class.
For now, we'll be using the service only to list all the emotions that are present in a plain text string. Here's how you create a ToneOptions object saying so:
ToneOptions options = new ToneOptions.Builder()
.addTone(Tone.EMOTION)
.html(false).build();
You can now compose a tone analysis request by calling the getTone() method, which expects a string containing the text to analyze and a ToneOptions object as its only arguments. To actually execute the request asynchronously, you must also call the enqueue() method, which takes a ServiceCallback instance as its argument.
toneAnalyzer.getTone(textToAnalyze, options).enqueue(
new ServiceCallback<ToneAnalysis>() {
@Override
public void onResponse(ToneAnalysis response) {
// More code here
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
}
});
Inside the onResponse() method of the ServiceCallback class, you have access to a ToneAnalysis object. By calling its getDocumentTone() method, you can determine the overall tone of the text you passed to the service.
The return value of the getDocumentTone() method is an ElementTone object containing a list of tone categories. Because we explicitly stated earlier that we're interested only in the emotions category, the list will contain only one element. Accordingly, here's how you extract the scores for all the emotions the service detected:
As you might expect, a ToneScore object represents a single emotion. It has a Double containing the actual score and a String telling you the name of the emotion. If the score is greater than 0.5, it means that there's a good chance the emotion is being expressed in the text.
Let us now pick only those emotions whose scores are greater than 0.5 and use them to create a message that can be displayed to the user using a Toast.
String detectedTones = "";
for(ToneScore score:scores) {
if(score.getScore() > 0.5f) {
detectedTones += score.getName() + " ";
}
}
final String toastMessage =
"The following emotions were detected:\n\n"
+ detectedTones.toUpperCase();
Because the onResponse() method runs on different thread, you must make sure you create and display the Toast only after calling the runOnUiThread() method.
The app is now ready. If you run it, type in a few sentences, and start the analysis, you'll be able to see Watson accurately identify the emotions present in your text.
Conclusion
In this tutorial, you created an Android app that can use IBM Watson's tone analyzer service to perform the complex task of guessing the emotions expressed in a piece of text. You also learned the basics of using the Watson Java SDK and the IBM Bluemix console.
Love using emojis? Now you can learn to make your own!
We all use emoticons/emojis
(emotion icons) in our messenger chats, apps, and online comments. Emojis are a very fun way to show our feelings without words. Though many apps offer free emoticons, you should not feel limited to only
those. Create your own!
Today you're going to learn, step by step, how to set up and design a small set of Khaleeji woman emojis. We’ll
work with basic Adobe Illustrator tools and shortcuts to create a female character with different expressions, and move on to using Xcode to export the images.
Common "beauty" features that Middle Eastern women are genetically blessed with, but not limited to, are:
full eyebrows
big kohl-contoured eyes, and curled lashes
olive complexions
plump lips
thick hair
Keep those in mind and sketch out a "non-emotional" female face, and add a hijab to make her look "Khaleeji" (from the Gulf).
Then use the same basic face sketch and multiply it, to illustrate nine different emotions you might share with friends and family, such as happy, in love, surprised, crying, and so forth.
Fundamentally, you can change expressions by just changing the eyebrows, eyes, and mouth of the initial sketch. Check out how I altered my emoji emotions.
Step 2
Set up a New Document (Command-N):
Number of Artboards: 1
Width: 618 px
Height: 618 px
Units: Pixels
Color Mode: RGB
Step 3
Use the Place shortcut (Command-Shift-P), and place the sketch. Then Lock (Command-2) the sketch down, so we can start tracing on top.
2. How to Trace the Initial Emoji Design
Step 1
Let's start tracing by drawing the eyes.
Select the Ellipse Tool (L), from the Tools panel.
Create the iris of the eye, a 60 x 60 px brown (#7C3722) fill circle, using the Ellipse Tool (L).
Draw the pupil of the eye, a 40 x 40 px brown (#351105) fill circle, and place it above the iris
Using the Ellipse Tool (L), create two eye reflection highlights: one rotated26 x 17 px and a14 x 14px (#FFFFFF) fill circle.
Then, with the Selection Tool (V), select all four ellipses and Group them together (Command-G).
Step 2
From the Tools panel, select the Pen Tool (P), and with a (#FFFFFF) white fill, draw in the "sclera"—the white of the eye.
Object> Arrange > Send Backward (Command-[), to position it behind the pupil shapes.
Then Copy (Command-C).
And Paste in Front (Command-F).
Object> Arrange > Bring Forward (Command-]), to position it in front of the pupil shapes.
What we need to do is create a clipping mask for the pupils.
With the Selection Tool (V), select the sclera + pupil group, Object > Clipping Mask> Make (Command-7).
Now the pupils are masked.
Step 3
Using the Pen Tool (P), draw in the upper/lower eyelids, eyeshadow, eyelashes, eyebrows, and cheek blush, with a black stroke and null fill.
Color fill:
Eyebrows #893A28
Eyeshadow & Lower Eyelid #CC6E4A
Eyelashes #000000
Eye Shading #B5D7EA
Cheeks Shading #FFB7A6
You will need to Align the shapes to the Front or Back.
To move above or below, Object >
Arrange > Bring to Front(Shift-Command-]) or Object > Arrange >
Send to Back(Shift-Command-[).
For just one step to back or front, Object > Arrange > Send Backward(Command-[) or Forward
(Command‑]). Object > Arrange > Bring Forward.
Step 4
Open the Transparency panel: Window > Transparency.
Select the light blue eye shade shape, and give it a Multiply: Blending Mode from Transparency panel.
Then select the cheek shape and give it a Multiply: Blending Mode, too.
Effect > Stylize > Feather: Radius:13px.
Step 5
Group all eye shapes together (Command-G).
We need to create symmetrical eyes. Use the Selection Tool (V), and select the eye group, cheek shade, and eyebrows. Take the Reflect Tool (O) and set the blue center reference point above the nose; Option-Shift-Drag and release to mirror into position.
Step 6
Let's illustrate the rest of the emoji features. Use the Pen Tool (P), and trace over the remaining parts of the sketch.
Then select each shape, give it a fill color of your choice, and arrange it in its proper order.
Remember, to move above or below, Object >
Arrange > Bring to Front(Shift-Command-]) or Object > Arrange >
Send to Back(Shift-Command-[), and just one step back or front, Object > Arrange > Send Backward(Command-[) or Forward
(Command‑]).
Step 7
Object > UnlockAll (Command-Alt-2), and delete the sketch. Tweak and clean up the artwork with the Direct Selection Tool (A).
Select the face shape, Object > Path > Offset Path: Offset - 4px
Then select and give the outer face shape a darker skin color.
Step 8
Select the hijab shape, Object > Path > Offset Path: Offset 5 px and give the new outer shape a black fill.
Now we have our initial emoji set up.
File > Save (Command-S).
Step 9
Our next step is to duplicate the artboard to maintain the basic emoji features. Go to Window > Artboards. Select the drop-down menu and Duplicate Artboards. Duplicate it nine times.
Then, from the Artboards panel's submenu, select Rearrange Artboards:
Layout: Grid by Row
Columns: 3
Spacing: 20 px
3. How to Illustrate Emotions
Step 1
Now that our artboards are set, we can start drawing in the emotions.
The first artboard emotion is: "Oh!"
Delete the lips and eyebrows.
Then, select the Pen Tool (P), and draw in the "O" lips and slanted eyebrows of the emotion :O
Select each new shape with the Selection Tool (V), and use the Eyedropper Tool (I) to select its corresponding partner, to give it the same color.
The eyebrow color I had wasn't strong enough in appearance, so replaced it with a darker color.
Select > Same > Fill Color and give them a fill color of #4F2018.
Use the Selection Tool (V) to move the small beauty spot closer to the lips, and you are done with the first emoji!
Step 2
Artboard 2: "Upset" emoji.
Delete the eyebrows and lips.
Draw a new expression with the Pen Tool (P), and match the colors with Eyedropper Tool (I).
Use the Selection Tool (V) to move the beauty spot closer to the lips.
Step 3
Artboard 3: "Angry" emoji.
First, select the eyebrows with the Selection Tool (V) and rotate them inwards to show anger. Then, draw angry lips and anger sparks with the Pen Tool (P), 1 pt, black stroke.
Finish off by matching colors with the Eyedropper Tool (I), and giving the sparks a red color.
Step 4
Artboard 4: "Shock" emoji.
Delete the eyebrows and lips.
Draw highly arched and curved eyebrows and an open mouth, with the Pen Tool (P), and match the colors with the Eyedropper Tool (I).
Step 5
Artboard 5: "Cool" emoji.
Use the Pen Tool (P) to draw cool cat-eye sunglasses over the eyes, and add a white reflection.
Then, using the Direct Selection Tool (A), tweak the lips to look more "pouty", and delete the dark center of the lips.
Step 6
Artboard 6: "Delighted" emoji.
Delete the eyes and the dark lip center.
Draw eyeshadow, and black filled "squinting" eyes with lashes, using the Pen Tool (P).
Use the Selection Tool (V) to lower the brows and slightly rotate them straighter.
Use the Eyedropper Tool (I), to match colors.
Step 7
Artboard 7: "Giggle" emoji.
Delete the eyes, brows, and lips.
Use the Pen Tool (P), to draw eyeshadow, arched squinting eyes with long lashes, a curved smile, and arched brows.
Use the Eyedropper Tool (I) to match colors.
Use the Selection Tool (V) to lift the cheek shadow upwards and move her beauty spot closer to the mouth.
Step 8
Artboard 8: "Cry Me a River" emoji.
Delete the eyes, brows, and lips
Use the Pen Tool (P) to draw inverted brows, water flowing eyes, lots of tears, and an open mouth.
Next, use the Eyedropper Tool (I) to match colors, and color fill the tears with shades of blue. Remember the shortcuts to arrange elements to the back/front. Move the beauty spot closer to the lips. Use the Pen Tool (P) with a dark skin shade, and draw a triangular shape below the tear flow to make the tears look as if they are flying out.
Step 9
Artboard 9: "In Love" emoji.
Delete the eyes and lips.
Use the Selection Tool (V) to rotate the ends of the brows, and lower them slightly.
Use the Pen Tool (P) and draw two big hearts in place of the eyes, a shy smile, and hearts around the hijab.
Finally, use the Eyedropper Tool (I) to match colors.
Step 10
The last step is to go back through the set, clean up the artwork, make tweaks wherever you see fit, arrange objects in the proper order, and add reflections or extra elements to make each emoji pop, if needed.
File > Save (Command-S).
4. How to Export & Build an Emoji Keyboard
Step 1
File > Export As.
Format: Select PNG, check Use Artboards, and Export.
The PNG dialog boxwill appear:
Resolution: Screen (72 ppi)
Background Color: Transparent
Click OK
Step 2
Now to make our emoji keyboard.
Apple made it easy with Sticker Apps for Messages in iOS 10. Most apps today do not allow for custom emoji or stickers, so until they're available, you need to build one.
The keyboard we will build with Xcode can
be used mixed with text you type and custom emoji that function
as stickers. You can actually peel
them off the keyboard and place them on top of other messages.
If you are just getting into creating sticker emojis, you can check out my
other tutorial How to Create iMessage Stickers for a more informative guide.
Upload a 1536 x 1536 px version of the app image into the MakeAppIcon webpage, and it will email you all the sizes you need for all iOS devices.
Click on the blueStickers.xcstickers folder in the left navigation area, and select the iMessage App Icon folder, and upload all the icon images by dragging and dropping.
Step 6
Finally, Product > Archive.
Window > Organizer. You will see your stickers in the left bar.
Validate.
If it's all good, Upload to App Store, and it will appear on your iTunes Connect, and you can send it through to Review.
Once you’re ready, click Submit. And
that’s it!
Wait for the review process, which usually takes a few days, and your emoji keyboard will be ready!
Ready, Set, Text!
Great job! We’ve illustrated a custom Khaleeji Woman Emoji set, using basic Adobe Illustrator shortcuts and tools. We can use these simple techniques to draw a larger set of emojis to share and upload on our iMessage app.
If you want to code a mobile app, you need to know a programming language. But it can be hard to choose the best language (or languages) for a project. There are a lot of options out there, and in this post I'll help you narrow them down so that you can pick the best.
It all depends on what you're building. For certain apps, mobile developers may not need all the available features of a particular language. In other situations, a single app may require more than one language. In this tutorial, I'll go through various mobile development languages and highlight some of the details that can help you make a decision.
Let's start with some languages which you may already be familiar with.
Android Languages
Java
According to the TIOBE Index, Java is the most popular programming language as of June 2017. If you want to develop Android apps, you'll most likely to stick to Java. It has a large and established developer community, and that means you can easily get technical support and help.
So, when you're developing for mobile with Java, you are free to come up with any type of app you can think of. The only limits will be your imagination and the level of your Java knowledge.
Kotlin was designed and developed by JetBrains, the Czech company known for their popular IDE, IntelliJ IDEA. Google's Android team has recently announced that they are officially adding support for the Kotlin programming language.
Kotlin was developed to address some of the issues in Java. According to the language's fans, Kotlin syntax is simpler, cleaner, and leads to less code bloat. This helps you focus more on solving the actual problem, rather than struggling with verbose syntax. Also, you can use Kotlin and Java together in the same project, and that makes it really powerful.
If you want to develop for iOS, Swift might be the language for you. Introduced in 2014 and declared open source in 2015, Swift is swiftly catching up with mobile developers. It's very popular, especially among new iOS development startups.
Apple has added some great features to the language, such as simplified syntax, the ability to easily pinpoint programmer errors, etc. Apple's huge efforts to promote Swift clearly indicate that it wants this new language to become the mainstream programming language for its app ecosystem.
Objective-C was the original development language for iOS. While the recently introduced Swift language is the future of iOS development, many advanced projects still rely on Objective-C. So the transition from Objective-C to Swift is expected to be somewhat slow, and you may need both of them for some projects, at least for the time being.
Cross-Platform Languages
JavaScript
JavaScript has a long history going back to the early days of the World Wide Web. A very popular front-end and server-side language, it lets web developers do everything from enhancing the user experience of their websites to building complete web apps.
Today, there are several JavaScript frameworks that specifically target mobile development platforms, such as Ionic 2 and React Native. It's very easy to develop cross-platform mobile apps using these frameworks and libraries. This means you only have to write a single version of your app, and it will run on iOS or Android.
TypeScript is a superset of JavaScript and offers better safety by adding optional static typing. It also provides better support for developing large-scale applications. Developed and maintained by Microsoft, TypeScript allows developers to write cross-platform mobile apps using frameworks such as NativeScript.
C# is the language of Windows Mobile. It's very similar to C++ and Java. Microsoft has adopted some of the features of Java to simplify its architecture, while maintaining the C++ like design. It also has a large and active community of developers who are always friendly and helpful.
C
C is the second most popular language on the TIOBE index, and just like Java, its community is full of seasoned developers who could offer you valuable advice on how to write bug-free code.
Created by Dennis Ritchie, while working for Bell Labs, C is a widely adopted and powerful language that allows you to directly manipulate low-level operations of a computer. If you want to use Android NDK (Native Development Kit), you'll need to get familiar with the C language.
C++
If you are familiar with C, then you'll really enjoy reading and writing C++ code. C++ is an extension of C, with more high-level features and support for object-oriented programming. C++ is also a favorite language of Android NDK developers. You can use C++ to develop Windows Mobile apps too. C++ goes head to head with Java in the field of software development, and it's really worth mastering.
Python
Python is another popular language that's easy to learn and easy to read. The creators of the language have made extra efforts to keep the syntax as simple and clear as possible. This really helps novice developers maintain high levels of productivity, from day one. If you are comfortable with writing Python code, then you can use frameworks such as Kivy to develop cross-platform mobile apps.
Ruby is an object-oriented scripting language, influenced by Ada, C++, Perl, Python, and Lisp. RubyMotion is a great framework for developing native and cross-platform mobile apps in Ruby. It's fairly easy to learn Ruby, thanks to its elegant syntax that focuses on simplicity and productivity.
Mobile apps can be grouped into three categories, namely native, hybrid, and native cross-platform. Native apps can fully utilize all the OS facilities and features, and they are the fastest when it comes to performance. However, you need to maintain different codebases for different mobile platforms, as each platform uses different programming languages.
For example, Android platform makes use of Java plus C/C++ to develop native apps. Apple's iOS platform relies on Objective-C and Swift as its native languages. C# is used by Windows Mobile platform to code its native apps. All of these native app programming languages are compiled, rather than interpreted.
Hybrid mobile apps are actually websites that are designed to work with mobile devices too. A user can access them via a mobile browser as if they are visiting a website on a desktop computer. The combination of HTML5, CSS and JavaScript is the obvious choice, if you want to develop web apps.
Recently, a new batch of mobile cross-platform frameworks has emerged. These frameworks combine the best features of native apps and hybrid apps—they're fast and light and can access the full power of the native device, but they also are coded with JavaScript and other web languages, so a lot of code can be reused between platforms.
React Native and NativeScript are popular native cross-platform frameworks. If you want to learn more about these, check out our comprehensive beginner course or some of our many tutorials.
Comparison of Features
Before getting deeper into the detailed language features, you must select a platform. You can refer to the article Mobile Development Platforms to get an idea of various platforms and how to pick the one that suits you best. Assuming that you've already selected a mobile development platform, let's see how these languages compare in terms of their features.
If you want to develop for native Android, Java and Kotlin are your obvious choices. So let's have a look at them.
Null Safety
Kotlin has better control over Null references so that the famous NullPointerException bugs (common in Java) are much easier to eliminate. This reduces development time and improves programmer productivity.
Concurrency
Although Java supports concurrent operations, the relevant code may suffer heavily from readability and maintainability issues. Kotlin addresses these issues by using Coroutines. The resulting code is easily readable and easily understandable too.
Type System
Java's type system isn't consistent, and this can sometimes lead to confusion. In particular, the primitive types such as integer, boolean, and so on need to be handled as special cases. By contrast, Kotlin has a relatively simple and more versatile type system that minimizes programmer errors and mistakes.
Supported Programming Styles
Although Java can theoretically support various programming styles, some developers believe that it overly promotes OOP (Object-Oriented Programming). Kotlin doesn't seem to enforce any particular style of programming, so developers have more freedom to choose an approach that fits best. However, Kotlin developers need to have a thorough knowledge of software architecture and development principles.
Which One to Choose?
In a nutshell, it seems that Kotlin is better than Java, but it may take some time for a complete transformation. One challenge is that programmers are used to the thinking patterns enforced by Java. Another is that Kotlin is a new language, and certain features are still experimental.
Anyway, Google has clearly announced that they will offer complete support for Kotlin. In fact, Android Studio, the official Android IDE, now comes with full support for Kotlin. New features and capabilities are constantly added to Kotlin. Over the next few years, we are going to experience a transition period from Java to Kotlin, at least in native Android development.
Native iOS
Objective-C and Swift are the two options you have for iOS development. So let's have a look at each one's features.
Code Syntax
Swift has simpler and clearer syntax to help programmers achieve their goals with the minimum number of LOC (Lines Of Code). This also helps reduce programmer errors and eases bug fixing.
Memory Management
Swift clearly beats Objective-C, when it comes to memory management. Swift enforces more robust and reliable control mechanisms, allowing programmers to avoid undesirable memory leaks.
Performance
Execution of Swift code is much faster than that of Objective-C. This clearly leads to faster app performance and better user experience.
Supported Programming Styles
Unlike Objective-C, Swift has built-in support for functional programming too. So developers don't have to limit themselves to any pre-defined programming styles. That helps developers understand the problem clearly and come up with a better solution.
Which One to Choose?
Just as Kotlin is slowly replacing Java in native Android development, Swift seems sure to thrive in native iOS development, forcing Objective-C to retire. Apple has already started extensive support for Swift, and that's going to get even better in the future. Like Android developers, iOS developers are also experiencing a transition period at the moment.
While there are several code migration tools available, it may not be possible to fully convert Objective-C projects to Swift without issues. Sometimes, specific workarounds may be required, and that might need a fair knowledge of Objective-C. So the best strategy is to give priority to Swift and learn a bit of Objective-C only when it's absolutely necessary. Also, you need to keep an eye on the latest Swift developments and trends.
Cross-Platform Apps
JavaScript (coupled with other HTML5 technologies) is the most used cross-platform mobile development language. There are also other languages, such as Python and Ruby, but JavaScript has the broadest range of support and adoption.
Unless you are already a big Ruby or Python fan and you want to try out the cutting-edge of mobile development with those languages, you should stick with JavaScript or its type-augmented sibling, TypeScript.
Conclusion
Choosing a mobile development language can be tricky if you don't understand the features of each one, along with the current industry trends. With this knowledge, though, it's easy to see that choosing a language heavily depends on the particular mobile development platform too.
I'm sure now you have a clearer picture of mobile app development languages and are able to match the relevance of their features to the latest development trends. So just get started coding your next app with confidence!
If you want some help getting started with a new language, check out some of the tutorials and video courses linked throughout this post, or some of our other posts on mobile development!
If you want to code a mobile app, you need to know a programming language. But it can be hard to choose the best language (or languages) for a project. There are a lot of options out there, and in this post I'll help you narrow them down so that you can pick the best.
It all depends on what you're building. For certain apps, mobile developers may not need all the available features of a particular language. In other situations, a single app may require more than one language. In this tutorial, I'll go through various mobile development languages and highlight some of the details that can help you make a decision.
Let's start with some languages which you may already be familiar with.
Android Languages
Java
According to the TIOBE Index, Java is the most popular programming language as of June 2017. If you want to develop Android apps, you'll most likely to stick to Java. It has a large and established developer community, and that means you can easily get technical support and help.
So, when you're developing for mobile with Java, you are free to come up with any type of app you can think of. The only limits will be your imagination and the level of your Java knowledge.
Kotlin was designed and developed by JetBrains, the Czech company known for their popular IDE, IntelliJ IDEA. Google's Android team has recently announced that they are officially adding support for the Kotlin programming language.
Kotlin was developed to address some of the issues in Java. According to the language's fans, Kotlin syntax is simpler, cleaner, and leads to less code bloat. This helps you focus more on solving the actual problem, rather than struggling with verbose syntax. Also, you can use Kotlin and Java together in the same project, and that makes it really powerful.
If you want to develop for iOS, Swift might be the language for you. Introduced in 2014 and declared open source in 2015, Swift is swiftly catching up with mobile developers. It's very popular, especially among new iOS development startups.
Apple has added some great features to the language, such as simplified syntax, the ability to easily pinpoint programmer errors, etc. Apple's huge efforts to promote Swift clearly indicate that it wants this new language to become the mainstream programming language for its app ecosystem.
Objective-C was the original development language for iOS. While the recently introduced Swift language is the future of iOS development, many advanced projects still rely on Objective-C. So the transition from Objective-C to Swift is expected to be somewhat slow, and you may need both of them for some projects, at least for the time being.
Cross-Platform Languages
JavaScript
JavaScript has a long history going back to the early days of the World Wide Web. A very popular front-end and server-side language, it lets web developers do everything from enhancing the user experience of their websites to building complete web apps.
Today, there are several JavaScript frameworks that specifically target mobile development platforms, such as Ionic 2 and React Native. It's very easy to develop cross-platform mobile apps using these frameworks and libraries. This means you only have to write a single version of your app, and it will run on iOS or Android.
TypeScript is a superset of JavaScript and offers better safety by adding optional static typing. It also provides better support for developing large-scale applications. Developed and maintained by Microsoft, TypeScript allows developers to write cross-platform mobile apps using frameworks such as NativeScript.
C# is the language of Windows Mobile. It's very similar to C++ and Java. Microsoft has adopted some of the features of Java to simplify its architecture, while maintaining the C++ like design. It also has a large and active community of developers who are always friendly and helpful.
C
C is the second most popular language on the TIOBE index, and just like Java, its community is full of seasoned developers who could offer you valuable advice on how to write bug-free code.
Created by Dennis Ritchie, while working for Bell Labs, C is a widely adopted and powerful language that allows you to directly manipulate low-level operations of a computer. If you want to use Android NDK (Native Development Kit), you'll need to get familiar with the C language.
C++
If you are familiar with C, then you'll really enjoy reading and writing C++ code. C++ is an extension of C, with more high-level features and support for object-oriented programming. C++ is also a favorite language of Android NDK developers. You can use C++ to develop Windows Mobile apps too. C++ goes head to head with Java in the field of software development, and it's really worth mastering.
Python
Python is another popular language that's easy to learn and easy to read. The creators of the language have made extra efforts to keep the syntax as simple and clear as possible. This really helps novice developers maintain high levels of productivity, from day one. If you are comfortable with writing Python code, then you can use frameworks such as Kivy to develop cross-platform mobile apps.
Ruby is an object-oriented scripting language, influenced by Ada, C++, Perl, Python, and Lisp. RubyMotion is a great framework for developing native and cross-platform mobile apps in Ruby. It's fairly easy to learn Ruby, thanks to its elegant syntax that focuses on simplicity and productivity.
Mobile apps can be grouped into three categories, namely native, hybrid, and native cross-platform. Native apps can fully utilize all the OS facilities and features, and they are the fastest when it comes to performance. However, you need to maintain different codebases for different mobile platforms, as each platform uses different programming languages.
For example, Android platform makes use of Java plus C/C++ to develop native apps. Apple's iOS platform relies on Objective-C and Swift as its native languages. C# is used by Windows Mobile platform to code its native apps. All of these native app programming languages are compiled, rather than interpreted.
Hybrid mobile apps are actually websites that are designed to work with mobile devices too. A user can access them via a mobile browser as if they are visiting a website on a desktop computer. The combination of HTML5, CSS and JavaScript is the obvious choice, if you want to develop web apps.
Recently, a new batch of mobile cross-platform frameworks has emerged. These frameworks combine the best features of native apps and hybrid apps—they're fast and light and can access the full power of the native device, but they also are coded with JavaScript and other web languages, so a lot of code can be reused between platforms.
React Native and NativeScript are popular native cross-platform frameworks. If you want to learn more about these, check out our comprehensive beginner course or some of our many tutorials.
Comparison of Features
Before getting deeper into the detailed language features, you must select a platform. You can refer to the article Mobile Development Platforms to get an idea of various platforms and how to pick the one that suits you best. Assuming that you've already selected a mobile development platform, let's see how these languages compare in terms of their features.
If you want to develop for native Android, Java and Kotlin are your obvious choices. So let's have a look at them.
Null Safety
Kotlin has better control over Null references so that the famous NullPointerException bugs (common in Java) are much easier to eliminate. This reduces development time and improves programmer productivity.
Concurrency
Although Java supports concurrent operations, the relevant code may suffer heavily from readability and maintainability issues. Kotlin addresses these issues by using Coroutines. The resulting code is easily readable and easily understandable too.
Type System
Java's type system isn't consistent, and this can sometimes lead to confusion. In particular, the primitive types such as integer, boolean, and so on need to be handled as special cases. By contrast, Kotlin has a relatively simple and more versatile type system that minimizes programmer errors and mistakes.
Supported Programming Styles
Although Java can theoretically support various programming styles, some developers believe that it overly promotes OOP (Object-Oriented Programming). Kotlin doesn't seem to enforce any particular style of programming, so developers have more freedom to choose an approach that fits best. However, Kotlin developers need to have a thorough knowledge of software architecture and development principles.
Which One to Choose?
In a nutshell, it seems that Kotlin is better than Java, but it may take some time for a complete transformation. One challenge is that programmers are used to the thinking patterns enforced by Java. Another is that Kotlin is a new language, and certain features are still experimental.
Anyway, Google has clearly announced that they will offer complete support for Kotlin. In fact, Android Studio, the official Android IDE, now comes with full support for Kotlin. New features and capabilities are constantly added to Kotlin. Over the next few years, we are going to experience a transition period from Java to Kotlin, at least in native Android development.
Native iOS
Objective-C and Swift are the two options you have for iOS development. So let's have a look at each one's features.
Code Syntax
Swift has simpler and clearer syntax to help programmers achieve their goals with the minimum number of LOC (Lines Of Code). This also helps reduce programmer errors and eases bug fixing.
Memory Management
Swift clearly beats Objective-C, when it comes to memory management. Swift enforces more robust and reliable control mechanisms, allowing programmers to avoid undesirable memory leaks.
Performance
Execution of Swift code is much faster than that of Objective-C. This clearly leads to faster app performance and better user experience.
Supported Programming Styles
Unlike Objective-C, Swift has built-in support for functional programming too. So developers don't have to limit themselves to any pre-defined programming styles. That helps developers understand the problem clearly and come up with a better solution.
Which One to Choose?
Just as Kotlin is slowly replacing Java in native Android development, Swift seems sure to thrive in native iOS development, forcing Objective-C to retire. Apple has already started extensive support for Swift, and that's going to get even better in the future. Like Android developers, iOS developers are also experiencing a transition period at the moment.
While there are several code migration tools available, it may not be possible to fully convert Objective-C projects to Swift without issues. Sometimes, specific workarounds may be required, and that might need a fair knowledge of Objective-C. So the best strategy is to give priority to Swift and learn a bit of Objective-C only when it's absolutely necessary. Also, you need to keep an eye on the latest Swift developments and trends.
Cross-Platform Apps
JavaScript (coupled with other HTML5 technologies) is the most used cross-platform mobile development language. There are also other languages, such as Python and Ruby, but JavaScript has the broadest range of support and adoption.
Unless you are already a big Ruby or Python fan and you want to try out the cutting-edge of mobile development with those languages, you should stick with JavaScript or its type-augmented sibling, TypeScript.
Conclusion
Choosing a mobile development language can be tricky if you don't understand the features of each one, along with the current industry trends. With this knowledge, though, it's easy to see that choosing a language heavily depends on the particular mobile development platform too.
I'm sure now you have a clearer picture of mobile app development languages and are able to match the relevance of their features to the latest development trends. So just get started coding your next app with confidence!
If you want some help getting started with a new language, check out some of the tutorials and video courses linked throughout this post, or some of our other posts on mobile development!
Firebase is a cross-platform real-time mobile database platform that allows coders to focus on what they do best—coding their apps—without having to worry about DevOps concerns like server infrastructure and database modeling. Backed by Google, Firebase takes the complexities out of dealing with back-end real-time databases, authenticating users, and working with offline synchronization workflows.
While there are many solutions out there for BaaS, such as Realm (check out my Realm.io tutorial here on Envato Tuts+) Firebase doesn’t require any prior infrastructure server configuration, as the platform takes care of hosting and in return exposes an SDK.
Beyond a NoSQL real-time database, with Firebase you get analytics, crash-reporting, user authentication, cloud messaging, push notifications and more. The associated costs also scale with your project—as you grow, you move from a freemium model to a per-usage model.
In this tutorial, I'll show you how to set up Firebase on iOS using CocoaPods, and how to authenticate users using two popular methods: email and password or via the phone with SMS.
To learn about Firebase for Android, check out some of our other tutorials here on Envato Tuts+.
This tutorial assumes you have a working knowledge of iOS and Swift, as well as some basic experience with CocoaPods. If you need to learn more, check out our Swift tutorials and CocoaPods tutorials.
Objectives of This Tutorial
By the end of this tutorial, you'll have started on a simple Firebase-powered app that makes use of the Firebase SDK to authenticate users, using email and password as well as by SMS. Along the way, you'll learn about:
setting up Firebase with CocoaPods
setting up the App Delegate to connect to Firebase
setting up the provisioning entitlements for Text/SMS user authentication
using FirebaseUI to authenticate users easily
In future tutorials in this series, you will learn to work with other aspects of the Firebase platform, such as using the real-time database to store app data.
Set Up the Project
In this series, we're going to build a to-do app called FirebaseDo. Let’s start by cloning the project from GitHub:
Next we are going to initialize the project to generate a new PodFile, as follows:
pod init
You should see a new file named Podfile located in the root directory of your project. This file basically sets out the libraries we want to use in our project. Open it and add the following Firebase declaration lines:
pod 'FirebaseUI'
Pod 'Firebase'
Save and then enter the following in your terminal to build the pods:
pod install
We will be using FirebaseDo.xcworkspace instead of FirebaseDo.xccodeproj, allowing us to work with the dependency libraries we set up on CocoaPods, so go ahead and open the workspace and then switch to your browser.
Next, click on Add Firebase to your iOS app, which will then walk you step by step through the process of registering your app on Firebase.
At some point, it will instruct you to add the GoogleService-info.plist file into your Xcode project:
You've already added the libraries via CocoaPods, so you can skip the remaining instructions and return to the Firebase console.
Authenticating Users
Firebase Authentication provides backend services,
easy-to-use SDKs, and ready-made UI libraries to authenticate users to your
app. It supports authentication using passwords, phone numbers, popular
federated identity providers like Google, Facebook and Twitter, and more. (source: Firebase Authentication)
Before we demonstrate how to use FirebaseUI to automate the authenticating your users, we are going to first explore the SDK methods that Firebase exposes as part of the FirebaseAuth Framework Reference API for handling the creation and sign-in of users manually.
Sign Up, Sign In, and Sign Out Users
To create a new user, you would use the Auth.auth().createUser() method block, as follows:
Assuming the errorobject is nil, the user will not only be signed up successfully but will also be signed in. To sign in an existing user explicitly, you would call:
Signing out a user is as easy as calling try!
FirebaseAuth.signOut():
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
We want to be able to handle various potential errors gracefully, in case the authentication calls go astray, and when the error object is not nil (or inversely, the user object is nil), an error has occurred. Consult the Firebase documentation for a list of all common error codes. In our code, we'll only handle a few general errors.
Managing Authentication State Changes
Throughout the app lifecycle, the authentication state will change, so being able to detect when a user has authenticated, or a session has expired, is important in ensuring users don't have access to parts of your app that they shouldn't be accessing.
By creating a handler, .addStateDidChangeListener, you are now able to detect what state the user is in and trigger a specific call, based on that.
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
// ...
}
Managing Users
After the user has authenticated, you are able to access the user object and obtain user information such as the user’s ID, email address, and photo avatar (if provided). The following method will also assert that the user is indeed currently authenticated with the user object not being nil:
if Auth.auth().currentUser != nil {
// User is signed in.
let uid = user.uid
let email = user.email
let photoURL = user.photoURL
// ...
} else {
// User is not signed in
}
Emailing Users
Firebase provides excellent support for sending users email verifications or a password reset request email.
Auth.auth().currentUser?.sendEmailVerification { (error) in
// ...
}
Auth.auth().sendPasswordReset(withEmail: email) { (error) in
// ...
}
Anonymous Users
Firebase also has a way to manage the anonymous authentication workflow, which essentially is a temporary account that can be used to authenticate users and provide them with limited access. The idea is at a certain point in time, anonymous users might opt to sign up, and Firebase can then provide a bridge to link their anonymous accounts to their sign-in credentials without having to lose data persisted during their anonymous states. To sign in an anonymous user, you would call:
Auth.auth().signInAnonymously() { (user, error) in
// ...
}
To transition the user from an anonymous account to an authenticated account (using email and password), you would call the following method within a registration screen view controller, requesting the email and password, and then call the user.link() method.
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
user.link(with: credential) { (user, error) in
// ...
}
Firebase also supports methods for the other federated authentication mechanisms.
There you have it—we’ve gone through the important API methods that Firebase have provided to handle and authenticate users. While the code I've shown you isn't complicated by any means, Firebase makes it even easier than this, with the introduction of FirebaseUI. In this second half of this tutorial, we are going to add authentication to our sample to-do app.
Implementing FirebaseUI
FirebaseUI provides a
drop-in auth solution that handles the UI flows for signing in users with email
addresses and passwords, phone numbers, and with popular federated identity
providers, including Google Sign-In and Facebook Login.
Next, we are going to demonstrate how to implement authentication using FirebaseUI.
In the Firebase Console, go to the Authentication tab and enable the following modes of authentication:
Email/Password
Phone
We just saw how to manage and authenticate users manually using the available Firebase SDKs. We are now going to see how to let FirebaseUI do all the heavy lifting for us. In HomeViewController.swift, import the following libraries:
In the UIViewController.swift declaration, add the FUIAuthDelegate:
class HomeViewController: UIViewController, FUIAuthDelegate {
...
Below this class declaration, we are going to declare three private variables that we will be working with. These will let us reference our current authentication object, the AuthUI instance, and our authentication listeners, respectively:
fileprivate(set) var auth:Auth?
fileprivate(set) var authUI: FUIAuth? //only set internally but get externally
fileprivate(set) var authStateListenerHandle: AuthStateDidChangeListenerHandle?
Next, let's wire up our View Controller so that when it loads up the first time, we hook up a listener to detect when the authentication state changes using a handler. When the auth state changes, we'll summon the self.loginAction(sender: self) method to bring up our FirebaseUI authentication controller.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.auth = Auth.auth()
self.authUI = FUIAuth.defaultAuthUI()
self.authUI?.delegate = self
self.authUI?.providers = [FUIPhoneAuth(authUI: self.authUI!),]
self.authStateListenerHandle = self.auth?.addStateDidChangeListener { (auth, user) in
guard user != nil else {
self.loginAction(sender: self)
return
}
}
}
In this method, we also instantiate the private variables we've declared earlier, set the authUI delegate to our own class, and finally set the list of other providers we will be supporting, which in our case will be FUIPhoneAuth.
If we wanted to support Google, Facebook or other third-party providers, we could add them to this list. Also note, we don’t need to explicitly include email and password as it is implicit, provided it is enabled it in the Firebase console.
Showing the Login UI
Next we handle the loginAction() method, which would be called in the case that the event listener determines the user is not currently authenticated. All we need to do in this case is present the authUI.authViewController modal FirebaseUI, and it would include the associated authentication providers we declared earlier.
This is where the magic begins, as FirebaseUI handles everything: asking the user to enter his or her email address, determining if the user exists (in which case the user will be asked for their password), or for a new user, collecting their name and nominating a password.
@IBAction func loginAction(sender: AnyObject) {
// Present the default login view controller provided by authUI
let authViewController = authUI?.authViewController();
self.present(authViewController!, animated: true, completion: nil)
}
If we were to implement the authentication methods manually, we would need to handle all these different scenarios, including email password resets and so on.
Handling Auth State Changes
Finally, we implement the required protocol for our FIRAuthUIDelegate delegate, which will allow us to listen and handle authentication states. This method will only proceed if an error has indeed occurred, but we can even handle successful authentications.
// Implement the required protocol method for FIRAuthUIDelegate
func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) {
guard let authError = error else { return }
let errorCode = UInt((authError as NSError).code)
switch errorCode {
case FUIAuthErrorCode.userCancelledSignIn.rawValue:
print("User cancelled sign-in");
break
default:
let detailedError = (authError as NSError).userInfo[NSUnderlyingErrorKey] ?? authError
print("Login error: \((detailedError as! NSError).localizedDescription)");
}
}
Phone Authentication Setup
Before we take the app for a spin, we need to add a few more steps to be able to handle phone-based authentication. Phone authentication lets users enter their phone numbers, and verifies their identity via an SMS message that includes a one-time code.
To obtain the APNs token needed by the Firebase server, implement the following in the AppDelegate.swift file:
As we have already enabled the phone number sign-in in the Firebase console, our next task is to provision FirebaseDo to receive APNs from Firebase, a task you would also do if you want to support push notifications in general. In this case, however, Firebase will send a silent push notification to the device to verify the phone number sign-in request.
You won’t be able to test this authentication method via Xcode Simulator, rather you will need to connect your iPhone to install and run the app.
In Xcode, go to Capabilities and enable Push Notifications. The app will automatically provision and create a FirebaseDo.entitlements file, as shown in the project navigator.
Next, we are going to create an Apple Push Notification Authentication Key to upload to Firebase. In the Apple Developer Portal, under Keys, fill in the name of your project, making sure to tick APNs. Download the resulting .p8 file and take note of the key ID as we are going to need to enter it shortly.
Switch back to the Firebase Console, and under Project Settings (the gear icon), select the Cloud Messaging tab. Under iOS App Configuration and APNs Authentication Key, select the Upload button and upload the .p8 file, along with the key ID and app ID. The resulting settings screen should resemble the following:
Testing the App
And that’s it—we didn’t have to add very much extra code to our app to set it up for a complete signup and login authentication workflow. Let’s build and run the app in Xcode to see FirebaseUI in action. The first time you run the app, you won't be authenticated, so you will get a generic template with the authentication options you’ve chosen in Firebase console.
Entering a new user’s email address will push the Create Account screen, asking you for your name and password.
Completing this form will register you as a new user (although our app will only display a blank screen). To confirm that a new user has been created, you can go to Authentication > Users in your Firebase Console.
Test out each of the authentication methods, remembering that you will need to log-out in order to re-trigger the authentication prompt. Re-trigger auth so by adding the following code as the first line in viewDidLoad() after the super call:
try firebaseAuth.signOut()
This will force the application back to its initial state so that you can test authenticating via phone SMS. Run the app again, this time choosing Sign in With Phone.
Conclusion
In this tutorial, you got an introduction to using Firebase as a back-end platform for your app, and you saw how to authenticate users using the traditional email and password combination, as well as via phone and SMS, an approach made popular by apps like WhatsApp.
We then started building our simple FirebaseDo app, and although it doesn’t do any of the actual reminder-type functionality yet, we will start working on that in the next tutorial. But in just a few lines, we managed to accomplish the following:
integrated Firebase to set up an authentication mechanism for email and password
added the ability to authenticate via SMS
tracked authentication states
handled errors gracefully
In the rest of the series, you will get a look at some of the other components of Firebase.
And while you're here, be sure to check out some of our other posts on iOS app development!