Thursday, August 18, 2016

How to Secure an iOS App


Security is a key aspect of software development. Almost every mobile application deals with user information or communicates with a remote server. Even though security has improved dramatically over the past decades, it continues to be a hotly debated topic.

In this article, I would like to highlight a number of topics that are related to security and mobile development. Along the way, I touch upon a number of best practices and suggestions that you may find useful to secure the applications you write.

Security and Privacy

Security is relative. Security exploits are discovered and patched on a regular basis. Nothing is perfect. That said, there are a number of things you can do to improve the security of your mobile applications. A burglar is less tempted to break into a building surrounded by an electric fence than one that isn't.

Some developers overlook the fact that the users of their applications trust them with their information. As a developer, you are responsible for keeping that information secure. It doesn't matter what that information is. While the information may look unimportant to you, it is important to the user.

Apple takes security and privacy very serious. HealthKit is a fine example of Apple's commitment to protect the user's privacy. The user decides which health data an application has access to. While the application can request access to the user's health data, HealthKit doesn't tell it which data it has access to. In other words, Apple considers the authorization status of an application to be sensitive information it should not know about.

1. Storing Data

Should Your Application Store Data

Before you decide how or where to store a particular piece of data, you need to ask yourself whether you should store that data in the first place. Is it possible, for example, to keep the data in memory instead of writing it to disk or sending it to a remote server? This can greatly simplify your application's architecture and improve its security.

Where Should You Store Data

If you decide that storing the data locally is your only option, you need to decide where you plan to store that data. For sensitive information, such as credentials, the keychain is your best option. This is only feasible for small amounts of data your application doesn't need frequent access to.

Does the data need to be backed up to iCloud or iTunes? If that isn't the case, then you may want to consider storing the data in the Caches directory of the application's sandbox. This directory is not backed up to iCloud and iTunes. Why is that important? Data that doesn't exist cannot be compromised.

Keychain

The defaults system, accessible through the NSUserDefaults class, is a fast and convenient way to store chunks of data. Unfortunately, the defaults system is often overused by developers. It happens all too often that sensitive information, such as credentials and access tokens, are stored in the defaults system.

A much better location for storing small chunks of sensitive information is the system's keychain. As the name implies, it was designed with security in mind and it has been around for many, many years. Even though the keychain is managed by the operating system, by default, other applications don't have access to the items your application stores in the keychain.

It is true that the interface for accessing the keychain services is archaic. Fortunately, there are several excellent libraries that overcome this hurdle. Lockbox, for example, is a lightweight library for interacting with the system's keychain services. Lockbox's interface is easy to use and understand.

Keys, Tokens, Credentials

It is tempting to store keys, tokens, and even credentials in easily accessible locations, such as the target's Info.plist or a JSON file in your application's bundle. The truth is, it is child's play to extract that information from an application downloaded from the App Store. By storing an API token for a web service in your application's Info.plist, other developers can find it and use it.

2. Networking

App Transport Security
Security and privacy have been on Apple's agenda for many years and, along with other major players, Apple has decided to lead by example. During last year's WWDC, the company introduced App Transport Security.

With App Transport Security, Apple aims to improve the security of its platforms and the applications running on them. No matter how much Apple invests in securing its operating systems, a system is only as secure as its weakest component and that includes third party applications.

App Transport Security enforces applications to send network requests over a secure connection. If App Transport Security is enabled for an application, network requests are sent over HTTPS by default. Apple emphasizes its commitment to security and privacy by automatically enabling App Transport Security for applications built with Xcode 7.

You can read more about App Transport Security on Envato Tuts+. While it is easy to disable App Transport Security, bear in mind that one of the goals of App Transport Security is to make developers consider the network behavior of their applications.

Who Am I Talking To

Virtually every mobile application uses the network. This means that people with bad intensions heavily focus on this aspect of application security. Networking is a complex matter and applications build on top of a slew of technologies to fetch the data they are interested in.

As a developer, it is key that you stick to a number of best practices. We already discussed App Transport Security and the rules this new technology enforces. It doesn't stop there, though. You may also want to look into more advanced topics, such as certificate pinning to ensure the server your application is communicating with isn't fraudulent. Modern libraries, such as Alamofire, make this much easier.

3. Sensitive Information

User Data
Most applications use or store sensitive user information. Mobile devices have access to a wide range of user information that is often personal and sensitive in nature, such as location, address book, and health information.

As I mentioned earlier in this article, the first question you need to ask yourself is whether you need to access this information and, more importantly, whether you need to store that information.

If you can access the information you need through a native framework, such as HealthKit, then there is no need to duplicate and store that information. For example, Apple will reject applications that store the user's health information in iCloud.

Keep It Local

Assuming that you need to store some sensitive information, consider whether that information should be kept local. Is it necessary to send sensitive information to a remote server?

Storing sensitive information comes with a warning. If the server you are storing sensitive information on is compromised, you may be held responsible for exposing that information to other parties.

Credentials

Online security has evolved tremendously over the past decades. Authentication protocols, such as OAuth, have made communication with web services more secure and transparent.

If your application needs to talk to a secure server, consider how your application manages credentials. Does it keep them in memory or store them on disk? If you ask the user's username and password to fetch an access token, it is fine to store that access token. But should you also store username and password? The answer is no in most situations.

For applications that deal with very sensitive data, such as health or financial information, it may even be better to keep the access token in memory, not storing it on disk. Keeping it in memory makes it much safer, making your application much less of a liability. Chances are that the access token has a short lifetime anyway.

Conclusion

The security of an application is a fundamental aspect of software development. Consider what data your application has access to and whether it should store that information. If you do decide to store sensitive information, keep the above tips and best practices in mind. Make sure you treat the user's information with respect. Even though the information may look unimportant to you, it is important to the user.
Written by Bart Jacobs

If you found this post interesting, follow and support us.
Suggest for you:

The Complete iOS 10 Developer Course - Build 21 Apps

Intro To iOS Backend Development: Image Uploads

How to Make a Freaking Video Game - iOS, SpriteKit, SceneKit

Master iOS 9 - 10 - Xcode 8 and Swift 3

Complete Swift 3 training - Get ready for XCode 8 and iOS 10

Monday, August 15, 2016

Build a High-Performance Mobile App With Famo.us and Manifold.js

For the last few months I’ve been wanting to dive into this new JavaScript framework since I saw its launch event in October of 2014. Famo.us includes an open-source 3D layout engine fully integrated with a 3D physics animation engine that can render to DOM, Canvas, or WebGL. In short, you can get native performance out of a web application, largely due to the way Famo.us handles the rendering of its content.

Jenn Simmons of the Web Platform Podcast recently had Famo.us CEO, Steve Newcomb on the podcast to discuss the mobile performance and their upcoming mixed mode. This was perfect timing, as Microsoft had just released ManifoldJS, a tool which allows you to package your web experience as native apps across Android, iOS, and Windows. I wanted to put these two technologies to the test.

In short, I wanted to determine if Famo.us does actually have great mobile performance, as well as have an understanding of how straightforward the process was for packaging my web application as a mobile app.

What Problem Do These Two Things Solve?

The web isn’t necessarily known for creating high-performance applications, which is a shame because it truly is capable of blazing fast interactive apps, but sadly has been plagued by the DOM. With technologies like the HTML5 canvas, WebGL, and asm.js, the browser really can be a playground for cutting-edge interactivity. Famo.us aims to solve this, getting around the bottleneck for most web applications, which is the DOM, and utilizing WebGL and abstracting your work from the DOM. More on this later.

ManifoldJS aims to make the life of a mobile developer easier than ever by utilizing Web App Manifests, allowing websites to declare app-like properties. ManifoldJS uses that standard for those platforms that support it, but falls back to Cordova for those that don’t. Cordova is great, but the W3C also considers work done at Mozilla (Firefox Open Web Apps), Google (Chrome Hosted Apps) and Microsoft (Windows 8 had local web apps, Windows 10 extends over to hosted web apps). With this, we can now wrap websites and create hybrid applications that can be deployed in the various app stores, while still taking advantage of many native aspects for each device (contacts, calendar, file storage, gyro, GPS, etc.).

When we combine the two, we can create applications at native speed that can be deployed in a number of app stores, utilizing largely one code base. There is no silver bullet for mobile development, but this certainly makes the process easier.

Getting Started With Famo.us

Famo.us has a University page, which provides a great starting point for understanding how the framework works, as well as offering a few sample projects. I ran through all of the courses on the University site and came out with a pretty clear understanding of the framework. They also have integration with other libraries, such as Angular, but I haven’t had time to dive into that just yet.

Next, I clicked on the link at the top-right corner of the page to download their package of guides and two example projects. This is different from what is found on their GitHub page.

I opened the famous-starter-kit folder and navigated to /reference-tutorials and found folders for /slideshow and /timbre. Slideshow is pretty clever; it grabs images from Picasa and draws them to the screen as though they came fresh from a Polaroid camera. You can find a live version of this on my site.

Out of the box, however, it didn’t work.

I soon realized what the issue was, though. Their sample pointed toward an invalid Picasa URL. It’s been more than six months since the sample was released, so I would hope that it would be corrected by now, as I’d imagine this would be a damper for a number of people learning to use this otherwise fantastic framework.

Once I changed the URL in the SlideData.js file, all was fine. What the project does is grab images from a Picasa album and draw them to screen. With each click, the camera drops the current image, and a fresh one is ejected from the front of the camera, and is quickly exposed before your eyes, along with some nice physics applied to the swaying back-and-forth of the image. The step-by-step instructions for creating this project can be found on the Famo.us website.

There is another project in the /timbre folder, but I wasn’t able to get that to work either. You can find the associated tutorial on the Famo.us website, though, and at least walk through the process of building it yourself.

How Does Famo.us Work?

I’m not going to spend too much time getting into the details of Famo.us here, but if you really want to dive deeper, there's an article on Medium that gives a great overview.

From the Famo.us website:
Interacting with the DOM is riddled with performance issues. Famo.us abstracts away DOM management […] If you inspect a website running Famo.us, you’ll notice the DOM is very flat: most elements are siblings of one another. […] Developers are used to nesting HTML elements because that’s the way to get relative positioning, event bubbling, and semantic structure. However, there is a cost to each of these: relative positioning causes slow page reflows on animating content; event bubbling is expensive when event propagation is not carefully managed; and semantic structure is not well separated from visual rendering in HTML. Famo.us promises a rich 60 FPS experience, and to do so, we needed to circumvent these inefficiencies.
By utilizing the CSS3 primitive -webkit-transform: matrix3d, along with the hardware acceleration it affords, we can get far greater performance than we could if we just tinkered with the DOM. Any time you touch the DOM, it is expensive. Nicole Sullivan, a fantastic web developer known for her CSS work, gives an excellent explanation of reflows and repainting inside the browser, and how we can avoid these issues. Fortunately, Famo.us abstracts all of this away from us.

Rather than write any HTML code, all of our Famo.us code will be done in JavaScript. Take a look at some of their samples on CodePen to get a good understanding for how little HTML you actually write (none) and what the JavaScript looks like. In an upcoming tutorial, I’ll dive far more in-depth with Famo.us than I do here.

Now we’re talking my language! Some high-performance applications in the browser!

How Does ManifoldJS Work?

The installation process for ManifoldJS is pretty straightforward. Check out their GitHub page for more information. Jeff Burtoft also walks you through the process of creating a hosted web app at ThisHereWeb.com.

This project will continue to evolve over the coming months. In the last week alone I’ve seen several additions. On platforms which natively support web applications, such as Windows 10, Chrome OS, and Firefox OS, ManifoldJS will create native packages. On platforms such as iOS and Android, Cordova is used, which allows a developer to write a web application but still access many of the native features of a device, either through Cordova itself, or the active plugin community.


Jeff Burtoft explains hosted web apps very well on his blog and in his recent //BUILD/ presentation. The video from //BUILD 2015 showcases exactly what you can do with this technology.

My Setup

I’m doing this tutorial from a MacBook Pro running Yosemite 10.10.3, Visual Studio Code as my IDE, and MAMP as my local web server. I then use Source Tree as my Git tool of choice, and host my open-source code on GitHub, and I’ll be deploying to iOS via Xcode.

I know, a Tech Evangelist at Microsoft using Apple products and telling you about open-source tools. What is the world coming to?

Putting It All Together

The first thing I did was download the Famo.us samples from their website. I made the appropriate changes to their SlideData.js file, as I mentioned above, so that my project was able to pull in feeds from Picasa. I’ve uploaded it to GitHub so that you have a sample that works immediately. View the live site, and head to GitHub to download the working project.

Afterwards, I logged in to Azure and created a new website. You can get $200 worth of Azure trial credits, or reach out to me about a free BizSpark membership for yourself or your startup, which grants $150/month of web hosting.

I then point this new Azure website to my GitHub repo. Scott Hanselman explains how to do this in a few steps. From there, I have Azure monitor my GitHub repo for this project, and any changes I push to that repository are immediately picked up by Azure, and the latest changes can be viewed on the website and manifest project immediately.

Generating the App Manifest

Next up, we need to use ManifoldJS to "wrap" our web app so that we can deploy it to the various app stores. Firefox OS and Chrome support this natively, but for iOS, Android, and Windows 8 or 10, we need to utilize Cordova. ManifoldJS will generate an app manifest file for us, which has all of the information the app stores need to get our project going.

You have two options here: Use the Manifold Web App Generator, which will provide a GUI and step-by-step instructions, or run it through the command line.


Alternatively, for the command line, you need to install ManifoldJS first. Make sure you have NPM installed, and then run:
  1. npm install -g manifoldjs/manifoldjs
With me so far? Now we can call ManifoldJS and have it generate a folder for us with projects for each of the platforms. In the terminal I entered:
  1. ManifoldJS -d /Users/DaveVoyles/Documents/FamousManifold http://famous-camera-app.azurewebsites.net/final/
The path following -d tells ManifoldJS which directory I want it to be stored in. Soon after, you should see the terminal building the project before your eyes.


Navigate to where you stored this project, and you’ll find a series of folders there. I then navigated to cordova/platforms/iOS and looked for the file ending in xcodeproj, as I wanted to test this out in the iOS simulator. Double click on that icon to open the project in Xcode.


And there we have it, a Famo.us application running inside of Cordova on iOS.


Wrapping It All Up

I plan to try out Angular + Famo.us in one of my upcoming demos, as well as wrapping that in ManifoldJS to test for performance on iOS. If you’re looking to debug these apps, might I suggest looking at VorlonJS? It’s platform-agnostic, takes a minute to set up, and in the link above, I illustrate how I can test apps on a desktop browser, as well as mobile devices.

I’d really like to stress test what mobile browsers are capable of when combining a framework like Famo.us and Cordova, so look for a sample involving those two soon. As the web continues to evolve, Microsoft will continue to update its dev.modern.ie/platform/status/ site to reflect changes to the new Edge browser. The most exciting announcement to me, though, is the recent switch from "in development" to "in edge" tag for asm.js. Soon we’ll be able to run native applications inside of the browser. It’s an exciting time to be working on the web.

More Hands-On With JavaScript

It might surprise you a bit, but Microsoft has a bunch of free learning on many open-source JavaScript topics, and we’re on a mission to create a lot more with Microsoft Edge.

Here are some great resources from my team and colleagues:
  • Hosted Web Apps and WebPlatform Innovations: a deep-dive on topics like manifold.JS
  • Microsoft Edge Web Summit2015: a complete series of what to expect with the new browser, new web platform features, and guest speakers from the community
  • Best of //BUILD/ andWindows 10: including the new JavaScript engine for sites and apps
  • Advancing JavaScript without Breaking the Web: Christian Heilmann’s recent keynote
  • Practical Performance Tips to Make Your HTML/JavaScript Faster: a seven-part series from responsive design to casual games to performance optimization
  • The Modern Web Platform Jump Start: the fundamentals of HTML, CSS, and JavaScript
And some free tools to get started: Visual Studio Code, Azure Trial, and cross-browser testing tools—all available for Mac, Linux, or Windows.
Written by David Voyles

If you found this post interesting, follow and support us.
Suggest for you:

Ionic by Example: Create Mobile Apps in HTML5

Mobile Game Development Gamemaker Studio

Ionic 2 Tutorial with Two Complete Apps

Android Application Programming - Build 20+ Android Apps

iOS 10 & Swift 3: From Beginner to Paid Professional

Sunday, August 14, 2016

20 Material Design Resources_part 2 (end)

3. Backgrounds

16 Material Design Backgrounds
I don't know about you, but I really like the Material Design wallpapers and backgrounds designers are creating. They are great for mobile, web, or as a desktop wallpaper.


10 Material Design Backgrounds
This item includes exactly what it says on the tin, ten beautiful Material Design backgrounds.


More Material Design Backgrounds
If you can't get enough of Material Design and want a few backgrounds, say 45, as a wallpaper for your computer, then this item is for you. The item includes a wide range of color combinations to fit everyone's needs.


Even More Material Design Backgrounds
Okay. This is one more set of Material Design backgrounds. The backgrounds included in this set are a bit more fancy. The item includes twelve backgrounds in various color combinations.


20 Material Design Backgrounds
I promise that this is the last set of Material Design backgrounds. If there's one thing I really like about Material Design, it's the color schemes and how Material Design plays with shadows and offsets.

4. Icons

Icons are an important part of mobile. The screens of mobile devices are often too small to include a lot of text and, therefore, icons are better suited for mobile user interfaces. GraphicRiver offers many, many icon sets. I'm sure you can find a set that perfectly fits your project's needs.

Material Design Icons
If your application adopts Google's Material Design guidelines, then you'll need icons that fit those guidelines. This item includes more than 700 icons you can use in your Material Design applications. Note that this set of icons can be used anywhere you like, native Android applications, web, desktop, etc.

Material Line Icons
This item includes no less than 240 line icons, ready to be used in your next mobile project. The item includes vector files, but, if you're in a hurry, it also includes PNG files you can just drop in your project. With 240 icons, virtually every commonly used icon is included.


More Icons
This icon pack includes 36 multipurpose Material Design icons for your next Android project. They are easy to edit so you can modify them to your project's needs.


5. Miscellaneous

Android App Mockup
Beautiful and compelling product shots of your application are a great way to feature your application. Screenshots aren't always the best solution for this. With these device mockups, you can insert screenshots of your application to do them justice.

This item includes eight high resolution scenes in which you can showcase your application. The templates are easy to use. Open the Photoshop file you like, insert your application's screenshot, and render the result.


Written by Bart Jacobs
If you found this post interesting, follow and support us.
Suggest for you:

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

The Complete Android Developer Course: Beginner To Advanced!

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps


Saturday, August 13, 2016

20 Material Design Resources_part 1

As a developer, your design skills may not be that great. But you want your applications to look great. Right? In this quick tip, I list 20 Material Design resources for Android you can find on GraphicRiver. Not only will they save you time, they will make your applications look great.

1. Templates

Application templates are great for speeding up application development. They help you give your application an appealing look and feel. GraphicRiver offers a broad range of template you can use in your Android projects. I've selected a few to give you an idea of what is available on GraphicRiver.

Material Design Mobile Mockup
This template covers a number of application types, such as a chat application, clock and calendar, camera, and weather. The files are neatly organized and the template makes use of the lovely Roboto font.

Football App with Material Design
Sports applications are hot and this template is geared towards football, also known as soccer in some countries. It includes no less than seventeen screens, ranging from statistics to leaderboards. Even though the template adopts Google's Material Design, you can easily repurpose it for other mobile platforms.

Mali-Garnet
This multipurpose template is a perfect fit if you are looking for a dark theme. It includes a number of application types, such as chat, photos, and camera. The components of the templates are vector-based so it shouldn't be a problem to make modifications without compromising quality and crispness.


Mistari
Mistari is a Material Design template that includes most of the screens you need for a modern mobile application, including calendar, weather, profile, and sign in/up. It's easy to change the primary colors of the template to fit your project's needs.


Rocket News
Rocket News focuses on news and magazine applications. The item includes most of the screens you'll need to build the foundation of a news or magazine application for Android.


Idealogic
This gorgeous Android template contains a massive 72 Photoshop files and includes three color styles. It is well organized and easy to customize. The template features a range of application types and a large number of controls, components, and interfaces. If you are looking for a template for inspiration, then this is certainly one to consider.


2. Components

If you don't want to start with a template and only need some inspiration or a few components, then GraphicRiver has your back covered. The following items include Material Design components that can be used in virtually every mobile or web project that adopts Material Design.

Material Design UI Kit
This set of Material Design components fits nicely in your next mobile or web project. The item includes buttons, sliders, checkboxes, menus, text fields, and even a video player. Did you spot that Roboto is the font used in this item?


Flat Navigation Kit
This item intensely focuses on navigation, both for mobile and web. It uses flat design in combination with simple icons, menus, and button styles. It looks modern, clean, and ready to drop in your next mobile or web project.


Material Design Pricing Table
This pricing table includes three designs. You can use it for mobile, web, or even for a paper brochure.


Material Design Ebook Template
One of the strengths of Material Design is its versatility. Google's Material Design team went to great lengths to ensure Material Design fits any context. This item includes a template for ebooks and, unsurprisingly, it looks and feels great. The item includes ten different pages, .indd and .idml files, you can use for your next ebook.


Medical Timetable
Don't be thrown off by the title of this item. This item include a gorgeous template for a calendar. It is detailed and beautifully adopts the Material Design guidelines. It can be used for mobile or web, depending on your project's needs.


Writen by Bart Jacobs
If you found this post interesting, follow and support us.
Suggest for you:

Ionic by Example: Create Mobile Apps in HTML5

Mobile Game Development Gamemaker Studio

Android Application Programming - Build 20+ Android Apps

Mobile Game Development Gamemaker Studio

iOS 10 Message Extension App Reskinning without Coding

Thursday, August 11, 2016

Create a Mobile App Using Famo.us and Angular_ part 2(end)

Where Angular Finally Comes In

Now here's where you can put all of your Angular skills and data binding to work with the Angular implementation. If you're already experienced with Angular, then it's not radically different here.
  1. <!-- Next button -->
  2. <fa-modifier
  3.     fa-origin    ="origin.center"
  4.     fa-align     ="align.nextBtn"
  5.     fa-size      ="size.btn"
  6.     fa-scale     ="scale.nextBtn.get()"
  7.     fa-translate ="trans.topLayer">
  8.     <fa-surface
  9.         class    ="one-edge-shadow center-align next-btn"
  10.         ng-click ="getPokemon(); nextBtnPressAnim(); frontImgAnim()">
  11.         {{nextBtn}}
  12.     </fa-surface>
  13. </fa-modifier>
This button appears on the first screen and simply pulls another Pokémon from the database. All of the ng (Angular) directives you are familiar with are here, such as ng-click. I have multiple functions here. Notice that they are not comma-separated.

I am also binding the value of $scope.nextBtn to {{nextBTn}} in HTML.

To allow Famo.us and Angular to work together, we need to include $Famo.us at the top of our JavaScript file. Here's how you do it:
  1. angular.module('famousAngularStarter')
  2.   .controller('PokemonCtrl', ['$scope', '$http', '$famous', function ($scope, $http, $famous) {
  3.  
  4.     /* Inject famo.us to DOM */
  5.     var View           = $famous['famous/core/View'                 ];
  6.     var Modifier       = $famous['famous/core/Modifier'             ];
  7.     var Surface        = $famous['famous/core/Surface'              ];
  8.     var Transform      = $famous['famous/core/Transform'            ];
  9.     var Transitionable = $famous['famous/transitions/Transitionable'];
  10.     var Timer          = $famous['famous/utilities/Timer'           ];
Animations

What would a high-performance app be without animations? Famo.us is packed with them, which makes it easy to get started. Here's one for animating the image on the front.
  1. /*
  2.  * @OnClick: Sets the opacity and scale for the front image when user clicks "Next" btn
  3.  * 1) Turns opacity invisible quickly before returning to original opacity, revealing new Pokemon
  4.  * 2) Turns scale down before quickly turning it back up to original size
  5.  */
  6. $scope.frontImgAnim = function() {
  7.   var hideDuration   =  200;
  8.   var returnDuration = 1300;
  9.  
  10.   $scope.opac.imgFront.    set(0,           {duration: hideDuration,   curve: "easeIn"},
  11.     function returnToOrigOpacity() {
  12.       $scope.opac.imgFront.set(1,           {duration: returnDuration, curve: "easeIn"})
  13.     }
  14.   );
  15.   $scope.scale.imgFront    .set([0.5, 0.5], {duration: hideDuration,   curve: "easeIn"},
  16.     function returnToOrigSize() {
  17.       $scope.scale.imgFront.set([0.8, 0.8], {duration: returnDuration, curve: "easeIn"})
  18.     }
  19.   )
  20. };
There are several curve types you can use here. Checkout the docs for more info. I'm also using a callback function, returnToOrigSize,, to have the image grow and then shrink back to the original size.

Points of Frustration

I ran into a few issues along the way.

FA-Directives Have Their Properties Set as Strings
  1. fa-origin    ="origin.center"
If you have a spelling error, the app will just use the default values for that property. This snagged me several times, which is why you see I set all of my properties as an object, such as align.frontName, to make it easier to read.

Adding Classes
In FA-Directives you add multiple classes as strings and they are not comma-separated.
  1. <fa-surface
  2.     class    ="one-edge-shadow center-align next-btn"
  3.     ng-click ="infoBtnPressAnim(); flip()">
  4.     {{infoBtnText}}
  5. </fa-surface>
If you try to add classes by creating surfaces in JavaScript, you pass in an array of strings.
  1. var logo = new Surface({
  2.     properties: {
  3.          ...
  4.     },
  5.     classes: ['backfaceVisibility, class-two'] 
  6. });
It took me a while to understand that, as I only found the solution in thisthread.

Famo.us + Angular Seems to Be Deprecated (For Now)
Midway through this project, I saw that Famo.us was working on an improved version of the framework that includes Mixed Mode. Famo.us + Angular doesn't take advantage of these additions (yet) at least. That doesn't mean FA is going anywhere, as it works perfectly fine—it's just that you won't be getting the latest features.

More Hands-On With JavaScript

This article is part of the web development series from Microsoft tech evangelists on practical JavaScript learning, open-source projects, and interoperability best practices, including Microsoft Edge browser and the new EdgeHTML rendering engine.

We encourage you to test across browsers and devices including Microsoft Edge—the default browser for Windows 10—with free tools on dev.modern.IE:

Scan your site for out-of-date libraries, layout issues, and accessibility
Use virtual machines for Mac, Linux, and Windows
Remotely test for Microsoft Edge on your own device
Coding Lab on GitHub: Cross-browser testing and best practices
Written by David Voyles

If you found this post interesting, follow and support us.
Suggest for you:

Learn Angular 2 Development By Building 10 Apps


Create a Mobile App Using Famo.us and Angular_part1

I love high-performance JavaScript, and I love sharing what I believe is its true potential. In this tutorial, I want to focus on Famo.us, which can allow you to maintain a silky-smooth 60 frames per second while having fluid animations on screen.

Famo.us does this by utilizing the CSS3 primitive -webkit-transform: matrix3d, which lets the framework compute the composite matrix and skip the browser’s renderer. No plug-in, no download, no hack. By appending this to each DIV, developers can render the composite matrix and go straight to the GPU.

I go more in-depth when discussing the ins and outs of Famo.us in this blogpost. Thanks to Zack Brown for all of his assistance with this! Let’s get started.

By the end of this project you will be able to:
  • understand how Angular works within the context of a Famo.us application
  • harness the true power of JavaScript and the good parts of HTML5
  • create smooth animations
My goal for this project is to illustrate how easily you can create HTML5 and JavaScript projects that work at near-native speeds on mobile applications.

Features
  • The mobile application runs on iOS and Android via Cordova.
  • The Windows 10 universal app runs natively on, well, Windows 10.
  • This project can also be run as a hosted website, although I have it scaled which is best for mobile devices.
Requirements
  • PC or Mac
  • Web server
  • Cross-platform test matrix (like a BrowserStack, IDE, or free virtual machines for Edge HTML, the rendering engine for Microsoft Edge and hosted web app content on Windows 10)
Setup
  1. Download the source from GitHub.
  2. Download and install a web server (I use MAMP on OS X, or the built-in IIS server with Visual Studio on Windows).
Open the Project
  1. Start your web server.
  2. Navigate to famous-angular-Pokemon/app/.
The project is designed to work on mobile devices, so use the mobile emulator in your browser to get the correct view. Here's what it would look like on an iPhone 6 inside the emulator via the Chrome desktop browser (375x667):

How It Works

Hitting the Database
I pull all of the information from the PokeAPI, which has a well-documented API, but it's missing images for each of the Pokémon. For the images, I just pull the name of the currently chosen Pokémon and append it to the end of this URL: http://img.pokemondb.net/artwork/. For example: http://img.pokemondb.net/artwork/venusaur.jpg will lead you to an image of Vanosaur. Nifty, right? Sadly, they do not have an API available.

Each time the user presses the Next button, a random number is generated between a min/max value that I've defined (say, 1 to 20), and it pulls a Pokémon from the database that matches that number. Here's what it looks like:

http://pokeapi.co/api/v1/pokemon/1/ returns a JSON object for Bulbasaur. You can play with their API.

Looping Through the Data
I then loop through that JSON object and set the properties I find to variables in Angular, using the $Scope object.

Here's an example:
  1. /*
  2.    * Grab Pokemon from the DB
  3.    */
  4.   $scope.getPokemon = function () {   
  5.     // Generate a random num and use it for the next pokemon
  6.     getRandomInt($scope.minVal, $scope.maxVal); 
  7.     // Retrieve data from DB and draw it to screen
  8.     $http.get($scope.dbURL + $scope.pokemonNum + "/")
  9.       .success(function(data) {
  10.         $scope.name       = data.name;
  11.         $scope.imageUrl   = $scope.imgDbURL + $scope.name.toLowerCase() + '.jpg'; 
  12.         /* 1) Empty out the current array to store the new items in there
  13.          * 2) Capitalize the first character for each ability from the database
  14.          * 3) Store that ability in a new abilityObj & add it into the abilities array
  15.          */
  16.         $scope.abilities.length = 0;
  17.         for (var i = 0; i < data.abilities.length; i++){
  18.          var capitalizedString = capitalizeFirstLetter(data.abilities[i].name);
  19.          var abilityObj        = {name: capitalizedString };
  20.           $scope.abilities.push(abilityObj);
  21.         }
  22.         $scope.hitPoints  = data. hp;
  23.         var firstType     = data.types[0].name;
  24.         $scope.types.name = capitalizeFirstLetter(firstType);
  25.         determineNewBgColor();
  26.       })
  27.       .error(function(status){
  28.         console.log(status);
  29.         $scope.name = "Couldn't get Pokemon from the DB";
  30.       });
  31.   };
You may notice that I also have a few other functions here, such as capitalizeFirstLetter, which does exactly that. I wanted the abilities and type (e.g. poison, grass, flying) to have the first letter capitalized, since they come back from the database in all lowercase characters.

I also loop through the abilities and push them to an ability object, which looks like this:
  1. $scope.abilities       = [
  2.   { name: "Sleep"},
  3.   { name: "Eat"  }
  4. ];
The database also returns multiple types for certain Pokémon, such as Charizard, who is flying as well as fire. To keep things simple, though, I only wanted to return one from the database.
  1. $scope.types      = { name: "Grass" }; 
  2. var firstType     = data.types[0].name;
Drawing It to the Screen
Famo.us has two waves of drawing content to the screen by creating surfaces, which are the elements that contain your text, images, etc.:
I didn't use JavaScript to draw the surfaces in this app. Instead I chose to use only FA (Famous-Angular) Directives, such as:
  1. <!-- Name-->
  2. <fa-modifier
  3.     fa-origin    ="origin.center"
  4.     fa-align     ="align.frontName"
  5.     fa-size      ="size.frontName"
  6.     fa-translate ="trans.topLayer">
  7.     <fa-surface
  8.         class    ="front-name-text">
  9.         {{name}}
  10.     </fa-surface>
  11. </fa-modifier>
This is for the name above the Pokémon on the front screen.

You'll notice that the surface is wrapped by a fa-modifier. You can read about those in the Famo.us documentation, but they essentially adjust the properties of a surface, such as alignment, size, and origin. It took me a while to wrap my head around the difference between alignment and origin, so here's how I came to understand it.

Origin 

This is the reference point on any surface. If I want to draw a rectangle and move it around the screen, I need to decide which point on that rectangle will be my starting point. The Famo.us docs explain it well. The values are laid out as follows:
  1. $scope.origin           = {
  2.                               // X    Y 
  3.  topLeft:                 [0,   0  ],
  4.  topRight:               [1,   0  ],
  5.  center:                   [0.5, 0.5],
  6.  bottomLeft:            [0,   1  ],
  7.  bottomRight:          [1,   1  ]
  8. };
Alignment

This is a surface's location on the screen. When you make changes to the alignment, it is using the origin as the reference point to start from.
  1. $scope.align              =  {
  2.                                 // X        Y 
  3.   frontName:             [0.50,    0.10],
  4.   frontImg:              [0.50,    0.40],
  5.   backImg:               [0.5,     0.38],
  6.   center:                [0.50,    0.50]
  7. };
Written by David Voyles
If you found this post interesting, follow and support us.
Suggest for you:

Monday, August 8, 2016

An Introduction to NativeScript


In this article, we're going to take a look at NativeScript, an open-source framework for building mobile apps with JavaScript. At the end of the article, you should have a pretty good idea of what NativeScript is, how it works, and what technologies it uses. Aside from that, we're also going to answer common questions that you might have when exploring a new technology, such as how it differs from alternatives like Cordova and React Native, and how Telerik is involved in the project.

1. What Is NativeScript?

NativeScript is a framework for building cross-platform native mobile apps. It allows developers to use XML, CSS and JavaScript to build apps for Android, iOS, and even the Windows Universal Platform. Unlike Cordova, which uses WebView for rendering the UI of the app, NativeScript uses the native platform's rendering engine, which means that it provides a truly native user experience.

2. Pros
  • It is free and open source. This means that you can contribute to the code and use it however you want, as long as you don't violate the Apache 2.0 license.
  • It allows you to build truly native apps for Android and iOS devices. Each of the UI components that NativeScript exposes is translated into its corresponding native UI components.
  • It lets you access native platform APIs through JavaScript code. You don't need to have knowledge of Java or Objective-C in order to use native platform APIs because you can write it all in JavaScript. This means that if you need to access a specific device feature, you can just learn how to access native APIs with JavaScript and you're good to go. 
  • It gives users an experience closer to native than those provided by hybrid mobile app frameworks like Cordova. 
  • It allows developers to easily build, deploy and manage their NativeScript apps through the Telerik platform. I'll discuss the Telerik Platform more in a later section.
  • It has zero-day support for new native platforms. This means that you can immediately use the latest native APIs and UI components whenever Google or Apple updates their platform.
  • The documentation provides lots of information on how to get started, core concepts, and the user interface. There are also examples, tutorials, a forum, Stack Overflow questions, and sample apps which can help beginners get started with NativeScript. 
  • You can write your NativeScript apps with TypeScript. TypeScript is a language that transpiles to JavaScript and adds object-oriented programming capabilities to JavaScript.
  • Any JavaScript library that you can find on npm that doesn't rely on the browser and the DOM can be used within NativeScript. Examples of such libraries include utility libraries such as lodash and underscore. 
  • You can do almost anything with the NativeScript CLI. Basics such as creating a new project, adding a platform, running on a device and deploying to a specific platform are all included. Aside from that, you can also install plugins, debug the app, and upload to the app store.
3. Cons
  • There's no HTML and DOM in NativeScript. You'll need to learn how to use the different UI components in order to build the UI of the app. 
  • Verified plugins are lacking. At the time of writing of this article, there are only 16 verified plugins in total. Though there are a lot of NativeScript plugins listed on npm, you can never really be sure of their quality. 
  • Developers need to know the native Android and iOS APIs in order to access the device hardware and other platform-specific features.
  • Due to its native nature, you can only test apps on an actual device or an emulator. This makes the initial setup for testing slower. But once you get it running on the device, hot-reloading takes over. This means that every time you make a change to the source code, it immediately reloads the app to reflect the changes.
  • Not all UI components are available for free. You need to purchase Telerik UI for NativeScript if you want to use components such as charts and calendars.
4. How Does It Work?

NativeScript is composed of a JavaScript virtual machine, a runtime, and a bridge module. The JavaScript virtual machine interprets and executes JavaScript code. Then the bridge module translates the calls to the platform-specific API calls and returns the result to the caller. To put it simply, NativeScript provides developers with a way to command the native platform through JavaScript instead of Objective-C on iOS or Java on Android.

Of course, there's a lot more going on behind the scenes, but the developers at Telerik explain it better than I can, so if you want to learn more about the inner workings of NativeScript, you can read the article by Georgi Atanasov on NativeScript - a Technical Overview or TJ VanToll's article on How NativeScript Works.

5. What Technologies Does It Use?

With NativeScript, you use XML to describe the UI of the app, CSS for styling, and JavaScript to add functionality.

You can use TypeScript with Angular 2 if you prefer to use a framework for authoring your JavaScript code.

For styling, NativeScript only uses a subset of CSS. This means that not all CSS features that are available in a browser environment can be used. For example, you cannot use floats or position attributes. Here's the full list of supported CSS properties. Just like in the browser, you can add styles that apply to the whole app, to specific pages, or to a specific UI component only. If you prefer to use Sass, you can install the NativeScript Dev Sass plugin.

For describing the structure of the user interface, you use XML. Each page in the app should be in its own XML file. NativeScript comes with pre-defined user interface widgets or components which you can use to build the UI of the app. Some of these components are similar to the different HTML elements that you use in the browser.

For example, there's an Image component, which is the equivalent of the img element, or the TextField component, which is equivalent to the input element with a type of text. Event handlers such as tapping a button are added in the component itself. Here's an example:
  1. <Button tap="doSomething" />
  1. exports.doSomething = function(){
  2.     // do something
  3. }
Another thing to note is that the components also serve as templates. If you're familiar with templating libraries such as Handlebars or Mustache, you should be at home with the following syntax:
  1. <ListView items="{{ animals }}">
  2.   <ListView.itemTemplate>
  3.     <StackLayout class="animal">
  4.       <Label text="{{ . }}"/>
  5.     </StackLayout>
  6.   </ListView.itemTemplate>
  7. </ListView>
The example above uses the ListView component. As the name suggests, this component allows you to create lists. animals is an array defined in the JavaScript file and is bound to the animals variable on page load. This makes the animals variable available for use inside the XML file.
  1. var animals = ['panda', 'tiger', 'monkey', 'snake', 'mantis'];
  2. function pageLoaded(args){
  3.     var page = args.object;
  4.  
  5.     page.bindingContext = {
  6.         animals: animals
  7.     }
  8. }
This outputs each item in the array inside the ListView.

Lastly, there are plugins which allow you to access the device hardware and platform-specific features. NativeScript comes with a camera plugin pre-installed. This allows you to access the camera of the device and take photos. You can then save the local path to the photo in your app for later use. Platform-specific features such as social sharing can also be used by installing plugins such as the NativeScript Social Share Plugin.

6. What Apps Can You Build?

Due to the native nature of NativeScript, you can build almost any kind of app with it. Here are a few examples of apps that you can build with NativeScript:
  • Apps that talk to the server, such as news apps and social networking apps.
  • Simple games such as chess, tic-tac-toe, or pinball.
  • Real-time apps such as chat apps or live feeds. There's a Firebase plugin for NativeScript which you can use to implement real-time apps.
  • Music and video streaming apps. There's a video player plugin which allows you to play videos stored locally or stream remote videos such as the ones on YouTube.
  • Maps and geolocation apps. There are plugins for Google Maps, and native map APIs.
  • Apps that access the device hardware. Examples include camera apps and IoT apps.
When it comes to the kinds of apps that you can build with NativeScript, the only limiting factors are performance and plugin availability. Writing native mobile apps in JavaScript comes with a price: you can't really expect to build apps that demand high performance. Examples include games with complex graphics and animations, apps with lots of moving parts, and background processes.

Another limitation is plugin availability. Most developers come to NativeScript from a web development background. This means that most of them aren't familiar with or have limited knowledge of the native platform APIs which could be used to create plugins to access the device hardware or platform-specific features such as contacts or messaging.

If you want to learn more about what kinds of apps you can build with NativeScript, you can check out the App Showcases page. Most of the apps that are listed in there are published on both the Google Play Store and Apple Store. This means that you can install it and run it on your device to get a feel of what apps built with NativeScript look like and how they perform.

7. How Does NativeScript Compare to Hybrid Frameworks?

If you're not new to hybrid mobile app development, you might have come across frameworks such as Cordova and React Native. NativeScript is related to these two frameworks in that they both aim to solve the problem of "Write once, run everywhere" in the field of mobile app development. Now let's look at each framework side by side:


To sum it up, Cordova is the old generation of hybrid mobile app frameworks. It uses the WebView to render the UI of the app and accesses native device capabilities by means of plugins. React Native and NativeScript are the new generation because they translate your JavaScript code so that it can be executed by the native platform.

Somebody might come up with a better name for frameworks like React Native and NativeScript in the future. But for now let's classify them as "Native Hybrid Frameworks" because they both use JavaScript for authoring apps and they both offer native-like experience and performance to users.

8. How Is Telerik Involved in the Project?

Telerik is the company that created NativeScript. And, just like any other company, they need to make money in order to survive. So you might ask, if NativeScript is free and open source, how does Telerik make money from it? Well, the answer is through the Telerik Platform and Telerik UI for NativeScript.

The Telerik Platform provides developers with the tools they need to easily design, build, test, deploy, manage and measure the performance of NativeScript apps. Here are a few examples of the tools they offer:
  • a visual app builder that allows you to drag and drop different UI components
  • a cloud database that provides the database for your app
  • live app updates for easily pushing updates to the app without having to resubmit it to the app store and have the user update the app manually
  • an analytics service that answers questions such as how your app is being used, how it's performing, and what your users think of it
Telerik UI for NativeScript is a set of components for building the UI of the app. NativeScript already comes with free UI components, but there are also paid UI components such as the Chart and Calendar which you can only use when you purchase it from Telerik.

9. Next Steps

If you want to learn more about NativeScript, I recommend checking out the following resources:

If you still have questions regarding NativeScript, be sure to check out the FAQ page.
For a hands-on article on building a hello world app with NativeScript, check out Getting Started with NativeScript.
If you want a collection of articles, video tutorials and code snippets about NativeScript, there's NativeScript Snacks and NativeScript Resources.

Conclusion

In this article you've learned the very basics of NativeScript. As you have seen, NativeScript is a good option for building mobile apps using the skills you already have as a web developer. I hope this article has provided you with the necessary knowledge to help you decide whether NativeScript is right for you.
Written by Wernher-Bel Ancheta

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

Build Apps with React Native

Ionic by Example: Create Mobile Apps in HTML5

iOS 10 Projects: Build Amazing Apps with Apple's Newest iOS

iOS 10 & Swift 3: From Beginner to Paid Professional