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

An Introduction to Android Firmware

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

Android phones and tablets are generally a lot more open than their counterparts running operating systems such as iOS, Tizen, or Windows 10 Mobile. If you don't like the firmware the device manufacturer has installed on your Android device, you are free to replace it with your own custom firmware. CyanogenMod, Paranoid Android, and the Pure Nexus Project are examples of custom firmware that enjoy a lot of popularity among Android users.

Custom firmware is also the only way you can install newer versions of Android on devices that are no longer supported by their manufacturers. Unless you own a device that belongs to the Nexus or Android One series, I'm sure you knew that already.

In this article, I help you understand what Android firmware really is and how an Android device uses it. I also introduce you to the tools you can use to replace a device's firmware.

A Word of Caution

Replacing firmware is a risky operation that can potentially make your device unusable. In most cases it also voids your device's warranty. Make sure that you have a backup of your data and a copy of your device's factory image handy before you go ahead and experiment with flashing custom firmware.

1. What Is Android Firmware?

Originally, firmware was a term used to refer to tiny, mission-critical programs installed in the read-only memory, or ROM, of an electronic device. Modifying firmware was either impossible or required special equipment that was usually out of the reach of ordinary end users.

Android firmware, however, is very different. It includes the entire Android operating system and it is stored in a writable form of memory called NAND flash memory, the same type of memory that is used in storage devices, such as USB sticks and SD cards. The word firmware is used only because device manufacturers didn't bother to come up with a new word for it.

Android firmware is also often referred to as Android ROM because, by default, it is not possible for users to directly write to it.

2. What Does Android Firmware Contain?

Firmware installed on an Android device by its manufacturer contains a build of the Android operating system and two additional closed source programs that are usually irreplaceable, a bootloader and radio firmware.

Understanding Bootloaders

An Android bootloader is a small piece of proprietary code that is responsible for starting the Android operating system when an Android device is powered on. However, the bootloader almost always performs one more task. It checks if the operating system it is starting is authentic.

How does it decide what is authentic? It checks if the boot partition has been signed using a unique OEM key, which is short for Original Equipment Manufacturer key. The OEM key, of course, belongs to the device manufacturer, is private, and there is no way you can know what it is.

Because of the authenticity check, you cannot directly install a custom ROM on an Android device. Thankfully, these days, most device manufacturers allow users to disable the check. In Android jargon, they allow users to unlock the bootloader.

The exact procedure you need to follow in order to unlock the bootloader depends on your device. Some manufacturers, such as Sony and HTC, expect you to provide a secret unlock token. Others just expect you to run a fixed set of commands using a terminal.

Usually, a tool called fastboot, which is a part of the Android SDK, is used to run the unlock commands. For example, if you own a Nexus device, you can unlock its bootloader by running the following command:

You learn more about fastboot later in this article. Note that, if you own a device that has a bootloader that cannot be unlocked, there is no easy way for you to modify or replace its firmware.

Understanding Radio Firmware

It might come as a surprise to you, but your Android smartphone actually runs another operating system on an independent processor called a baseband processor. Radio firmware refers to the operating system that runs on the baseband processor.

Usually, it is an RTOS, which short for real-time operating system, and is responsible for managing the cellular radio capabilities of the device. In other words, it is what allows your device to make calls and connect to the internet using wireless technologies such 2G, 3G, and 4G LTE.

The RTOS is a proprietary piece of code and popular baseband processor manufacturers, such as Qualcomm, MediaTek, and Spreadtrum, make sure that its internal workings stay a secret. The Android operating system usually communicates with the RTOS using sockets and callbacks.

Generally, it is not a good idea to replace the radio firmware of your device.

Understanding Android Builds

The Android build is the only part of the firmware that is created from open source code. Consequently, this is the only part that you can modify and extend. When you hear Android enthusiasts say "I flashed a new ROM on my device", you can be sure that they are talking about a new Android build.

An Android build is usually shared in the form of a ZIP file that can be used by fastboot. It has the following contents:

android-info.txt is a text file specifying the prerequisites of the build. For example, it could specify the version numbers of the bootloader and the radio firmware that the build needs. Here is a sample android-info.txt file:

boot.img is a binary file that contains both a Linux kernel and a ramdisk in the form of a GZIP archive. The kernel is a boot executable zImage that can be used by the bootloader.

The ramdisk, on the other hand, is a read-only filesystem that is mounted by the kernel during the boot process. It contains the well known init process, the first process started by any Linux-based operating system. It also contains various daemons such as adbd and healthd, which are started by the init process. Here is what the directory tree of the ramdisk looks like:

system.img is the partition image that will be mounted on the empty system directory you can see in the above tree. It contains the binaries required for the Android operating system to run. It includes the system apps, fonts, framework JAR files, libraries, media codecs, and more. Obviously, this is the file Android users are most interested in when they flash a new ROM.

The system image is also the file that makes most Android users develop an interest in flashing custom firmware. System image files provided by device manufacturers are often full of unnecessary apps and customizations, informally called bloatware. The only way to remove the bloatware is to replace the manufacturer's system image with a more desirable system image.

userdata.img is a partition image that will be mounted on the empty data directory you can see in the ramdisk directory tree. When you download a custom ROM, this image is usually blank and it is used to reset the contents of the data directory.

recovery.img is very similar to boot.img. It has a boot executable kernel file the bootloader can use and a ramdisk. Consequently, the recovery image too can be used to start an Android device. When it is used, instead of Android, a very limited operating system is started that allows the user to perform administrative operations, such as resetting the device's user data, installing new firmware, and creating backups.

The procedure you need to follow in order to boot up using the recovery image is device specific. Usually, it involves entering the bootloader mode, also called fastboot mode, by pressing a combination of hardware keys present on the device, and then selecting the Recovery option. For example, on a Nexus device you need to press and hold the power button in combination with the volume down button.

Alternatively, you can use adb, a tool included in the Android SDK, to directly enter recovery mode.

3. Using fastboot

The easiest way to flash new firmware on your device is to use the fastboot tool. fastboot follows the fastboot protocol to communicate with an Android device. However, it can only do this when the device has been started in fastboot mode. The quickest way to enter fastboot mode is by using adb:

To flash a custom ROM that is available in the form of a ZIP file containing all the image files I mentioned in the previous section, you can use the fastboot update command. For example, here is how you would flash a ROM present in a file called update.zip:

If you want to flash only a specific image, you can do so using the fastboot flash command. For example, here is how you would flash only the system image:

Similarly, if you want to replace only the boot image, you would use the following command:

It is always a good idea to test if a boot or recovery image is working before actually flashing it to your device. To do so, you can use the fastboot boot command. For example, here is how you would check if a custom recovery image called twrp.img is compatible with your device:

Note that none of the fastboot commands I mentioned in this section will work if the bootloader of your device has not been unlocked.

Conclusion

You now know what Android firmware is and how to replace it. I want you to understand that replacing firmware is a risky operation that can potentially make your device unusable. In most cases it also voids your device's warranty. Make sure that you have a backup of your data and a copy of your device's factory image handy before you go ahead and experiment with flashing custom firmware.


2016-07-04T16:45:30.000Z2016-07-04T16:45:30.000ZAshraff Hathibelagal

What to Expect From Swift 3

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

You probably know that Swift 3 is coming later this year. It is the first release that incorporates the hard work of a fantastic community. Dozens of proposals were submitted since Apple open sourced Swift in 2015 and dozens were accepted after careful consideration by the core team. In this article, we take a look at some of the important changes in Swift 3.

What Is Swift 3 About?

The core team has a very clear goal in mind with the release of Swift 3, creating a solid foundation for the Swift programming language. At WWDC 2016, Chris Lattner emphasized that Swift 3 introduces a range of breaking changes with the intent of getting the fundamentals right. That is the common theme of the upcoming release. This means breaking existing features, removing some features, and improving the foundation of the language.

The Swift evolution project has been a true success story for everyone involved in the Swift community. The engagement has been tremendous and the result is Swift 3. Apple is transparent about the release process and snapshots of Swift 3 are available from the Swift website and included in Xcode 8, which is in beta at the time of writing.

More Than Swift

The Swift 3 release not only focuses on the Swift programming language, it also includes substantial changes to the toolchain, the standard library, and the language's interoperability with Cocoa. Remember that Swift is more than a language. When we talk about Swift, we generally only think about the language, but it also includes the standard library and the package manager.

Source Compatibility

If you have worked with Swift, then you know that migrating a codebase from one version to another is no small feat. Unfortunately, migrating a project to Swift 3 will be no different.

That said, the primary goal of Swift 3 is to make sure the transition from Swift 3 to future versions of the language won't be like that. Source compatibility is a key focus point of Swift 3.

Awesomeness

Swift was designed to be a modern programming language, but it was equally important to create a language that looked nice and was ... well ... awesome. With Swift 3, the team continues to "optimize the language for awesomeness" as Chris Lattner puts it.

While there are many breaking changes, the net result is a language that feels and looks great. Swift 3 is a joy to use. The changes to Core Graphics and Grand Central Dispatch, which we discuss in a moment, are fine examples.

What Is Changing?

Enough about how awesome Swift is and how much more awesome Swift 3 will be. In the remainder of this article, I would like to focus on some of the key changes introduced in Swift 3. Keep in mind that Swift 3 continues to evolve until the official release later this year.

API

Readability

A lot of time and energy was spent on improving the API of the Swift language. The changes are significant, there is no denying that. But the result is very, very nice. With Swift 3, the core team aims for an API that focuses on readability and accessibility.

While many of us have become used to the verbosity of Objective-C, the new Swift API takes a different approach by only emphasizing and focusing on the essentials. Take a look at the following example of Swift 2.2.1. This example should look familiar if you have spent some time with Swift ... or Objective-C.

In Swift 3, this code snippet looks slightly different as you can see below.

The Swift community realized that there is no need to include a reference to what is about to be presented since that information is already included in the first parameter. As a result, the method name becomes more readable and more concise. A definite improvement if you ask me.

This is a common thread in Swift 3. Several of the proposals that were accepted and included in Swift 3 focus on simplification and removing cruft from the language. The Swift API was initially heavily influenced by the verbose nature of Objective-C. Readability is great, but Swift 3 cuts back on verbosity without compromising readability.

The Swift community is of the opinion that the design of an API should always take the use of the API into account and that is clearly visible in the changes that are introduced in Swift 3. I am sure you agree that the revamped API looks—and reads—great.

Labeling Parameters

Another important change many developers welcome is the consistent signature of function and methods by including the first parameter label by default. This is what a typical function looks like in Swift 2.2.1. By default, the first parameter label is omitted when the function is invoked.

That is no longer true in Swift 3. The first parameter is no longer given a special treatment, which is a very welcome change.

Because of this change, you could further improve the above example by omitting the reference to the view in the function name.

Import as Member

Working with C APIs in Swift has always looked and felt clunky. Core Graphics functions, for example, are imported as global functions, which isn't a great solution and, as a result, using Core Graphics in Swift doesn't feel great.

The same applies to Grand Central Dispatch. In the next example, we use Grand Central Dispatch to asynchronously dispatch a task to a background queue.

In Swift 3, the API feels much more like a native Swift API. Functions are imported as methods, which results in the following syntax in Swift 3.

Removing Features

The Swift community also agreed on the removal of a number of features, some of which have sparked a few heated discussions. I would like to point out four of them.

C-Style for Loops

Does this look familiar to you?

C-style for loops are no longer available in Swift 3. Wait. What? Why? That is a very good question. You can read the proposal, submitted by Erica Sadun, on GitHub. This brings us to the next controversial change.

Say Goodbye to ++ and --

Soon after open sourcing Swift, Chris Lattner, the creator of Swift, submitted a proposal to remove the increment and decrement operators from the language. In his proposal, he mentions that these operators were added, "without much consideration", early in the development of Swift. To clean up the Swift API and avoid any confusion, ++ and -- are no longer available in Swift.

Don't panic, though. The solution is simple. No need to fret.

No More var Parameters

If you are familiar with functions in Swift, then you know that the parameters of a function are constant by default. You can change this behavior by prepending a parameter name with the var keyword. For variable parameters, a variable copy of the parameter is passed to the function.

But how does this differ from parameters marked as inout? Right. That is exactly what many of us have been wondering and it is the motivation for removing variable parameters from the language.

From the perspective of the function, there is no difference, that is, the function receives a mutable local copy of the parameter's value. As the name implies, however, a parameter marked as inout writes its value back to the original variable.

To avoid any confusion, var parameters are no longer available in Swift 3. Fortunately, inout parameters are here to stay.

Speaking of inout parameters, in Swift 3, the inout keyword is integrated in the type syntax of function parameters. Take a look at the following examples to better understand this change.

Implicit Tuple Splat Behavior

Even though Swift is still very young, there are many features that are pretty advanced. Did you know that you can pass a tuple to a function instead of a list of parameters? There is no need to cheer, though. This feature is going to be removed in Swift 3.

Chris Lattner refers to this behavior as "cute" in his proposal to remove the feature. While this behavior can be useful from time to time, it seems to have quite a few consequences. The reason for bringing up this proposal is to highlight the main goal of the core team, simplifying the syntax and the API of the language.

I can see how this feature looked neat at first, but, as the language grew, gained in complexity, and more people started using it, features like this are adding limited value to the language in exchange for what seems to be a list of complications, including performance issues during compilation and complexity to the type checker that could be avoided by omitting the feature.

What Is the Deal With Swift 2.3?

Last week, I wrote about Xcode 8. In that article, I mentioned that Xcode 8 supports both Swift 2.3 and Swift 3. But what is Swift 2.3 and how does it compare to Swift 2.2?

Swift 2.3 is a minor but important update to Swift. The main difference with Swift 2.2.1, the version included in Xcode 7.3.1, is compatibility with the SDKs for Apple's new operating systems, iOS 10, tvOS 10, watchOS 3, and macOS Sierra (10.12).

This means that you can use and build against the new SDKs without making the jump to Swift 3. With Xcode 8, you can submit applications to the App Store using Swift 2.3 or Swift 3. The Swift team knows and understands that the migration to Swift 3 has a significant impact on existing projects that include Swift. Swift 2.3 makes sure you can migrate your projects when you see fit.

Tools

What I also like about the Swift project is that the tools are developed alongside the language. This means that the tools also receive a substantial update when Swift 3 is released later this year.

Documentation

During WWDC, we already saw a glimpse of the changes made to the documentation. While this may seem trivial, have you ever considered how much time you spend browsing the documentation? I have a soft spot for details like this and appreciate the effort the team has put into making the documentation more accessible. The changes are even more dramatic in Xcode 8 as I wrote last week.

Xcode

For now, the vast majority of Swift developers use Xcode as their workhorse. This may change in the future as the language gains traction on other platforms. Didn't Google have plans to use Swift on Android?

In Xcode 8, the integration of Swift is much improved. Navigating the standard library, for example, is more intuitive. In one of the sessions of WWDC 2016, Ewa Matejska illustrates how the synthesized interfaces are now more intuitive and easier to understand. This makes browsing the standard library less daunting.

This brings us to compilation and optimization. You may have heard of whole module optimization. This feature is now enabled by default in Xcode. It impacts application performance and Apple recommends to have this feature enabled in production. If you want to learn more about whole module optimization, I recommend reading this article by Keith Harrison.

While whole module optimization increases compilation time when you first build a project, the results are more than worth it. Subsequent builds are less impacted thanks to incremental compilation.

Conclusion

Swift 3 is a major milestone for everyone involved in the Swift community. Even though nobody likes breaking changes, the direction the language is taking is becoming more clear, making the platform more robust and ready for future changes without compromising source compatibility.

In this article, I highlighted a few of the more important changes that you can expect in Swift 3. For a comprehensive list of the changes, I encourage you to visit the migration guide on the Swift website.

You can also visit the Swift evolution project on GitHub to read more about the proposals that have been accepted and the ones that are still being worked on. Don't be scared. The proposals are often easy to understand. In fact, the goal of the Swift evolution project is for everyone to be able to add to the discussion. What is stopping you?

2016-07-08T15:55:19.781Z2016-07-08T15:55:19.781ZBart Jacobs

How to Create an Xcode Source Editor Extension

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

Introduction

Xcode is the main IDE (Integrated Development Environment) used by thousands and thousands of developers every day. It is an awesome tool, but sometimes you want to customize some of its features and behaviors to better fit your workflow.

Until Xcode 7, it was possible to inject code into Xcode at runtime to create plugins. Plugins could be submitted and distributed through a great app called Alcatraz. This is no longer possible in Xcode 8.

Xcode 8 validates each library and bundle to prevent malicious code from running without your permission. When Xcode starts, previously installed plugins with Alcatraz are not loaded anymore. Not everything is lost though, Apple also announced at WWDC the possibility to develop Xcode source editor extensions so that everyone can extend existing source editing features. Let's take a look about what we can achieve with such extensions.

1. Getting Started

Xcode 8 source editor extensions are a first step in the right direction. If you have been working with Xcode for a while, you may have found yourself in a situation where you wished that a specific task could be automated within Xcode. Source editor extensions allow third party applications to modify a source file, which is exactly what you need to speed up your workflow.

At this moment, extensions can only interact with the source code. This means that not every plugin available through Alcatraz can be replaced by a source editor extension. But who knows what the future brings.

It is important to understand that each extension must be contained in a macOS app. You could, for example, add preferences and explanations about what the extension does in the macOS app and distribute it through the Mac App Store. Also note that each extension runs in a separate process. If the extension crashes, it won't crash Xcode. Instead, it will display a message that the extension was not able to finish its work.

Furthermore, extensions don't have a user interface and they can only modify the code directly when the user invokes your command. They can't, for example, run in the background.

I recommend watching the WWDC 2016 session about source editor extensions. Not only does it explain how to get started developing Xcode source editor extensions, it also shows tips and shortcuts to speed up your development.

2. Overview

In this tutorial, we are going to develop an extension that cleans up the closure syntax in Swift. Xcode autocompletes a closure syntax with the parentheses, but they can be omitted for brevity. This is a task that can be easily be automated by wrapping it into a source editor extension.

The shorter explanation of what we are going to develop is an extension that transforms any closure to the simpler and cleaner syntax. Take a look at the example below.

3. Project Setup

It goes without saying that this tutorial requires Xcode 8. You can download it from Apple's developer website. It runs on both OS X 10.11 and macOS 10.12.

Create a new OS X project of type Cocoa Application and give it the name CleanClosureSyntax. Make sure that you have set the language of the project to Swift. We will use the new Swift 3 syntax in this tutorial.

Create A New Cocoa Application Project in Xcode 8

We will leave the macOS app empty for now and we can focus on creating the Xcode source editor extension. From the File menu, choose New > Target.... In the left sidebar, choose OS X and select Xcode Source Editor Extension from the list.

Add a New Target of Type Xcode Source Editor Extension

Click Next and set Product Name to Cleaner. A new target will be created for you. Click Activate if Xcode asks you if the newly created Scheme should be activated.

4. Project Structure

Let's first analyze what Xcode just created for us. Expand the Cleaner folder to see its contents.

Xcode Project Contents and Layout

We won't modify SourceEditorExtension.swift in this tutorial, but it can be used to further customize your extension. The extensionDidFinishLaunching() method is called as soon as the extension is launched so that you can perform any initialization if needed. The commandDefinitions property getter can be used if you want to dynamically show or hide certain commands.

SourceEditorCommand.swift is the hear of the extension. This file is where you will implement the logic for the extension. The perform(with:completionHandler:) method is called when the user launches your extension. The XCSourceEditorCommandInvocation object contains a buffer property, which is used to access the source code in the currently selected file. The completion handler should be called with value nil if everything went well, otherwise pass it an NSError instance.

5. Implementing the Extension

Now that the project contains all the required targets, we are ready to start writing the extension. To recap, we want to remove the parentheses from any closure in a Swift file. This can be done in three steps:

  • find the lines that contain a closure
  • remove the two parentheses from that particular line
  • substitute back the modified line

Let's get started.

We can use a regex (regular expression) to parse each line of code and see if it contains a closure. You can refer to Akiel's tutorial about Swift and regular expressions if you want to learn more about regular expressions. You can use RegExr to test your regular expressions. Take a look at the following screenshot to see how I tested my regex.

Regex to Parse A Closure Syntax

Open SourceEditorCommand.swift and modify the perform(with:completionHandler:) method to look like this:

Find Lines With Closure Syntax

We first create and array of Int values that will contain the line indexes of the modified lines. This is because we don't want to substitute all the lines. We want to replace only the lines that we modify.

We enumerate over all the lines of the invocation.buffer object and we try to find a match for the RegularExpression object. If I remove the escaping characters from the regex, it looks like the following:

This regex matches when a string has the following characteristics:

  • It has a curly open bracket ({), which is followed by 0 or more characters, except a new line character (\n).
  • An open parenthesis (() must be found again, followed by 0 or more characters. This part should contain the parameters of the closure.
  • We then need to find a closing parenthesis ()), followed by 0 or more characters, which are the optional return types.
  • Finally, the in keyword should be found.

If the RegularExpression object fails to find a match (for example, if the regex is not valid), we call the completionHandler with the error as a parameter. If a string that matches all these conditions is found on a line, we have correctly localized a closure.

Clean Up Syntax

When a match is found, we call a utility method on NSString that removes the parentheses. We also need to pass in the range of the match to avoid removing some other parentheses outside of the closure.

Update Lines

The last part of code checks that at least a line was changed. If this is true, we call setArray() to substitute back the new lines and the correct indexes. The completion handler is called with the value nil so that Xcode knows that everything went well.

We still have to implement the remove(characters:range:) method on NSString. Let's add this extension at the top of file.

This method calls replacingOccurrences(of:with:range:) on NSString for each character that we want to remove.

6. Testing

Xcode 8 comes with a great solution to test extensions. First of all, if you are running OS X 10.11 El Capitan, open Terminal, execute the following command, and restart your Mac.

After doing this, build and run your extension by selecting the appropriate scheme. When it asks which app to run, search for Xcode and make sure to select the beta version of Xcode 8. A new Xcode version will be launched with the application icon grayed out so that you can recognize in which instance of Xcode you are testing the extension.

In the new Xcode instance, create a new project or open an existing one, and go to Editor > Clean Closure > Source Editor Command. Make sure to have at least one closure in the currently focused Swift file to see the result. As you can see in the following animation, our extension works.

The Final Result

Source Editor Command is the default name for a command. You can modify it in the Info.plist file of the extension. Open it and change the string to Clean Syntax.

We can also assign a shortcut to automatically invoke the Clean Syntax command. Open Xcode's Preferences and select the Key Bindings tab. Search for Clean Syntax and the command will appear. Click to the right of it and press the shortcut you would like to use, for example, Command-Alt-Shift-+. You can now go back to the source file and press that shortcut to invoke it directly.

Xcode Preferences to Set a Key Binding for an Extension Command

7. Tips and Tricks

Xcode 8 and source editor extensions are still in beta at the time of writing. The following tips can help you debug some issues you may be running into.

If your extension is not selectable in the Xcode testing instance, kill the com.apple.dt.Xcode.AttachToXPCService process and run the extension again.

Xcode Has A Process That You Can Kill if the Extension Is No Visible

Only substitute back the lines that you modify in the buffer. This makes the extension run faster and it will have less chances to be killed by Xcode. The latter can happen if Xcode believes a command of your extension is taking too long.

If you want to show multiple commands, assign to each command a different identifier and use the commandIdentifier property on the XCSourceEditorCommandInvocation object to recognize which one the user triggered.

Conclusion

Creating Xcode source editor extension is really easy. If you can improve your workflow and speed up your development by creating a source editor extension, then go ahead and make it happen. Apple introduced a new way for developers to share signed plugins through the Mac App Store so that you can release your work and watch other developers benefit from it.

You can find the source code of the example of this tutorial on GitHub.

2016-07-11T16:45:09.000Z2016-07-11T16:45:09.000ZPatrick Balestra

How to Create an Xcode Source Editor Extension

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

Introduction

Xcode is the main IDE (Integrated Development Environment) used by thousands and thousands of developers every day. It is an awesome tool, but sometimes you want to customize some of its features and behaviors to better fit your workflow.

Until Xcode 7, it was possible to inject code into Xcode at runtime to create plugins. Plugins could be submitted and distributed through a great app called Alcatraz. This is no longer possible in Xcode 8.

Xcode 8 validates each library and bundle to prevent malicious code from running without your permission. When Xcode starts, previously installed plugins with Alcatraz are not loaded anymore. Not everything is lost though, Apple also announced at WWDC the possibility to develop Xcode source editor extensions so that everyone can extend existing source editing features. Let's take a look about what we can achieve with such extensions.

1. Getting Started

Xcode 8 source editor extensions are a first step in the right direction. If you have been working with Xcode for a while, you may have found yourself in a situation where you wished that a specific task could be automated within Xcode. Source editor extensions allow third party applications to modify a source file, which is exactly what you need to speed up your workflow.

At this moment, extensions can only interact with the source code. This means that not every plugin available through Alcatraz can be replaced by a source editor extension. But who knows what the future brings.

It is important to understand that each extension must be contained in a macOS app. You could, for example, add preferences and explanations about what the extension does in the macOS app and distribute it through the Mac App Store. Also note that each extension runs in a separate process. If the extension crashes, it won't crash Xcode. Instead, it will display a message that the extension was not able to finish its work.

Furthermore, extensions don't have a user interface and they can only modify the code directly when the user invokes your command. They can't, for example, run in the background.

I recommend watching the WWDC 2016 session about source editor extensions. Not only does it explain how to get started developing Xcode source editor extensions, it also shows tips and shortcuts to speed up your development.

2. Overview

In this tutorial, we are going to develop an extension that cleans up the closure syntax in Swift. Xcode autocompletes a closure syntax with the parentheses, but they can be omitted for brevity. This is a task that can be easily be automated by wrapping it into a source editor extension.

The shorter explanation of what we are going to develop is an extension that transforms any closure to the simpler and cleaner syntax. Take a look at the example below.

3. Project Setup

It goes without saying that this tutorial requires Xcode 8. You can download it from Apple's developer website. It runs on both OS X 10.11 and macOS 10.12.

Create a new OS X project of type Cocoa Application and give it the name CleanClosureSyntax. Make sure that you have set the language of the project to Swift. We will use the new Swift 3 syntax in this tutorial.

Create A New Cocoa Application Project in Xcode 8

We will leave the macOS app empty for now and we can focus on creating the Xcode source editor extension. From the File menu, choose New > Target.... In the left sidebar, choose OS X and select Xcode Source Editor Extension from the list.

Add a New Target of Type Xcode Source Editor Extension

Click Next and set Product Name to Cleaner. A new target will be created for you. Click Activate if Xcode asks you if the newly created Scheme should be activated.

4. Project Structure

Let's first analyze what Xcode just created for us. Expand the Cleaner folder to see its contents.

Xcode Project Contents and Layout

We won't modify SourceEditorExtension.swift in this tutorial, but it can be used to further customize your extension. The extensionDidFinishLaunching() method is called as soon as the extension is launched so that you can perform any initialization if needed. The commandDefinitions property getter can be used if you want to dynamically show or hide certain commands.

SourceEditorCommand.swift is the hear of the extension. This file is where you will implement the logic for the extension. The perform(with:completionHandler:) method is called when the user launches your extension. The XCSourceEditorCommandInvocation object contains a buffer property, which is used to access the source code in the currently selected file. The completion handler should be called with value nil if everything went well, otherwise pass it an NSError instance.

5. Implementing the Extension

Now that the project contains all the required targets, we are ready to start writing the extension. To recap, we want to remove the parentheses from any closure in a Swift file. This can be done in three steps:

  • find the lines that contain a closure
  • remove the two parentheses from that particular line
  • substitute back the modified line

Let's get started.

We can use a regex (regular expression) to parse each line of code and see if it contains a closure. You can refer to Akiel's tutorial about Swift and regular expressions if you want to learn more about regular expressions. You can use RegExr to test your regular expressions. Take a look at the following screenshot to see how I tested my regex.

Regex to Parse A Closure Syntax

Open SourceEditorCommand.swift and modify the perform(with:completionHandler:) method to look like this:

Find Lines With Closure Syntax

We first create and array of Int values that will contain the line indexes of the modified lines. This is because we don't want to substitute all the lines. We want to replace only the lines that we modify.

We enumerate over all the lines of the invocation.buffer object and we try to find a match for the RegularExpression object. If I remove the escaping characters from the regex, it looks like the following:

This regex matches when a string has the following characteristics:

  • It has a curly open bracket ({), which is followed by 0 or more characters, except a new line character (\n).
  • An open parenthesis (() must be found again, followed by 0 or more characters. This part should contain the parameters of the closure.
  • We then need to find a closing parenthesis ()), followed by 0 or more characters, which are the optional return types.
  • Finally, the in keyword should be found.

If the RegularExpression object fails to find a match (for example, if the regex is not valid), we call the completionHandler with the error as a parameter. If a string that matches all these conditions is found on a line, we have correctly localized a closure.

Clean Up Syntax

When a match is found, we call a utility method on NSString that removes the parentheses. We also need to pass in the range of the match to avoid removing some other parentheses outside of the closure.

Update Lines

The last part of code checks that at least a line was changed. If this is true, we call setArray() to substitute back the new lines and the correct indexes. The completion handler is called with the value nil so that Xcode knows that everything went well.

We still have to implement the remove(characters:range:) method on NSString. Let's add this extension at the top of file.

This method calls replacingOccurrences(of:with:range:) on NSString for each character that we want to remove.

6. Testing

Xcode 8 comes with a great solution to test extensions. First of all, if you are running OS X 10.11 El Capitan, open Terminal, execute the following command, and restart your Mac.

After doing this, build and run your extension by selecting the appropriate scheme. When it asks which app to run, search for Xcode and make sure to select the beta version of Xcode 8. A new Xcode version will be launched with the application icon grayed out so that you can recognize in which instance of Xcode you are testing the extension.

In the new Xcode instance, create a new project or open an existing one, and go to Editor > Clean Closure > Source Editor Command. Make sure to have at least one closure in the currently focused Swift file to see the result. As you can see in the following animation, our extension works.

The Final Result

Source Editor Command is the default name for a command. You can modify it in the Info.plist file of the extension. Open it and change the string to Clean Syntax.

We can also assign a shortcut to automatically invoke the Clean Syntax command. Open Xcode's Preferences and select the Key Bindings tab. Search for Clean Syntax and the command will appear. Click to the right of it and press the shortcut you would like to use, for example, Command-Alt-Shift-+. You can now go back to the source file and press that shortcut to invoke it directly.

Xcode Preferences to Set a Key Binding for an Extension Command

7. Tips and Tricks

Xcode 8 and source editor extensions are still in beta at the time of writing. The following tips can help you debug some issues you may be running into.

If your extension is not selectable in the Xcode testing instance, kill the com.apple.dt.Xcode.AttachToXPCService process and run the extension again.

Xcode Has A Process That You Can Kill if the Extension Is No Visible

Only substitute back the lines that you modify in the buffer. This makes the extension run faster and it will have less chances to be killed by Xcode. The latter can happen if Xcode believes a command of your extension is taking too long.

If you want to show multiple commands, assign to each command a different identifier and use the commandIdentifier property on the XCSourceEditorCommandInvocation object to recognize which one the user triggered.

Conclusion

Creating Xcode source editor extension is really easy. If you can improve your workflow and speed up your development by creating a source editor extension, then go ahead and make it happen. Apple introduced a new way for developers to share signed plugins through the Mac App Store so that you can release your work and watch other developers benefit from it.

You can find the source code of the example of this tutorial on GitHub.

2016-07-11T16:45:09.000Z2016-07-11T16:45:09.000ZPatrick Balestra

How to Use Jscrambler 4 to Protect Your Application's Integrity

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

In recent years, as a platform-independent language, JavaScript has found its way to a wide array of uses, ranging from mobile applications to HTML5-based games and Node.js servers. Long gone are the days when you only used JavaScript for special effects and form validation.

This development is good both for developers and for consumers, who get faster updates to their applications regardless of the platform they are on. 

But it also raises questions about security. 

How can we make sure our applications run as intended? How do we enforce our licenses? And what about piracy?

In this tutorial, we will look at the most common threats to your JavaScript applications and how you can protect against them. We will also look at the steps in making Jscrambler 4.0 a part of your development workflow to easily keep your JavaScript applications secure.

Secure the Communication Between Your Client and Server

As JavaScript is mostly used online, the natural place to start is the connectivity between the application running on your users' devices and your server.

First, let me get this out of the way: no matter how good protection you add on the client side, you always need to start with the assumption that the client can be compromised. Some go as far as to say that you have to treat the client as malicious. 

Fundamentally, the reason for this is that no matter how well you secure your client, the HTTP communication between the JavaScript client and your server can always be tampered with, with the help of request-sniffing tools or even custom-made clients that use your server's protocols. 

So, if your application talks to a server, before adding any other form of client-side security, start by securing your server as much as possible—just as you would when using a regular HTML interface.

1. Validate Your Data

You can think of securing your server through two concepts: data integrity and data confidentiality. 

Data integrity means that the data in your application should remain accurate and consistent during its lifecycle. Data confidentiality means that your users' data should stay secure, and third parties should never get access to it.

While you should do parameter validation already in the JavaScript client, that won't prevent hackers from sending malformed or even malicious data to your server. After all, someone looking to break your server probably won't even use your UI!

So, when working with a JavaScript application, all the regular server-side validations, from escaping HTML characters to checking that attributes are of the correct type, still apply.

Sometimes, the data sent in is correctly formatted but doesn't make sense in the application's state—for example, when a player submits an impossibly high score. You can protect your server against situations like these by using sanity checks and placing as much of the application's logic on the server as possible. 

2. Keep Your Data Secure

Another part of securing the client-server communication is making sure that all user-specific data stays confidential and accessible by only the authorized user. 

The first step is to use SSL in all communication between your JavaScript client and your server to prevent others on the internet from spying on the data passed between the two.  

Next, you'll need to validate that the requests are indeed coming from the correct user. The details for how to best do this depend on your application. In web-based applications, nonces are a useful technique, whereas in a game's context, OAuth authentication might be a more natural approach.

Just keep in mind that you should never store sensitive information such as passwords or API keys in your client. It's a good idea to think of your server as an API that can be used by the JavaScript client but also other clients on the internet.

You Can't Check Everything on the Server

While the checks mentioned above apply to every type of application, when more complexity is added to the client, some verifications become hard to do.

In multiplayer games, for example, running all the logic through your server will work well as long as the game is simple and you only have a limited number of players. But as the active user base grows, the load on the server will make you consider the possibility of moving some of the processing to the client. The same happens if your game logic is so complex that simulating it on the server would take up a lot of resources.

That's where the boundaries get blurred. 

While the idea of never trusting the client sounds good, in practice you'll have to set a threshold, saying "this is how much I trust my client" and only do sanity checks on the server. If some of the player's actions also affect other players, that's where you need to involve the server more, leaving the spots where the user can harm only his or her own experience to the client to handle.

And what about the many JavaScript use cases where you don't have a server, or where placing the application logic on the server doesn't make sense, such as mobile apps, HTML5 streaming players, and map applications?

Finally, it's good to keep in mind that no matter how well you secure your server, your JavaScript client is always exposed. So, unless you add some kind of protection to it, it's very easy for an attacker (Man-in-the-Browser or data exfiltration attacks, for example) to gain access to sensitive data, or to modify the user experience.

Protect Your JavaScript

As a dynamic language, JavaScript can be modified in the browser using basic tools such as the browser's built-in debugger. If you know what you are doing, you can replace parts of the code and change the application's behavior on the fly.

As we saw above, you should make sure invalid data never makes it to the database on your server. But some changes are more restricted than this. A malware plugin might add new buttons to your application to lure the user to an external site. Or the user might hack the client to see more of the game without playing it.

Changes like this will not break your entire application, but they will change the way the user experiences it. In the case of malware, this can also pose a serious threat to the user's privacy.

Because JavaScript is an interpreted language, this is impossible to prevent entirely. A dedicated hacker will always find a way to get past the obstacles, just as a burglar can break any lock. But we can make breaking in so hard that most users will use proper methods (such as getting good at your game) rather than hack the application.

This is where Jscrambler can help you. 

1. Make Your JavaScript Hard to Hack

Jscrambler is a JavaScript security platform that aims to make sure JavaScript applications are executed the way they were developed to be.

Jscrambler homepage

To give Jscrambler a try, visit its homepage and sign up for a free trial. If you find it lives up to your expectations, you can later pick one of its paid plans.

When signed in, if there is some text saying "A new version of Jscrambler is now available" at the top of the page, it means you're still seeing the old version. Click on Try it now.

A new version of Jscrambler is now available

Jscrambler 4 organizes your work in applications, each of which can consist of one or more JavaScript files. So next, you'll see the screen for selecting the application to work on. 

Select the application to work on

If you want to test the functionality using a JavaScript application of your own, click on Create App

For now, however, let's choose Playground. In this mode, you'll get to try all transformations on an example script, while the transformations you can apply to your actual application are limited by your subscription level.

On the left, you'll see the File Tree, a list of files in your application, and an Add button for importing or creating new files. In the playground, the Add button is disabled.

On the right, there is a menu for picking the Language Specifications and Application Mode for your app. Jscrambler uses them to ensure the transformed code will work in your selected environment, taking its limitations and possibilities into account.

We'll now go with ES5 and a basic Web Browser App.

Select the file to transform

Click on the filename (clock.js) to start working on it.

The file's contents will be shown in the middle of the screen: the source code on the left and the version transformed by Jscrambler on the right.

Source code view

Next, select the Code Transformations tab on the right to reveal a list of available transformations. Jscrambler allows you to choose the transformations you find relevant to your code. You can even use annotations in your code to change the way some of the code gets transformed. That can be handy in performance-critical code blocks, for example rendering functions in games.

To test the transformations, select them one at a time. Then click on Protect App at the bottom of the window to create a new version of your transformed code.

Next to the button, you'll see a meter presenting the effects of these changes on your JavaScript code.

Information about the protection

In the meter, you'll see three icons, representing the cost, resilience, and potency (going from left to right in the screen shot above) of the transformations you have selected for your application.

To get started, check the checkbox in front of Control Flow, and then click on Protect App.

Code after applying control flow transformation

The Control Flow Flattening is one of the powerful new transformations added in Jscrambler 4. It flattens the script's control flow so that it becomes hard for a person reading the code to follow the logic of your application. 

Next, continue by selecting some more obfuscation options. As you add more, you'll notice how your code gets more and more difficult to read—and thus edit without breaking its functionality.

Also, when you click on Protect App again, even without changing the settings, you'll notice that the contents of the protected script change every time. 

Jscrambler's transformations are polymorphic, making sure the transformations produce a different output every time. This way, even if someone were able to hack the current version, next time you run your code through Jscrambler, those changes would no longer work.

2. Make Your Application Protect Itself

So far, we have talked about ways to make sure your application works as expected by preventing both the user and outsiders from modifying your source code. But that's not the only threat to your application you need to worry about. 

As JavaScript has become popular in standalone and mobile applications, piracy has become a real issue also in this realm.

I'm sure we've all clicked "View Source" to learn how to do a cool new effect or trick, and adapted what we've learned to our websites. That's not what I'm talking about here. 

Instead, let's assume you created a popular mobile game in HTML5 and JavaScript. Thanks to JavaScript's portability, you can use the same code on Android, iOS, and other platforms, and reach a larger audience without the extra work from writing native versions for every environment. But there's a problem: anyone can copy your JavaScript code, make a few modifications, and sell it as their own!

The transformations in the previous step help prevent this by making the code hard to read and reverse engineer. In addition to them, Jscrambler adds code traps, functionality that makes the code protect itself.

Let's take a look at some of them.

In Jscrambler, in the list of transformations, you'll find a section titled Code Locks.

Code Locks

The transformations in this section add yet another layer of security to your JavaScript application. 

Using them, you can limit the execution of your code to a given set of browsers, a time frame (useful for demos that shouldn't be runnable after the preview period is over), on a given domain (usually yours), and a particular operating system.

One more powerful feature for protecting your code is Client-side RASP (Runtime Application Self-Protection). It modifies your JavaScript code, making it defend itself from runtime tampering. For example, the application will stop working if anyone tries to open the debugger.

Finally, in the Optimization section, select Minification to minify the code and make the file smaller.

Protected code with all obfuscation and optimization flags turned on

Then, click on Protect App, followed by Download App to download the source code and use it in your application.

Download App

Jscrambler keeps track of your transformation history, so you can always go back to an earlier version.

3. Use Templates to Make Your Work Easier

As we have seen, configuring your protection level by selecting checkboxes one by one is straightforward. But you can still speed up your workflow by grouping your common combinations of transformations into templates.

Once you have found a set of transformations that you'd like to store for future use, click Create Template at the bottom of the Application Settings section.

Jscrambler will prompt you to give your template a name and description. 

Create Template

Type in something descriptive for the future, and click on Save Template

You can also use one of the templates already available on the Your Templates tab:

Readymade transformations

Move your mouse pointer above the template names to read more about them and understand when they make sense. Then click on them to see what transformations they apply to your code.

4. Make Jscrambler a Part of Your Development Workflow

So far, we have covered some ways in which Jscrambler can help you protect your application using the web UI. While the interface is intuitive, as your application grows, you'll want something more straightforward.

Also, as I mentioned earlier, Jscrambler is polymorphic, generating a different output every time. So, it's useful to run the tool again now and then, even if there are no changes to the specific files.

To do this, let's look at Jscrambler's command-line tool.

First, download and install the command-line tool using npm. On your command line, type:

Once the installation completes, go back to your applications in the Jscrambler admin. 

Notice that to use the command-line tool, you'll need to use an actual application instead of the playground script. So, if you don't have an application yet, create one now.

After selecting the transformations you want to apply, click on the download button at the top right corner of the page. This will download your settings to your computer as a JSON file.

Download your application settings

Copy the JSON file to your project. Don't commit it to version control as the file contains your API key and secret for using the Jscrambler API.

Then, run the jscrambler command to execute the transformations on your JavaScript files. 

For example, if you only have one file, test.js, you can run the following command:

In the command, you passed in the JSON file containing your application settings using the -c parameter, followed by the output file (-o test.protected.js), and finally the JavaScript file to protect.

To run the protection for all JavaScript files in the project directory, you can use something like this:

In this example, instead of an output file, you define a directory (protected) where Jscrambler will place the results of the protection.

Now, you don't have to go back to Jscrambler's web UI every time you make changes to your JavaScript files. This will make it more likely that you'll remember the step, and thus keep your application secure.

As a further improvement, you could also set up the Jscrambler task to run whenever there are changes in your scripts, for example using Grunt. Or it could even be a task on your continuous integration server, running whenever a new version of the code is committed.

Conclusion

Jscrambler provides cutting-edge tools to make it hard for crackers, cheaters, and malware to inject unwanted functionality to your application or change your application's variables. It also makes it hard for others to copy your code and redistribute it as their own.

Security is a complex field with multiple different threats to consider. So, when your JavaScript code talks to a server, the best solution is to use a combination of server development best practices, robust parameter validation, and a JavaScript security platform such as Jscrambler to make the client tamper-proof. This way, you can prevent most of the attacks against your application's integrity already in the client and make sure your customers get the experience you designed for them to have.

Jscrambler can also help you defeat Man-in-the-Browser (MitB) attacks and fraud, bots, 0-day threats, and APT (Advanced Persistent Threats) by detecting changes made to the DOM and giving you all the information you need to stop these attacks. For more information, please contact support@jscrambler.com.

For more information about Jscrambler, its new features, and latest updates, you can also visit the Jscrambler website.

2016-07-13T14:00:05.000Z2016-07-13T14:00:05.000ZJarkko Laine

An Introduction to NativeScript

$
0
0

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:

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:

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.

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:


CordovaReact NativeNativeScript
CreatorNitobi; Later purchased by Adobe SystemsFacebookTelerik
UIHTMLUI components are translated to their native counterpartsUI components are translated to their native counterparts
Can test onBrowser, emulator, deviceEmulator, deviceEmulator, device
Code withHTML, CSS, JavaScriptUI components, JavaScript, subset of CSSUI components, subset of CSS, JavaScript
Native functionality accessThrough pluginsNative modulesNative API access through JavaScript
Deploys toAndroid, iOS, Ubuntu, Windows, OS X, Blackberry 10Android and iOS. Windows Universal and Samsung Tizen coming soonAndroid and iOS. Windows Universal coming soon
JavaScript libraries and frameworkAny front-end library or framework (e.g. Angular, Ember)Any library that doesn't depend on the browserAny library that doesn't depend on the browser
Coding patternAny front-end framework can be used to structure the codeThe UI markup, JavaScript and CSS are all lumped together in a single file by default
MVVM/MVC pattern
How JavaScript code is executedWebViewJavaScriptCore Engine to execute app code on both Android and iOS
Webkit JavaScriptCore engine to execute app code on iOS and Google's V8 JavaScript engine on Android

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:

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.

2016-07-15T12:15:03.000Z2016-07-15T12:15:03.000ZWernher-Bel Ancheta

An Introduction to NativeScript

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

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:

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:

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.

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:


CordovaReact NativeNativeScript
CreatorNitobi; Later purchased by Adobe SystemsFacebookTelerik
UIHTMLUI components are translated to their native counterpartsUI components are translated to their native counterparts
Can test onBrowser, emulator, deviceEmulator, deviceEmulator, device
Code withHTML, CSS, JavaScriptUI components, JavaScript, subset of CSSUI components, subset of CSS, JavaScript
Native functionality accessThrough pluginsNative modulesNative API access through JavaScript
Deploys toAndroid, iOS, Ubuntu, Windows, OS X, Blackberry 10Android and iOS. Windows Universal and Samsung Tizen coming soonAndroid and iOS. Windows Universal coming soon
JavaScript libraries and frameworkAny front-end library or framework (e.g. Angular, Ember)Any library that doesn't depend on the browserAny library that doesn't depend on the browser
Coding patternAny front-end framework can be used to structure the codeThe UI markup, JavaScript and CSS are all lumped together in a single file by default
MVVM/MVC pattern
How JavaScript code is executedWebViewJavaScriptCore Engine to execute app code on both Android and iOS
Webkit JavaScriptCore engine to execute app code on iOS and Google's V8 JavaScript engine on Android

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:

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.

2016-07-15T12:15:03.000Z2016-07-15T12:15:03.000ZWernher-Bel Ancheta

Kickstart Your iOS Career With These 4 Courses

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

Do you want to develop apps for iOS devices?

If so, these four courses will give you the solid foundation you need. With expert guidance from Envato Tuts+ instructor Derek Jensen, you'll learn all the fundamentals of Swift 2, the programming language that developers use to create iOS apps. Then you'll move on to more complex topics like unit testing and creating Apple TV apps.

1. Up and Running With Swift 2

Swift is a programming language designed specifically for creating iOS, OS X and watchOS apps. The designers of Swift drew from the best of the new generation of languages, while also building on the success of C and Objective-C. Swift has a powerful type system for safe programming and adds many features to make the lives of programmers easier. 

This course will start from the foundations to give you a thorough understanding of the Swift language. It will introduce Swift's types, control flow and object-orientation syntax, with a special emphasis on the features that make Swift unique. This course will also highlight some of the great new features that have come to Swift in version 2.

2. iPhone App Development With Swift

Whether you are a seasoned iOS developer or just getting started, it pays to learn how to use the Swift programming language for your next app. Swift is the future of application development for Apple platforms, and this course is the perfect way to get started.

In this course you will learn how to use Swift to build an iPhone app from scratch. You'll learn the basic concepts behind creating any iPhone app with Swift, and then you’ll build a simple app to practice your skills.

3. Unit Testing With Swift and XCTest

The process of creating an iOS app doesn't stop with the creation of functional code. At some point you will need to verify that the code you have written satisfies all of your project's requirements. In this course you'll learn how to do just that for your iOS and Swift code.

Xcode 6 has a built-in testing framework called XCTest that will allow you to quickly and easily write unit tests in order to verify your code. Get started now and learn how to successfully write basic tests and verify your code using XCTest.

4. Create an Apple TV App With Swift

As time goes on in the world of development targeting the Apple platform, we continue to find new and exciting ways to engage consumers. The newest Apple platform allows us to engage our audience while they are sitting in their living room, or anywhere with a television. With Apple TV, you can now write apps that inform and entertain your users in a whole new way.

In this course, you'll learn the basics of creating a tvOS app that can run on an Apple TV. You'll learn to use Swift to create a tvOS app: an Envato Tuts+ magic 8-ball that helps users decide the next language they want to learn on Envato Tuts+.

Start Learning With a Free Trial

You can take all of these and more app development courses with a free 10-day trial of our monthly subscription. So get started today, and kickstart your iOS career with some solid Swift programming skills.

2016-07-19T15:39:03.000Z2016-07-19T15:39:03.000ZAndrew Blackman

Android From Scratch: How to Store Application Data Locally

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

When it comes to persisting application data locally, Android developers are definitely spoiled for choice. In addition to direct access to both the internal and external storage areas of an Android device, the Android platform offers SQLite databases for storing relational data, and special files for storing key-value pairs. What's more, Android apps can also use third-party databases that offer NoSQL support.

In this tutorial, I'll show you how to make use of all those storage options in your Android apps. I'll also help you understand how to pick the most appropriate storage option for your data.

1. Storing Key-Value Pairs

If you are looking for a quick way to store a few strings or numbers, you should consider using a preferences file. Android activities and services can use the getDefaultSharedPreferences() method of the PreferenceManager class to get a reference to a SharedPreferences object that can be used to both read from and write to the default preferences file.

To start writing to the preferences file, you must call the edit() method of the SharedPreferences object, which returns a SharedPreferences.Editor object.

The SharedPreferences.Editor object has several intuitive methods you can use to store new key-value pairs to the preferences file. For example, you could use the putString() method to put a key-value pair whose value is of type String. Similarly, you could use the putFloat() method to put a key-value pair whose value is of type float. The following code snippet creates three key-value pairs:

Once you've added all the pairs, you must call the commit() method of the SharedPreferences.Editor object to make them persist.

Reading from a SharedPreferences object is a lot easier. All you need to do is call the appropriate get*() method. For example, to get a key-value pair whose value is of type String, you must call the getString() method. Here's a code snippet that retrieves all the values we added earlier:

As you can see in the above code, as the second parameter, all the get*() methods expect a default value, which is the value that must be returned if the key is not present in the preferences file.

Note that preferences files are limited to strings and primitive data types only. If you wish to store more complex data types or binary data, you must choose a different storage option.

2. Using an SQLite Database

Every Android app can create and make use of SQLite databases to store large amounts of structured data. As you might already know, SQLite is not only light-weight, but also very fast. If you have experience working with relational database management systems and are familiar with both SQL, which is short for Structured Query Language, and JDBC, which is short for Java Database Connectivity, this might be your preferred storage option.

To create a new SQLite database, or to open one that already exists, you can use the openOrCreateDatabase() method inside your activity or service. As its arguments, you must pass the name of your database and the mode in which you want to open it. The most used mode is MODE_PRIVATE, which makes sure that the database is accessible only to your application. For example, here's how you would open or create a database called my.db:

Once the database has been created, you can use the execSQL() method to run SQL statements on it. The following code shows you how to use the CREATE TABLE SQL statement to create a table called user, which has three columns:

Although it's possible to insert new rows into the table using the execSQL() method, it's better to use the insert() method instead. The insert() method expects a ContentValues object containing the values for each column of the table. A ContentValues object is very similar to a Map object and contains key-value pairs.

Here are two ContentValues objects you can use with the user table:

As you might have guessed, the keys you pass to the put() method must match the names of the columns in the table.

Once your ContentValues objects are ready, you can pass them to the insert() method along with the name of the table.

To query the database, you can use the rawQuery() method, which returns a Cursor object containing the results of the query.

A Cursor object can contain zero or more rows. The easiest way to loop through all its rows is to call its moveToNext() method inside a while loop.

To fetch the value of an individual column, you must use methods such as getString() and getInt(), which expect the index of the column. For example, here's how you would retrieve all the values you inserted in the user table:

Once you have fetched all the results of your query, make sure that you call the close() method of the Cursor object in order to release all the resources it holds.

Similarly, when you have finished all your database operations, don't forget to call the close() method of the SQLiteDatabase object.

3. Using the Internal Storage

Every Android app has a private internal storage directory associated with it, in which the app can store text and binary files. Files inside this directory are not accessible to the user or to other apps installed on the user's device. They are also automatically removed when the user uninstalls the app.

Before you can use the internal storage directory, you must determine its location. In order to do so, you can call the getFilesDir() method, which is available in both activities and services.

To get a reference to a file inside the directory, you can pass the name of the file along with the location you determined. For example, here's how you would get a reference to a file called alice.csv:

From this point on, you can use your knowledge of Java I/O classes and methods to read from or write to the file. The following code snippet shows you how to use a FileOutputStream object and its write() method to write to the file:

4. Using the External Storage

Because the internal storage capacity of Android devices is usually fixed, and often quite limited, several Android devices support external storage media such as removable micro-SD cards. I recommend that you use this storage option for large files, such as photos and videos.

Unlike internal storage, external storage might not always be available. Therefore, you must always check if it's mounted before using it. To do so, use the getExternalStorageState() method of the Environment class.

Once you are sure that the external storage is available, you can get the path of the external storage directory for your app by calling the getExternalFilesDir() method and passing null as an argument to it. You can then use the path to reference files inside the directory. For example, here's how you would reference a file called bob.jpg in your app's external storage directory:

By asking the user to grant you the WRITE_EXTERNAL_STORAGE permission, you can gain read/write access to the entire file system on the external storage. You can then use well-known public directories to store your photos, movies, and other media files. The Environment class offers a method called getExternalStoragePublicDirectory() to determine the paths of those public directories.

For example, by passing the value Environment.DIRECTORY_PICTURES to the method, you can determine the path of the public directory in which you can store photos. Similarly, if you pass the value Environment.DIRECTORY_MOVIES to the method, you get the path of the public directory in which movies can be stored.

Here's how you would reference a file called bob.jpg in the public pictures directory:

Once you have the File object, you can again use the FileInputStream and FileOutputStream classes to read from or write to it.

Conclusion

You now know how to make the most of the local storage options provided by the Android SDK. Regardless of the storage option you choose, read/write operations can be time-consuming if large amounts of data are involved. Therefore, to make sure that the main UI thread always stays responsive, you must consider running the operations in a different thread.

To learn more about saving application data locally, refer to the official data storage API guide.

2016-07-20T12:50:18.000Z2016-07-20T12:50:18.000ZAshraff Hathibelagal

Cost-Effective Mobile Solutions: Think Small Business, Not Enterprise

$
0
0

Introduction

Although the term "enterprise apps" sounds as if these applications must be used exclusively by large corporations, in actuality small businesses can benefit from developing such apps as well. But certainly, the cost of app development can be a barrier to entry for small and independent businesses.

In this tutorial, I'll offer some ideas for developing an enterprise app that not only brings key benefits but is actually affordable and achievable for small companies.

Why Enterprise Apps?

ScienceSoft Cost-effective Mobile Development - Screenshot of Banking Mobile App

Let's take the example of a local electrical services company. Its business is made tougher due to the number of large and mid-sized competitors: not only do they have to be good at their job, they must excel in order to sustain customers and grow. The company’s employees usually spend 90% of their working time in the field, which makes it difficult for their managers to control the progress, and for the employees to get by without job-specific desktop apps.

Enterprise mobile applications address these challenges and partially make up for the human resources small businesses don’t have yet. Apart from allowing tracking of remote activities in the field, these apps can facilitate communication and contain all kinds of knowledge bases or configuration guidelines.

Enterprise apps let employees perform their responsibilities faster and more effectively, keeping customers satisfied and loyal. They also can provide managers with a clearer picture of what's happening and how productive the team is.

Overall, an enterprise mobile app organizes small businesses’ workflows, increases productivity and, by allowing employees to take advantage of useful data and promptly respond to urgent events, increases customer conversion rates too, growing sales.

How to Cut Costs of Mobile App Development

Keep It Simple

ScienceSoft Cost-effective Mobile Development - Screenshot of Simple Mobile App

The key secret to initially launching an enterprise app cost-effectively is reducing app functionality to only one or two features.

If you take away only one thing from today's article, please remember that.

Choose only the processes that you believe should be improved in the first place and develop your app around useful features for these particular processes. Consequently, development costs will be within your reach.

This certainly doesn’t mean that you will be stuck with such basic functionality forever. Iterative software development is always best. 

Once you get the basic features developed and put the app into service, you can just wait for a couple of months until it proves profitable and provides you budget for the next release on its own.

Outline Your Requirements First

ScienceSoft Cost-effective Mobile Development - Screenshot of Team Talking Over Tablet

One you've identified the most important features to build into your mobile app, detail your requirements around those. 

Even if your internal teams have good product management skills and you're thoughtful about cost cutting, choosing the wrong development vendor can lead to problems. Frankly, it helps to have a mobile development expert to help you.

Before proceeding to the development stage, we advise you to make sure your partner vendor is able to discuss your project in details and will manage the application lifecycle to the very end.

Go Cross Platform

ScienceSoft Cost-effective Mobile Development - Photo Multiple Mobile Devices

Cross-platform mobile development not only makes enterprise applications available for all employees whatever devices they use, but also reduces costs significantly.

Today’s hybrid and cross-platform development frameworks have already caught up with native technologies and offer from 70% (Cordova, Appcelerator) to 100% (Xamarin) native experience for Android, iOS and Windows phones at reasonable prices. 

Development of an application with an average functionality on the hybrid Ionic framework, for instance, can provide you with a slick UX and 85-95% performance compared to developing natively within each framework.

Reuse Your Resources

ScienceSoft Cost-effective Mobile Development - Photo of User on Phone and Tablet

If you’re planning to develop several apps at once, there’s a high chance that you will be able to reuse some features. In other words, if the feature is developed for one of your company's applications, migrate it to your new app's functionality. Think DRY (don't repeat yourself) at the application level.

For instance, you can develop a mobile app with a 3D presentation of your major product—and then make only minimal changes to adjust the presentation to another product you’ll want to bring to the fore in your marketing campaigns. Needless to say, you save both money and time with each new application.

Again, choosing the right vendor has a huge impact on outcomes. The ability to reuse features can be overlooked entirely when your vendor isn’t competent in your business analysis. Other times, your app may be left hanging in the air when it turns out that the vendor can’t perform integration with the systems you have.

Planning and Managing Integration

Integration means making your app freely communicate with your existing business solutions. It does affect development costs, but is basically the same kind of investment in the future as an application itself: you pay once and watch it carry value forward into the future. 

Integrating an app with your existing solutions such as ERP, CRM and CMS allows easy uploading, downloading and interconnection of any and all of your information. This kind of data exchange will speed up the workflow and eradicate tedious re-input tasks for your employees.

Gather Feedback

If successful, your teams and customers will become increasingly reliant on and demanding of your applications. Share your plans with them early on. Ask them for ideas. And integrate their requests into the application over time.

Final Thoughts

ScienceSoft Cost-effective Mobile Development - Cool Photo of Mobile Photography App

As you can see, enterprise applications can be closer to your small business than you thought. Using these guidelines, you can devise a strategy that would help you cut development costs and still build quality mobile applications. ScienceSoft welcomes your further questions on the discussed matters and gladly offers you professional guidance.

Want some guidance? Request a quote from ScienceSoft for your mobile application today.

About ScienceSoft

ScienceSoft is a full-cycle software consulting and development company headquartered in McKinney, Texas, that branches out mobile development as one of its major competencies.

With 11 years of mobile experience, the company has delivered over 300 successful projects and is known for industry-specific solutions for enterprises and mid-size businesses in Healthcare, Telecommunication, Retail, Banking and more domains, featuring such end clients as Burger King, Orange, T-Mobile, Viber and MTV.

Their team of 75 mobile consultants, developers, UX/UI designers and testing specialists provide full-stack services using both native and cross-platform technologies, including Xamarin and Cordova.

ScienceSoft - Customers that Use Our Software

ScienceSoft offers native mobile development on Android, iOS and Windows Phone by developers with experience measured by dozens of projects. Moreover, the company is continuously extending the number of showcase projects in cross-platform mobile development and offers you Xamarin and Cordova mobile development.


ScienceSoft Cost-effective Mobile Development - Chart of ScienceSoft Developer and Their Mobile Experience

About the Author

Andrei  Khomushka

Head of Android Development Department at ScienceSoft. Andrei has over 10 years of experience in programming and designing mobile and web-based solutions. His track record as a project manager includes mobile development for Viber, a VoIP app with 600 mln users worldwide, and Bellator, America’s leading Mixed Martial Arts organization, as well as delivering of the award-winning banking solution for a European bank. 

Envato Tuts+ writer Jeff Reifman also contributed to this article.

Related Links

2016-07-20T14:00:01.000Z2016-07-20T14:00:01.000ZJeff Reifman

Cost-Effective Mobile Solutions: Think Small Business, Not Enterprise

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

Introduction

Although the term "enterprise apps" sounds as if these applications must be used exclusively by large corporations, in actuality small businesses can benefit from developing such apps as well. But certainly, the cost of app development can be a barrier to entry for small and independent businesses.

In this tutorial, I'll offer some ideas for developing an enterprise app that not only brings key benefits but is actually affordable and achievable for small companies.

Why Enterprise Apps?

ScienceSoft Cost-effective Mobile Development - Screenshot of Banking Mobile App

Let's take the example of a local electrical services company. Its business is made tougher due to the number of large and mid-sized competitors: not only do they have to be good at their job, they must excel in order to sustain customers and grow. The company’s employees usually spend 90% of their working time in the field, which makes it difficult for their managers to control the progress, and for the employees to get by without job-specific desktop apps.

Enterprise mobile applications address these challenges and partially make up for the human resources small businesses don’t have yet. Apart from allowing tracking of remote activities in the field, these apps can facilitate communication and contain all kinds of knowledge bases or configuration guidelines.

Enterprise apps let employees perform their responsibilities faster and more effectively, keeping customers satisfied and loyal. They also can provide managers with a clearer picture of what's happening and how productive the team is.

Overall, an enterprise mobile app organizes small businesses’ workflows, increases productivity and, by allowing employees to take advantage of useful data and promptly respond to urgent events, increases customer conversion rates too, growing sales.

How to Cut Costs of Mobile App Development

Keep It Simple

ScienceSoft Cost-effective Mobile Development - Screenshot of Simple Mobile App

The key secret to initially launching an enterprise app cost-effectively is reducing app functionality to only one or two features.

If you take away only one thing from today's article, please remember that.

Choose only the processes that you believe should be improved in the first place and develop your app around useful features for these particular processes. Consequently, development costs will be within your reach.

This certainly doesn’t mean that you will be stuck with such basic functionality forever. Iterative software development is always best. 

Once you get the basic features developed and put the app into service, you can just wait for a couple of months until it proves profitable and provides you budget for the next release on its own.

Outline Your Requirements First

ScienceSoft Cost-effective Mobile Development - Screenshot of Team Talking Over Tablet

One you've identified the most important features to build into your mobile app, detail your requirements around those. 

Even if your internal teams have good product management skills and you're thoughtful about cost cutting, choosing the wrong development vendor can lead to problems. Frankly, it helps to have a mobile development expert to help you.

Before proceeding to the development stage, we advise you to make sure your partner vendor is able to discuss your project in details and will manage the application lifecycle to the very end.

Go Cross Platform

ScienceSoft Cost-effective Mobile Development - Photo Multiple Mobile Devices

Cross-platform mobile development not only makes enterprise applications available for all employees whatever devices they use, but also reduces costs significantly.

Today’s hybrid and cross-platform development frameworks have already caught up with native technologies and offer from 70% (Cordova, Appcelerator) to 100% (Xamarin) native experience for Android, iOS and Windows phones at reasonable prices. 

Development of an application with an average functionality on the hybrid Ionic framework, for instance, can provide you with a slick UX and 85-95% performance compared to developing natively within each framework.

Reuse Your Resources

ScienceSoft Cost-effective Mobile Development - Photo of User on Phone and Tablet

If you’re planning to develop several apps at once, there’s a high chance that you will be able to reuse some features. In other words, if the feature is developed for one of your company's applications, migrate it to your new app's functionality. Think DRY (don't repeat yourself) at the application level.

For instance, you can develop a mobile app with a 3D presentation of your major product—and then make only minimal changes to adjust the presentation to another product you’ll want to bring to the fore in your marketing campaigns. Needless to say, you save both money and time with each new application.

Again, choosing the right vendor has a huge impact on outcomes. The ability to reuse features can be overlooked entirely when your vendor isn’t competent in your business analysis. Other times, your app may be left hanging in the air when it turns out that the vendor can’t perform integration with the systems you have.

Planning and Managing Integration

Integration means making your app freely communicate with your existing business solutions. It does affect development costs, but is basically the same kind of investment in the future as an application itself: you pay once and watch it carry value forward into the future. 

Integrating an app with your existing solutions such as ERP, CRM and CMS allows easy uploading, downloading and interconnection of any and all of your information. This kind of data exchange will speed up the workflow and eradicate tedious re-input tasks for your employees.

Gather Feedback

If successful, your teams and customers will become increasingly reliant on and demanding of your applications. Share your plans with them early on. Ask them for ideas. And integrate their requests into the application over time.

Final Thoughts

ScienceSoft Cost-effective Mobile Development - Cool Photo of Mobile Photography App

As you can see, enterprise applications can be closer to your small business than you thought. Using these guidelines, you can devise a strategy that would help you cut development costs and still build quality mobile applications. ScienceSoft welcomes your further questions on the discussed matters and gladly offers you professional guidance.

Want some guidance? Request a quote from ScienceSoft for your mobile application today.

About ScienceSoft

ScienceSoft is a full-cycle software consulting and development company headquartered in McKinney, Texas, that branches out mobile development as one of its major competencies.

With 11 years of mobile experience, the company has delivered over 300 successful projects and is known for industry-specific solutions for enterprises and mid-size businesses in Healthcare, Telecommunication, Retail, Banking and more domains, featuring such end clients as Burger King, Orange, T-Mobile, Viber and MTV.

Their team of 75 mobile consultants, developers, UX/UI designers and testing specialists provide full-stack services using both native and cross-platform technologies, including Xamarin and Cordova.

ScienceSoft - Customers that Use Our Software

ScienceSoft offers native mobile development on Android, iOS and Windows Phone by developers with experience measured by dozens of projects. Moreover, the company is continuously extending the number of showcase projects in cross-platform mobile development and offers you Xamarin and Cordova mobile development.


ScienceSoft Cost-effective Mobile Development - Chart of ScienceSoft Developer and Their Mobile Experience

About the Author

Andrei  Khomushka

Head of Android Development Department at ScienceSoft. Andrei has over 10 years of experience in programming and designing mobile and web-based solutions. His track record as a project manager includes mobile development for Viber, a VoIP app with 600 mln users worldwide, and Bellator, America’s leading Mixed Martial Arts organization, as well as delivering of the award-winning banking solution for a European bank. 

Envato Tuts+ writer Jeff Reifman also contributed to this article.

Related Links

2016-07-20T14:00:01.000Z2016-07-20T14:00:01.000ZJeff Reifman

Create Your First NativeScript App

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

In the last article, I introduced you to NativeScript. There you learned the basics of NativeScript and how it differs from other mobile development frameworks. This time you'll be getting your hands dirty by creating your first NativeScript app. I'll walk you through the whole process of building an app with NativeScript, from setting up your development environment to running the app on your device. Here's an outline of what I'll discuss:

  1. Setting up NativeScript
  2. Building the app
  3. Running the app
  4. Debugging the app

We'll be specifically running the app on the Android platform. But you can still follow along if you want to deploy to iOS as the code will be pretty much the same. The only differences are in the process for setting up NativeScript and the commands that you execute when running the app.

The completed source code for this app is available from the tutorial GitHub repo.

1. Setting Up NativeScript

To set up NativeScript, you first have to install Node.js. Once Node.js is installed, you can install the NativeScript command-line tool by executing npm install -g nativescript on your terminal. 

The final step is to install the development tool for each platform that you want to deploy to. For Android, this is the Android SDK. For iOS, it's XCode. You can follow the installation guide on the NativeScript website for more detailed instructions on how to set up the necessary software for your development environment.

Once you've set up your environment, execute tns doctor to make sure that your environment is ready for NativeScript development. If you're on Linux or Windows, you'll see something like this if your environment is ready:

There's a note in there that you can only develop for iOS only on Mac OS X systems. This means that if you're on a PC, you'll only be able to deploy to Android devices. However, if you're on Mac, you'll be able to deploy on both iOS and Android platforms.

If you run into any problems during the setup, you can get an invitation to join the NativeScript Slack Community and once you have joined, go to the getting started channel and ask your questions in there.

2. Creating the App

The app that we're going to build is a note-taking app. It will allow the user to create notes, each with an optional image attachment that will be captured with the device camera. The notes are persisted using NativeScript application settings, and can be individually deleted.

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

NativeScript app

Start by executing the following command to create a new NativeScript project:

noter is the name of the project, and com.yourname.noter is the unique app ID. This will be used later on to identify your app once you submit it to the Play or App Store. By default, the tns create command will create the following folders and files for you:

  • app
  • node_modules
  • platforms
  • package.json

You'll typically only have to touch the files inside the app directory. But there are also instances where you might need to edit files inside the platforms/android directory. One such case is when a plugin that you're trying to use doesn't automatically link the dependencies and assets that it needs. 

Next, navigate to the app directory and delete all files except the App_Resources folder. Then create the following files:

  • app.js
  • app.css
  • notes-page.js
  • notes-page.xml

These are the files that will be used by the NativeScript runtime. Just like when building web pages, .css files are used for styling, and .js files for functionality. But for the markup of the app, we use XML instead of HTML. Usually you would create a separate folder for each screen of the app (e.g. login, sign up, or dashboard) and have XML, CSS, and JavaScript files inside each folder. But since this app has only one screen, we created all the files inside the root directory.

If you need more information about the NativeScript directory structure, check out Chapter 2 of the NativeScript Getting Started Guide.

3. The Entry Point File

Open the app.js file and add the following code:

This is the entry point for a NativeScript application. It uses the application module and its start method to specify the module used for the initial page of the app. In this case, we've specified notes-page, which means that the module is notes-page.js, the markup is notes-page.xml, and the styling for the page is notes-page.css. This is a convention used in NativeScript, that all files for a specific page have to have the same name.

4. Adding the UI Markup

Open the notes-page.xml file and add the following code:

When creating app pages in NativeScript, you should always start with the <Page> tag. This is how NativeScript knows you're trying to create a new page. The xmlns attribute specifies the URL to the schema used for the XML file. 

If you visit the schema URL specified, you can see the definition of all the XML tags that you can use within NativeScript. The loaded attribute specifies the function to be executed once the page is loaded. We'll take a look at this function definition later on in the notes-page.js file.

By default, the app header only contains the title of the app. If you wanted to add other UI components, you'd need to redefine it by using <Page.actionBar>. Then inside you define the things that you want to see in the header. The title is specified by using <ActionBar> and setting its title attribute to the page title that you want. 

Below we've used the mustache syntax to output the value of app_title defined in the notes-page.js file. This is how you output values that are bound to the page.

To define buttons, first use <ActionBar.actionItems> as the parent, and each <ActionItem> will be the buttons that you want to define. The tap attribute specifies a function to be executed when the button is tapped, while os.position and android.position are the positions of the button in iOS and Android. 

To specify the button text, you could use the <ActionItem>'s text attribute. However, NativeScript doesn't currently allow changing the text color of the button through CSS. That's why instead we've used <ActionItem.actionView> to define the content of the button and to set its text color.

Next is the actual page content. You can arrange the different elements by using one or more of the layout containers. Below we've used two of the available layouts: StackLayout and GridLayout

StackLayout allows you to stack all the elements inside of it. By default, the orientation of this layout is vertical, so that each UI component is stacked below the last. Think of lego bricks with a downward flow. 

On the other hand, GridLayout allows you to arrange elements in a table structure. If you've ever used Bootstrap or other CSS grid frameworks then this should seem natural to you. The GridLayout lets you define rows and columns among which each UI component can be placed. We'll take a look at how this is implemented later on. For now, let's move on to the code.

First, let's define the form for creating a new note. Just like in HTML, you can define attributes such as id and cssClass (equivalent to HTML's class attribute). The id attribute is attached to an element if you want to manipulate it from code. In our case, we want to animate the form later on. cssClass is used to specify the CSS class that you will use to style the element. 

Inside the form is a text field for entering the note title, a button for attaching an image, the selected image, and a button for saving the note. The image element is only visible if the attachment_img has a truthy value. That will be the case if an image was previously attached. 

Next is the list that shows the notes that were already added by the user. Lists are created by using the ListView component. This accepts items as a required attribute. The value can either be a plain array or an observable array. 

If you do not need to perform any form of update (e.g. deleting or updating a field) to each item in the array, a plain JavaScript array will do. Otherwise, use an observable array which allows you to perform updates to the array and have it automatically reflected to the UI. We'll take a look at how an observable array is defined later on. 

Also note that a ListView can have an itemTap attribute, which allows you to specify the function to be executed when an item in the ListView is tapped. But in this case we haven't really added it since we don't need to perform any action when an item is tapped.

The items in the ListView can be defined using <ListView.itemTemplate>. Here we're using a <GridLayout> to create two rows and two columns. The columns attribute is used to specify how many columns you want in each row. 

In this case, *,* means that there are two columns, each taking up an equal amount of the available space in the current row. So if the whole row has a total width of 300 pixels, each column will be 150 pixels wide. So basically each * represents one column, and you use a comma to separate each of them. 

The rows attribute works similarly, but controls the amount of space used by a single row. auto means it will only consume the amount of space needed by the children of each row. 

After defining the columns and rows in the GridLayout, you still have to specify which of its children belongs to which row and column. The first row contains the title of the item (1st column) and the delete button (2nd column). The second row contains the image that was attached to the item (1st column). The row and columns are specified by using the row and col attribute for each element. 

Also notice the use of horizontalAlignment and verticalAlignment. You can think of this as the NativeScript equivalent of HTML's text-align attribute. But instead of text, we're aligning UI components. horizontalAlignment can have a value of right, left, center, or stretch, while verticalAlignment can have a value of top, bottom, center, or stretch. Most of these are self-explanatory, except for stretch, which stretches to take up the available horizontal or vertical space. 

In this case, horizontalAlignment and verticalAlignment are used to center the image both horizontally and vertically inside its column. And horizontalAlignment is used on the delete button to align it to the right-most part of the second column.

We haven't specified an itemTap attribute for the ListView. Instead, we want to attach a delete action that will be executed whenever a delete button inside a list item is tapped. Each item has an index attribute, which we're passing as a custom attribute for the delete button. This is the unique key used for identifying each item so that we can easily refer to them when needed. 

Also notice the loaded attribute. Just as <Page> has a loaded attribute, buttons can also have one. You'll see later on how this is used.

5. JavaScript Code

Now we're ready to look at the JavaScript that makes it all work. In this section, we'll code the notes-page.js file.

Initialization

First we import the data/observable and data/observable-array modules. These are built-in modules in NativeScript that allow us to create observable objects and arrays. Observables allow us to automatically update the UI whenever these objects and arrays get updated. 

In our app, pageArray is used for storing the array of notes, and pageData is used for tying it to the page. pageData also serves as the general container for all data that we want to show in the UI.

Next, import all the other modules that we'll be using in this page:

  • camera: for working with the device camera.
  • view: for referring to specific elements in the page. Think of it as the equivalent of document.getElementById in NativeScript.
  • ui/enums: a global dictionary of constant values for anything related to UIs.
  • ui/animation: for animating elements.
  • application-settings: for persisting local data.
  • file-system: for working with the filesystem.

Next, initialize the values for the variables that will be used throughout the whole file. page is used for storing a reference to the current page, notesArr is the plain array copy of the current notes in the page, and current_index is the initial value of the index that is used as the unique ID for each note.

The pageLoaded() Function

Functions become available in the context of the page by means of using exports. Earlier in the notes-page.xml file, you saw that the pageLoaded() function is executed when the page is loaded. 

Inside the pageLoaded() function, we'll start by getting the reference to the page. Then we show the form for creating a new note, and get the currently stored values of the new note title and the notes from the application settings.

Next, still within the pageLoaded() function, check if there are notes that are stored locally. If not, we create an array of notes. This array will serve as the default content for new users of the app. However, if there are already some notes stored locally, we convert them to an array and then push that data to the observable array. 

Note that before we push the items into the observable array, we first check if it's empty. We have to do this because using the camera module executes the loaded event on the page once again after an image is selected. This means that if we're not careful, we'll end up pushing duplicates into the array every time the user uses the camera. 

Now that we have the notes data set up, we can update the page title by setting its item_title attribute to the value that we got from the application settings earlier. Then bind pageData to the page so that the UI automatically gets updated whenever a change is made to the items that we've set. 

Animate the form for creating new notes. We do this by using the getViewById function in the view and passing in the context (the current page) as the first argument and the id attribute assigned to the element that you want to manipulate. 

Next, call the animate function. This accepts an object containing the animation settings. Here we want the form to slide down 160 pixels from its original position over a period of 800 milliseconds.

The newNote() Function

The newNote() function is executed when the user taps on the New Item action item on the header. This hides and shows the new item ListView and slides the form up or down depending on the current value of showForm

If showForm is true, which means it's currently being shown, we change the opacity of the ListView to 1 over the course of 400 milliseconds, and then slide the form up to hide it. Otherwise, we hide the ListView and slide the form down.

The btnLoaded() Function

In the notes-page.xml file, we have a loaded attribute in the button for deleting a note. This is the function that gets executed when that event happens. 

By default, the function assigned to the itemTap attribute in the ListView won't get executed when a button is defined inside a ListView item. This is because NativeScript assumes that the actions to be performed for each list item can be triggered only from those buttons. 

The code below is a workaround for that default behavior. This basically removes the focus on the delete button so that you can still execute a function when a user taps on a ListView item. In this case, we don't really need this code since we haven't assigned any functionality to item taps, but it is a good tool to have when working with lists.

The openCamera() Function

Next is the openCamera() function, which gets executed when the user taps on the Attach Image button. The current state is not maintained when using the camera module, so we need to save the title of the new note into the application settings first. 

Afterwards we can launch the default camera app in the device by calling the takePicture() method. This method accepts an object containing the picture settings. Once the user has taken a picture and tapped on the Save button in Android or the use image button on iOS, the promise resolves and the callback function passed to then() gets executed. 

The actual image is passed as an argument to the function, and we use this to save the file to the documents path. Once that's done, we save the full file path to the app settings and the current app state so that we can get the value later, before saving the note.

The saveNote() Function

The saveNote() function is executed when the user taps on the Save Note button. This gets the current value of the note title text field and the image path, increments the current_index, and pushes the new item into the plain notes array and observable notes array. Then it saves the current notes and the current_index into the application settings, removes the values for the new note from the application settings, updates the UI so that the form shows its empty state, and shows the list while hiding the new note form.

The deleteNote() Function

Lastly, we have the deleteNote() function which gets executed when a user taps on the delete button inside a list item. As you have already seen from previous functions, an object is passed in as an argument to functions that are attached as an event handler for a specific component. This object has the object property, which refers to the component itself. 

From there, you can get the value of an attribute that was passed to it. In this case, we're getting the value of the index attribute, and we use it to get the actual index of the item that we want to delete.

6. Adding Styles

Open the app.css file and add the following global styles:

If you want to apply page-specific styles, you can also create a notes-page.css file and define your styles in there. 

7. Running and Debugging the App

You can run the app on your device by executing tns run and then the platform where you want to deploy. Here's an example for android:

This automatically installs the Android platform for you if it hasn't already been installed and then runs the app on your device once it's installed. Once the app is running, you can execute tns livesync android --watch to automatically refresh the app every time you make changes to the source files.

Debugging

Just like any other app framework, NativeScript allows developers to debug their app. This is done with the Chrome dev tools. There are two ways of doing this:

  1. If have an app already running, you can open a new terminal window and execute tns debug android --start to attach a debugger to the currently running instance of the app.
  2. If you don't have an app running yet, use tns debug android --debug-brk to build an instance of the app with a debugger attached to it.

No matter which option you choose, this will open up a new tab in the Google Chrome browser that allows you to debug the app just like a normal JavaScript web app. This means that you can actually use console.log in your source code to inspect the contents of the variables that you're working with.

Conclusion and Next Steps

In this article, you've learned how to build an app with NativeScript. Specifically, you've learned concepts such as using UI components, layouts, styling, animations, using the device camera, and maintaining application state with application settings. 

Now that you've built your first NativeScript app, it's now time to take your skills even further by checking out what else you can do with NativeScript and building some more apps with it. 

2016-08-05T12:00:05.000Z2016-08-05T12:00:05.000ZWernher-Bel Ancheta

Android From Scratch: Creating Styles and Themes

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

As Android developers, we tend to focus primarily on the functionality of our apps. Functionality alone, however, is rarely enough. On Google Play, which hosts well over a million apps today, looks are just as important as functionality, if not more. If you find that hard to believe, I suggest you take a quick look at the apps in the Top Charts section of Google Play.

There are two approaches to modifying the look of Android apps. The first approach involves directly modifying the properties of views in layout XML files. This approach is feasible only if you are working on a simple app that has a small number of views and activities. The second approach involves creating and using custom styles and themes. If you are familiar with web development, the first approach is akin to using inline CSS styles, and the second approach is akin to using style sheets.

In this tutorial, you'll learn how to create custom styles and themes for your Android apps. You'll also learn how to use Android Studio's tools and shortcuts that facilitate style creation.

1. Creating Styles

Styles are obviously applied to UI components. Therefore, let's start by creating a new empty activity and adding two views to its layout XML file.

As you can see in the above code, properties such as layout_width and layout_margin are explicitly included in the definition of each view.

To create a new style for the first view, right click on it and select Refactor > Extract > Style.

You will now see a dialog where you can give a name to the style and also select the attributes that should be included in it. Let the name be MyBox and select all the attributes except background.

Extract style

When you press OK, you'll see that the code for the first view has changed.

The view now has a style attribute that points to the MyBox style. You can take a look at the definition of the style by opening res/values/styles.xml.

Once a style has been created, it can be applied to any view. For example, here's how you would apply MyBox to the second view:

With the styles applied, here's what the two views look like in an activity:

Two views with styles

2. Extending Styles

Android allows you to create styles that use other styles as a foundation. In other words, it allows you to extend existing styles.

There are two different syntaxes you can follow while extending a style. The first syntax is often called the implicit syntax and uses a dot notation. For example, here's how you create two derived styles, called TEAL and CYAN, using MyBox as the parent style:

As you might have guessed, both MyBox.TEAL and MyBox.CYAN have all the properties of MyBox. In addition to those, they have the android:background property.

The second syntax for creating a derived style is usually referred to as the explicit syntax. It involves using a parent attribute whose value is set to the name of the parent style. Here's a code snippet that defines a style called TealBox.

Applying derived styles is no different from applying normal ones.

Most developers use the implicit syntax while extending their own styles, and the explicit syntax while extending platform styles.

3. Creating Themes

All this while, we've only been applying styles to views that are inside an activity. Android allows you to apply styles to entire activities and applications too. When a style is applied to an activity or application, it becomes a theme.

By default, all apps created using the latest version of Android Studio use a theme called AppTheme. AppTheme is a descendant of the well-known AppCompat theme, a large and very comprehensive theme that can affect the looks of almost all the commonly used views.

You can find the definition of AppTheme in styles.xml:

AppTheme follows Material Design. Therefore, in order to create your own themes that conform to the Material Design spec, using AppTheme as a parent is always a good idea. Alternatively, you could directly use Theme.AppCompat as a parent.

Although you can always create themes by writing XML code—remember, they are just styles—in this tutorial, I'm showing you how to use Android Studio's Theme Editor to do all the hard work for you.

To open the Theme Editor, open the Tools menu and select Android > Theme Editor.

On the right-hand side of the Theme Editor window, you have controls not only to modify themes, but also to create new ones. The left-hand side shows you a preview of the results of the modifications you make to the themes.

Theme Editor

To create a new theme, click on the Theme drop-down menu and select the Create New Theme option.

In the dialog that pops up, set the name of the new theme to MyTheme and press OK.

Create new theme

At this point, styles.xml will have a new line that looks like this:

Let us now modify MyTheme using the Theme Editor. To keep things simple, in this tutorial we'll be modifying the values of the colorPrimary, colorPrimaryDark, and colorAccent attributes only.

To modify the value of colorPrimary, click on the colorPrimary button. The Theme Editor will now show you a dialog containing a color picker. Choose any color you want, but make sure that you give it a new name. If you forget to do so, the Theme Editor will overwrite the color used by AppTheme.

Editing colorPrimary

Follow the same steps to modify the values of colorPrimaryDark and colorAccent. The Theme Editor will automatically use the color you chose for colorPrimary to suggest appropriate colors for both colorPrimaryDark and colorAccent.

The definition of MyTheme would now look like this:

4. Applying Themes

Before we apply the theme we created, let us add a few commonly used views to the activity. Doing so will make it easier for us to notice the effects of the theme.

The following code creates a normal Button, a borderless Button, a colored Button, a Checkbox, a RadioButton, a Switch, a Seekbar, a TextView, and an EditText.

With all the newly added views, the layout will look like this:

Layout using AppTheme

If you've read the Material Design spec, I'm sure you can tell that the activity currently uses shades of indigo for colorPrimary and colorPrimaryDark. For colorAccent, it uses a shade of pink. Those are the default colors specified by Android Studio. You can find their hex equivalents in your project's res/values/colors.xml.

To apply MyTheme, the theme we created in the previous step, to your activity, open your project's manifest file and add an android:theme attribute to the activity's definition. Set its value to @style/MyTheme.

Similarly, you can apply the theme to your entire application by setting the value of the android:theme attribute of the application's definition to @style/MyTheme.

If you take a look at your activity now, it should look very different.

Layout using MyTheme

Conclusion

In this tutorial, you learned how to create and apply custom Android styles and themes. Feel free to use this knowledge to give new and better looks to your apps. However, try not to get too carried away—most Android users today are so accustomed to Material Design that deviating from its guidelines can annoy them.

To learn more about styles and themes, I suggest you go through the Styles and Themes Guide.

2016-08-09T12:32:26.000Z2016-08-09T12:32:26.000ZAshraff Hathibelagal

Create a Weather App With TypeScript and NativeScript

$
0
0

In this tutorial I'll show you how to build a weather app in NativeScript using the TypeScript language. 

In the previous article in this series we created a note-taking app using plain JavaScript. This time we're going to use TypeScript. First let's find out why TypeScript is a good option for building NativeScript apps. 

1. Why TypeScript?

TypeScript is a first-class citizen in NativeScript. It is used by the core NativeScript team to build the NativeScript framework itself. Here are a couple of reasons why you would want to use TypeScript for developing NativeScript apps:

  • TypeScript compiles to JavaScript. When the compiler runs, it catches any errors that you might have in your code so that you can act on them immediately without waiting for the NativeScript compiler to finish. This means more productivity for you as the developer.  
  • TypeScript allows you to use ES6 Features such as classes, modules, arrow functions, template literals, and much more. This means more tools at your disposal to organize and write better code.

If I did a poor job at convincing you or you want to know more about why TypeScript is good for developing with NativeScript, you can check out Build Better NativeScript Apps With TypeScript.

2. Tooling

To fully take advantage of the features that TypeScript offers, I recommend that you use the Visual Studio Code text editor. It has an IntelliSense feature which provides smart auto-completion while you're writing TypeScript code, it integrates with Git, and it has debugging capabilities as well. 

Best of all, there's also a NativeScript plugin which will make you more productive when developing NativeScript apps. One feature that I find useful is the emulator integration. This allows you to run the emulator directly from the text editor and debug the app from the text editor itself. Visual Studio Code is free and available on all major platforms (Windows, Linux, OS X). 

However, if you don't want to leave the comfort of your text editor, you can also install extensions that will make coding with TypeScript better. For Atom, there's the atom-typescript plugin. For Sublime Text, there's the TypeScript Sublime plugin

3. Overview of the App

The app that we're going to create is a weather app. It will have the following pages: 

  • A main page which shows the current weather along with some relevant information such as the temperature, air pressure, and humidity.
  • A forecast page which shows a five-day forecast of what the weather is going to be for the next five days.

Here's what the main page will look like:

Main page

And here's the forecast page:

forecast page

You can find the completed source code for this app on its GitHub repo.

4. OpenWeatherMap

The weather data will come from the OpenWeatherMap API, and just like any other API, you need to sign up for an API key in order to use it. Go ahead and sign up for an account, I'll wait. Once you're logged in, go to the API keys page, copy the value of the key field, and keep it somewhere safe. You'll need it later, once you start creating the app.

OpenWeatherMap generate API keys

5. Creating the App

Now that you know what the app will look like, it's time to actually start creating it. Start by creating a new NativeScript project which uses the TypeScript template:

Once that's done, navigate into the app folder and create the following folders and files. For your convenience, you can also download or clone the GitHub repo and copy the files from the app folder.

We will only ever work inside the app directory, so every time I reference a file path or a folder, assume that the app directory is the root.

Install the Dependencies

The app requires a couple of dependencies: the NativeScript Geolocation Module and Moment. You can install the Geolocation module with the following command:

And install Moment with:

The Geolocation module is used to determine the current location of the user. Moment allows easy formatting of the Unix timestamps, which we will be getting from the API later on.

Common Modules

Before we take a look at the code for each of the pages of the app, let's first take a look at the custom modules which will be used throughout the app.

Constants

The constants module (common/constants.ts) contains all the constant values used throughout the app: things like the base URL of the OpenWeatherMap API, the API key that you got earlier, the paths to the endpoints that we will be using, the character codes of the weather icons, and the wind directions.

Utilities

The utilities module includes all sorts of utility functions: things like converting degrees to directions, determining a descriptive text for the wind speed, converting Kelvin to Celsius, and converting character codes into a character. You'll see how all of these functions are used later on in the pages. 

Navigation

The navigation module is a custom helper module which allows us to easily navigate between all the pages of the app. Open the common/navigation.ts file and add the following:

This uses the Frame module to navigate to other pages of the app. The getStartPage() method simply returns the location of the main app page. The goToForecastPage(), as the name suggests, allows the user to navigate to the forecast page. 

When navigating in NativeScript, you need to have a reference of where you currently are. That's why you first need to call the topmost() function to get the current or uppermost page, and then the navigate() function to go to another page. This function accepts the path to the page where you want to go. 

Requestor

The Requestor module performs the actual request to the OpenWeatherMap API. As mentioned in the Introduction to NativeScript article, NativeScript uses a JavaScript virtual machine to run JavaScript code. This means that we can also use functions that are available in the browser. 

One such function is fetch, which allows us to make HTTP requests to a remote server. The parameter is the URL where you want to make the request. It returns a promise so we use then() to wait for the raw response. Note the use of the word "raw"; the fetch function returns the response with headers and other low-level information—that's why we need to call the json() function to get the actual JSON data. This will return another promise so we use then() one more time to get the actual object.

Alternatively, you can use the Http module, which is a more robust way of making HTTP requests in NativeScript.

Location Store

The location store serves as the storage for the location information. This allows us to update and get the current location from any file which imports this module.

Main Page

Now it's time to take a look at the code for each of the pages of the app. But before we do that, first open up the entry-point file (app.ts). This uses the navigation module to get the starting page of the app:

Next, let's break down the pages/main/main.xml file.

The navigatingTo event is used to execute a similarly named function in the TypeScript file every time the user navigates to this specific page. The CSS class is also dynamically determined from the TypeScript file.

The ScrollView component is used to wrap everything so that a vertical scrollbar is automatically generated when the content goes beyond what the screen size can display. 

And because we're going to load the data from a remote server, the ActivityIndicator component is used to show the default loading animation of the platform. This requires you to supply a busy attribute, which accepts a boolean value that controls whether to start the animation or not. By default, this is set to true and only updated to false once the app is done making the request to the server. 

The visibility attribute is also used to make sure that the component doesn't consume any space while it's not animating.  

For the main content, we have the general overview of the current weather at the top, and the details below it. The general overview shows an icon representing the current weather, the current temperature, the weather description, and the place.

For the details, there's a whole bunch of information about the current weather which you can probably guess by looking at the text attribute. Each one is also accompanied by its own icon. 

On the screenshot that I showed you earlier, you saw that it uses a two-column layout for both pages. That's the reason why we're using GridLayout. But as you can see from the code below, we're also using a GridLayout for the first column of each row. 

You might ask why we're doing this instead of just creating a three-column layout with the icon on the first column, the weather attribute on the second, and the value on the third. That's perfectly understandable, and it would make the code more concise. 

But the problem is that NativeScript version 2.1 doesn't currently allow percentage units for its GridLayout. This means we can't use something like 10% for the icon while the other two columns consume 45% each. 

The layout that we've used below works around that problem by using a GridLayout to wrap the icon and weather attribute, with the icon consuming 30 pixels and the weather attribute consuming the amount of space required to contain the text. Note the use of the row and col attribute on the GridLayout as well.

The last markup for the main page is the button that leads to the forecast page:

Main Page JavaScript

Open the pages/main/main.ts file and add the following code:

In the above code, we import a couple of built-in NativeScript modules, the main view-model, and the navigation. 

The EventData object is extracted using object destructuring, an ES6 feature made available by TypeScript. The EventData is what we pass in as an argument to the navigatingTo function so that it will have access to any data passed in by any page which navigates to this page. 

This has an object property, which is basically whatever component triggered the event. In this case, we know that it's triggered on the Page component, and that's why we use <Page> as a type-assertion. After that, we bind the main view-model to the page. This will allow us to add or update a property in the class, and it will instantly get reflected on the page.

In the main view model (pages/main/main-view-model.ts), first import all the modules that we will be using:

Create the view model by extending the Observable module, which makes all the properties in this class observable. This means that all references of each property in the UI will get updated every time it is changed in this class.

Inside the constructor, check if geolocation is enabled. If it's not enabled then try to enable it by calling the enableLocationRequest() function. This triggers the app to ask the user to enable geolocation. 

Next, determine whether it's day or night and set the page background according to the result. Then set the icons in the page.

After that, try to determine the current location. Note that if the user didn't allow geolocation then the app wouldn't work at all, because the weather depends on the user's location. The app will try to determine the user's location in 10 seconds. If it fails to do so, then an error message is shown to the user.

If the location request succeeded, we save it using the locationStore. This allows us to access the location on other pages later on without requesting it again.

For your reference, here's a sample response that you might get when requesting the location in NativeScript. You can check out the Location documentation for NativeScript to learn more about each of the properties below.

We can construct the full API request URL using template literals and make the request using the Requestor module.

Once a response comes back, extract and format it, and then set the resulting value as a property of the class. And because the class is observable, this will automatically update the UI of the app.

For your reference, here's a sample response that might be returned by the API:

You can find the detailed information about each property in the documentation for the current weather data.

Finally. there's the setIcons() function, which sets all the icons used in the page:

Main Page Styles and Icons

Here are the styles for the main page:

Notice the use of the weathericons as the font-family for the icon and small-icon classes. This is how we use icon fonts in NativeScript. If you're fond of icon fonts like Font Awesome on your web pages, you can use them the same way in NativeScript apps. 

First, download the icon font that you want to use. For this app, the Weather Icons Font is used. Extract the zip archive and inside the extracted folder go to the font directory. Copy the .ttf file to the fonts directory in your app and rename it to weathericons.ttf. The filename is what you use as the value for the font-family every time you want to use that specific font icon. Aside from that, you also have to add the font-size to control the size of the icons.

Forecast Page

Now let's take a look at the markup for the forecast page (pages/forecast/forecast.xml). In the header, there's a back button which allows the user to go back to the main page. Note that instead of the general-purpose Button component, we're using a NavigationButton, which is the NativeScript equivalent of the iOS back button and the Android navigation button. 

For the main content, the Repeater component is used instead of the usual ListView. Both components can be used to generate a list, but ListView comes with more bells and whistles. For example, it automatically generates a vertical scrollbar when the list goes over the screen size. Infinite scrolling functions are also built-in. 

The Repeater component is used in this case because there's no real need for the features I just mentioned. All we need is a bare-bones list.

Inside each Repeater.itemTemplate is a GridLayout with two columns, one for the general weather information and one for the details. 

The first column is a StackLayout containing the date, weather icon, and the weather description. The second column is also a StackLayout containing four GridLayouts that will contain the four weather attributes (temperature, wind speed, cloudiness, and air pressure). 

The first GridLayout has three columns for containing the icon, the day temperature, and the night temperature. The other three rows only have two columns—for the icon and the value of the weather attribute.

Note the use of $parents['Page']. When using the Repeater or ListView component, you can't have access to data outside the array that you specified for the list to use—not unless you explicitly specify the parent component where the data is available. That is where $parents['Page'] comes in. $parents is a special variable in NativeScript that allows you to access data available on a specific component. In this case, we specified Page to access the icons for each weather attribute.

Forecast Page JavaScript

The code for the forecast page is pretty much the same as the code for the main page. The only difference is that the navigation function is for going to back to the main page, and we're using the ForecastViewModel as the view-model.

Here's the code for the view model (pages/forecast/forecast-view-model.ts):

Inside the constructor, we get the current location from the location store and construct the URL endpoint for the 16-day weather forecast. But instead of 16, we only want five days, so we specify 6 for the count (cnt). We use 6 because the time zone is dependent on the server and not on the location specified. This means that there's a possibility that the API will return the weather for the previous day or the current day. That's why there's an extra 1 day which serves as the padding.

Next, make the request and update the UI with the API response by calling the getForecast() function:

Here's a sample response returned by the 16-day forecast endpoint. Note that to make the sample more concise, I've set the count to 1, which is why the list property only contains one object.

Forecast Page Styles

Here are the styles for the forecast page (pages/forecast/forecast.css):

Global App Styles

Open the app.css file and add the following styles:

6. Changing the Default App Icon

You can change the default app icon by going to the App_Resources folder. There you can see an Android and iOS folder. For Android, you can replace the image file in each of the following folders to change the icon:

  • drawable-hdpi
  • drawable-ldpi
  • drawable-mdpi

For iOS, it's the images inside the Assets.xcassets/AppIcon.appiconset folder that you want to replace.

If you want to easily create icons for both Android and iOS, check out MakeAppIcon. Simply choose an image file to use as the icon, and it will automatically generate different sizes for both Android and iOS. You can then move those to the folders mentioned above. Just make sure you got the correct sizes, and the names are the same as the images they replace.

7. Running the App

You can run the app on your device or emulator as usual by executing the following tns commands:

The only difference now that we're using TypeScript is that there's an additional step at the start of each task, to compile the TypeScript files into JavaScript. TypeScript's strong type-checking acts a safety net for catching some errors before NativeScript even compiles the app.

Conclusion

In this tutorial, you learned how to build an app with NativeScript using the TypeScript language. Specifically, you learned the following concepts: 

  • Structuring your app by putting related files into their own folder.
  • Code re-use using modules.
  • Using view-models to provide data and functionality for the pages of the app.
  • Determining location with the geolocation plugin.
  • Making HTTP requests.
  • Using font icons.
  • Navigating between pages.

I'll leave you with a few resources to continue with your journey in developing awesome apps with NativeScript:

2016-08-17T13:57:18.000Z2016-08-17T13:57:18.000ZWernher-Bel Ancheta

Create a Weather App With TypeScript and NativeScript

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

In this tutorial I'll show you how to build a weather app in NativeScript using the TypeScript language. 

In the previous article in this series we created a note-taking app using plain JavaScript. This time we're going to use TypeScript. First let's find out why TypeScript is a good option for building NativeScript apps. 

1. Why TypeScript?

TypeScript is a first-class citizen in NativeScript. It is used by the core NativeScript team to build the NativeScript framework itself. Here are a couple of reasons why you would want to use TypeScript for developing NativeScript apps:

  • TypeScript compiles to JavaScript. When the compiler runs, it catches any errors that you might have in your code so that you can act on them immediately without waiting for the NativeScript compiler to finish. This means more productivity for you as the developer.  
  • TypeScript allows you to use ES6 Features such as classes, modules, arrow functions, template literals, and much more. This means more tools at your disposal to organize and write better code.

If I did a poor job at convincing you or you want to know more about why TypeScript is good for developing with NativeScript, you can check out Build Better NativeScript Apps With TypeScript.

2. Tooling

To fully take advantage of the features that TypeScript offers, I recommend that you use the Visual Studio Code text editor. It has an IntelliSense feature which provides smart auto-completion while you're writing TypeScript code, it integrates with Git, and it has debugging capabilities as well. 

Best of all, there's also a NativeScript plugin which will make you more productive when developing NativeScript apps. One feature that I find useful is the emulator integration. This allows you to run the emulator directly from the text editor and debug the app from the text editor itself. Visual Studio Code is free and available on all major platforms (Windows, Linux, OS X). 

However, if you don't want to leave the comfort of your text editor, you can also install extensions that will make coding with TypeScript better. For Atom, there's the atom-typescript plugin. For Sublime Text, there's the TypeScript Sublime plugin

3. Overview of the App

The app that we're going to create is a weather app. It will have the following pages: 

  • A main page which shows the current weather along with some relevant information such as the temperature, air pressure, and humidity.
  • A forecast page which shows a five-day forecast of what the weather is going to be for the next five days.

Here's what the main page will look like:

Main page

And here's the forecast page:

forecast page

You can find the completed source code for this app on its GitHub repo.

4. OpenWeatherMap

The weather data will come from the OpenWeatherMap API, and just like any other API, you need to sign up for an API key in order to use it. Go ahead and sign up for an account, I'll wait. Once you're logged in, go to the API keys page, copy the value of the key field, and keep it somewhere safe. You'll need it later, once you start creating the app.

OpenWeatherMap generate API keys

5. Creating the App

Now that you know what the app will look like, it's time to actually start creating it. Start by creating a new NativeScript project which uses the TypeScript template:

Once that's done, navigate into the app folder and create the following folders and files. For your convenience, you can also download or clone the GitHub repo and copy the files from the app folder.

We will only ever work inside the app directory, so every time I reference a file path or a folder, assume that the app directory is the root.

Install the Dependencies

The app requires a couple of dependencies: the NativeScript Geolocation Module and Moment. You can install the Geolocation module with the following command:

And install Moment with:

The Geolocation module is used to determine the current location of the user. Moment allows easy formatting of the Unix timestamps, which we will be getting from the API later on.

Common Modules

Before we take a look at the code for each of the pages of the app, let's first take a look at the custom modules which will be used throughout the app.

Constants

The constants module (common/constants.ts) contains all the constant values used throughout the app: things like the base URL of the OpenWeatherMap API, the API key that you got earlier, the paths to the endpoints that we will be using, the character codes of the weather icons, and the wind directions.

Utilities

The utilities module includes all sorts of utility functions: things like converting degrees to directions, determining a descriptive text for the wind speed, converting Kelvin to Celsius, and converting character codes into a character. You'll see how all of these functions are used later on in the pages. 

Navigation

The navigation module is a custom helper module which allows us to easily navigate between all the pages of the app. Open the common/navigation.ts file and add the following:

This uses the Frame module to navigate to other pages of the app. The getStartPage() method simply returns the location of the main app page. The goToForecastPage(), as the name suggests, allows the user to navigate to the forecast page. 

When navigating in NativeScript, you need to have a reference of where you currently are. That's why you first need to call the topmost() function to get the current or uppermost page, and then the navigate() function to go to another page. This function accepts the path to the page where you want to go. 

Requestor

The Requestor module performs the actual request to the OpenWeatherMap API. As mentioned in the Introduction to NativeScript article, NativeScript uses a JavaScript virtual machine to run JavaScript code. This means that we can also use functions that are available in the browser. 

One such function is fetch, which allows us to make HTTP requests to a remote server. The parameter is the URL where you want to make the request. It returns a promise so we use then() to wait for the raw response. Note the use of the word "raw"; the fetch function returns the response with headers and other low-level information—that's why we need to call the json() function to get the actual JSON data. This will return another promise so we use then() one more time to get the actual object.

Alternatively, you can use the Http module, which is a more robust way of making HTTP requests in NativeScript.

Location Store

The location store serves as the storage for the location information. This allows us to update and get the current location from any file which imports this module.

Main Page

Now it's time to take a look at the code for each of the pages of the app. But before we do that, first open up the entry-point file (app.ts). This uses the navigation module to get the starting page of the app:

Next, let's break down the pages/main/main.xml file.

The navigatingTo event is used to execute a similarly named function in the TypeScript file every time the user navigates to this specific page. The CSS class is also dynamically determined from the TypeScript file.

The ScrollView component is used to wrap everything so that a vertical scrollbar is automatically generated when the content goes beyond what the screen size can display. 

And because we're going to load the data from a remote server, the ActivityIndicator component is used to show the default loading animation of the platform. This requires you to supply a busy attribute, which accepts a boolean value that controls whether to start the animation or not. By default, this is set to true and only updated to false once the app is done making the request to the server. 

The visibility attribute is also used to make sure that the component doesn't consume any space while it's not animating.  

For the main content, we have the general overview of the current weather at the top, and the details below it. The general overview shows an icon representing the current weather, the current temperature, the weather description, and the place.

For the details, there's a whole bunch of information about the current weather which you can probably guess by looking at the text attribute. Each one is also accompanied by its own icon. 

On the screenshot that I showed you earlier, you saw that it uses a two-column layout for both pages. That's the reason why we're using GridLayout. But as you can see from the code below, we're also using a GridLayout for the first column of each row. 

You might ask why we're doing this instead of just creating a three-column layout with the icon on the first column, the weather attribute on the second, and the value on the third. That's perfectly understandable, and it would make the code more concise. 

But the problem is that NativeScript version 2.1 doesn't currently allow percentage units for its GridLayout. This means we can't use something like 10% for the icon while the other two columns consume 45% each. 

The layout that we've used below works around that problem by using a GridLayout to wrap the icon and weather attribute, with the icon consuming 30 pixels and the weather attribute consuming the amount of space required to contain the text. Note the use of the row and col attribute on the GridLayout as well.

The last markup for the main page is the button that leads to the forecast page:

Main Page JavaScript

Open the pages/main/main.ts file and add the following code:

In the above code, we import a couple of built-in NativeScript modules, the main view-model, and the navigation. 

The EventData object is extracted using object destructuring, an ES6 feature made available by TypeScript. The EventData is what we pass in as an argument to the navigatingTo function so that it will have access to any data passed in by any page which navigates to this page. 

This has an object property, which is basically whatever component triggered the event. In this case, we know that it's triggered on the Page component, and that's why we use <Page> as a type-assertion. After that, we bind the main view-model to the page. This will allow us to add or update a property in the class, and it will instantly get reflected on the page.

In the main view model (pages/main/main-view-model.ts), first import all the modules that we will be using:

Create the view model by extending the Observable module, which makes all the properties in this class observable. This means that all references of each property in the UI will get updated every time it is changed in this class.

Inside the constructor, check if geolocation is enabled. If it's not enabled then try to enable it by calling the enableLocationRequest() function. This triggers the app to ask the user to enable geolocation. 

Next, determine whether it's day or night and set the page background according to the result. Then set the icons in the page.

After that, try to determine the current location. Note that if the user didn't allow geolocation then the app wouldn't work at all, because the weather depends on the user's location. The app will try to determine the user's location in 10 seconds. If it fails to do so, then an error message is shown to the user.

If the location request succeeded, we save it using the locationStore. This allows us to access the location on other pages later on without requesting it again.

For your reference, here's a sample response that you might get when requesting the location in NativeScript. You can check out the Location documentation for NativeScript to learn more about each of the properties below.

We can construct the full API request URL using template literals and make the request using the Requestor module.

Once a response comes back, extract and format it, and then set the resulting value as a property of the class. And because the class is observable, this will automatically update the UI of the app.

For your reference, here's a sample response that might be returned by the API:

You can find the detailed information about each property in the documentation for the current weather data.

Finally. there's the setIcons() function, which sets all the icons used in the page:

Main Page Styles and Icons

Here are the styles for the main page:

Notice the use of the weathericons as the font-family for the icon and small-icon classes. This is how we use icon fonts in NativeScript. If you're fond of icon fonts like Font Awesome on your web pages, you can use them the same way in NativeScript apps. 

First, download the icon font that you want to use. For this app, the Weather Icons Font is used. Extract the zip archive and inside the extracted folder go to the font directory. Copy the .ttf file to the fonts directory in your app and rename it to weathericons.ttf. The filename is what you use as the value for the font-family every time you want to use that specific font icon. Aside from that, you also have to add the font-size to control the size of the icons.

Forecast Page

Now let's take a look at the markup for the forecast page (pages/forecast/forecast.xml). In the header, there's a back button which allows the user to go back to the main page. Note that instead of the general-purpose Button component, we're using a NavigationButton, which is the NativeScript equivalent of the iOS back button and the Android navigation button. 

For the main content, the Repeater component is used instead of the usual ListView. Both components can be used to generate a list, but ListView comes with more bells and whistles. For example, it automatically generates a vertical scrollbar when the list goes over the screen size. Infinite scrolling functions are also built-in. 

The Repeater component is used in this case because there's no real need for the features I just mentioned. All we need is a bare-bones list.

Inside each Repeater.itemTemplate is a GridLayout with two columns, one for the general weather information and one for the details. 

The first column is a StackLayout containing the date, weather icon, and the weather description. The second column is also a StackLayout containing four GridLayouts that will contain the four weather attributes (temperature, wind speed, cloudiness, and air pressure). 

The first GridLayout has three columns for containing the icon, the day temperature, and the night temperature. The other three rows only have two columns—for the icon and the value of the weather attribute.

Note the use of $parents['Page']. When using the Repeater or ListView component, you can't have access to data outside the array that you specified for the list to use—not unless you explicitly specify the parent component where the data is available. That is where $parents['Page'] comes in. $parents is a special variable in NativeScript that allows you to access data available on a specific component. In this case, we specified Page to access the icons for each weather attribute.

Forecast Page JavaScript

The code for the forecast page is pretty much the same as the code for the main page. The only difference is that the navigation function is for going to back to the main page, and we're using the ForecastViewModel as the view-model.

Here's the code for the view model (pages/forecast/forecast-view-model.ts):

Inside the constructor, we get the current location from the location store and construct the URL endpoint for the 16-day weather forecast. But instead of 16, we only want five days, so we specify 6 for the count (cnt). We use 6 because the time zone is dependent on the server and not on the location specified. This means that there's a possibility that the API will return the weather for the previous day or the current day. That's why there's an extra 1 day which serves as the padding.

Next, make the request and update the UI with the API response by calling the getForecast() function:

Here's a sample response returned by the 16-day forecast endpoint. Note that to make the sample more concise, I've set the count to 1, which is why the list property only contains one object.

Forecast Page Styles

Here are the styles for the forecast page (pages/forecast/forecast.css):

Global App Styles

Open the app.css file and add the following styles:

6. Changing the Default App Icon

You can change the default app icon by going to the App_Resources folder. There you can see an Android and iOS folder. For Android, you can replace the image file in each of the following folders to change the icon:

  • drawable-hdpi
  • drawable-ldpi
  • drawable-mdpi

For iOS, it's the images inside the Assets.xcassets/AppIcon.appiconset folder that you want to replace.

If you want to easily create icons for both Android and iOS, check out MakeAppIcon. Simply choose an image file to use as the icon, and it will automatically generate different sizes for both Android and iOS. You can then move those to the folders mentioned above. Just make sure you got the correct sizes, and the names are the same as the images they replace.

7. Running the App

You can run the app on your device or emulator as usual by executing the following tns commands:

The only difference now that we're using TypeScript is that there's an additional step at the start of each task, to compile the TypeScript files into JavaScript. TypeScript's strong type-checking acts a safety net for catching some errors before NativeScript even compiles the app.

Conclusion

In this tutorial, you learned how to build an app with NativeScript using the TypeScript language. Specifically, you learned the following concepts: 

  • Structuring your app by putting related files into their own folder.
  • Code re-use using modules.
  • Using view-models to provide data and functionality for the pages of the app.
  • Determining location with the geolocation plugin.
  • Making HTTP requests.
  • Using font icons.
  • Navigating between pages.

I'll leave you with a few resources to continue with your journey in developing awesome apps with NativeScript:

2016-08-17T13:57:18.000Z2016-08-17T13:57:18.000ZWernher-Bel Ancheta

How to Design and Build a Material Design App

$
0
0
Material Design principles

Google's Material Design took the web design world by storm when it was introduced in 2014, and its popularity has continued to grow since then.

If you still need to get fully up to speed on Material Design, the two courses described below are ideal for you. In the first course, you'll master the fundamentals and build a simple app, and in the second course you'll take it to the next level and build a fully functional Material Design app. 

1. Getting to Know Material Design

In this course, Adi Purdila will introduce you to Material Design, Google’s widely discussed visual language. You’ll learn the definition of material, its properties, and the basic principles of the language.

In later lessons, you’ll design a very simple application using Material Design, and to finish up the course you’ll find a quiz to test what you’ve learned.

2. Build a Material Design App

Google's Material Design has quickly become a popular and widely implemented design language. Many Android users now expect their apps to conform to the material design spec, and app designers will expect you to be able to implement its basic principles. 

In this course, Envato Tuts+ instructor Ashraff Hathibelagal will show you how to build a practical, fully functional Material Design app that is ready to publish on Google Play. 

Starting from the app design created by instructor Adi Purdila in his course Getting to Know Material Design, you will learn how to work with the various Material Design UI widgets available in the Android Support library, such as FloatingActionButton, TextInputLayout, and RecyclerView. You will also learn how to perform read and write operations on a modern mobile database called Realm.

Start Learning With a Free Trial

You can take both of these courses, and also get access to our full library of web design and code courses, with a free 10-day trial of our monthly subscription. So get started today, and master Material Design and much more.

2016-08-23T14:40:03.000Z2016-08-23T14:40:03.000ZAndrew Blackman

How to Design and Build a Material Design App

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-27070
Material Design principles

Google's Material Design took the web design world by storm when it was introduced in 2014, and its popularity has continued to grow since then.

If you still need to get fully up to speed on Material Design, the two courses described below are ideal for you. In the first course, you'll master the fundamentals and build a simple app, and in the second course you'll take it to the next level and build a fully functional Material Design app. 

1. Getting to Know Material Design

In this course, Adi Purdila will introduce you to Material Design, Google’s widely discussed visual language. You’ll learn the definition of material, its properties, and the basic principles of the language.

In later lessons, you’ll design a very simple application using Material Design, and to finish up the course you’ll find a quiz to test what you’ve learned.

 

2. Build a Material Design App

Google's Material Design has quickly become a popular and widely implemented design language. Many Android users now expect their apps to conform to the material design spec, and app designers will expect you to be able to implement its basic principles. 

In this course, Envato Tuts+ instructor Ashraff Hathibelagal will show you how to build a practical, fully functional Material Design app that is ready to publish on Google Play. 

Starting from the app design created by instructor Adi Purdila in his course Getting to Know Material Design, you will learn how to work with the various Material Design UI widgets available in the Android Support library, such as FloatingActionButton, TextInputLayout, and RecyclerView. You will also learn how to perform read and write operations on a modern mobile database called Realm.

 

Start Learning With a Free Trial

You can take both of these courses, and also get access to our full library of web design and code courses, with a free 10-day trial of our monthly subscription. So get started today, and master Material Design and much more.

2016-08-23T14:40:03.000Z2016-08-23T14:40:03.000ZAndrew Blackman

Pokémon GO Style Augmented Reality With Vuforia

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

1. Introduction

Thanks to the wild success of Pokémon GO, augmented reality (AR) is getting a lot of attention in the mobile development world. The idea of augmented reality isn’t new, but only now is the technology finally getting close to maturity and commercial viability. But what is augmented reality exactly?

This a really broad concept that can take many different forms. The idea can be applied to entertainment, science, military, education, you name it. What these applications all have in common, though, is a real-time connection between the physical world and the digital.  

A live direct or indirect view of a physical, real-world environment whose elements are augmented (or supplemented) by computer-generated sensory input such as sound, video, graphics or GPS data. — Wikipedia

Concretely, AR is often realized in interactive experiences that overlay a camera feed with 2D or 3D objects, informed by some sensor data. 

However, creating an engaging augmented reality experience from scratch can be a real challenge. Fortunately, there are some solutions available that can make this job easier. One of the most solid augmented reality tools out there is Vuforia, an AR library that is compatible with Android, iOS, UWP, and some brands of smart glasses. 

In this tutorial we'll explore augmented reality using Vuforia. We'll explore Vuforia's features, possibilities, and challenges, and we'll also take a look at  how the SDK works and its main functions. We won't explore any code in this tutorial—future tutorials in this series will dig into coding in Vuforia, with step-by-step guides targeting all the library's main features.

2. Vuforia

Originally developed by Qualcomm and recently bought by PTC, Vuforia is on its sixth version. Its SDK is constantly evolving and is compatible with Android, iOS, UWP, and Unity. Unfortunately, Vuforia isn't open source, but its price range is reasonable, and there is no up-front cost for development or education. You can create almost any kind of AR experience on the most popular mobile platforms using Vuforia. 

2.1. How Does It Work?

Vuforia uses the device's camera feed combined with accelerometer and gyroscope data to examine the world. Vuforia uses computer vision to understand what it 'sees' on the camera to create a model of the environment. After processing the data, the system can roughly locate itself in the world, knowing its coordinates: where is up, down, left, right, and so on. What you do with this depends on your development goals.

There are multiple possibilities:

  • Using World coordinates: Any kind of object can be exhibited using some arbitrary reference, ignoring real obstacles but considering the World localization obtained. The object can be out of view and continue to "exist" in the same position. This is a system similar to the one used by Pokémon GO.
  • Recognizing targets: Vuforia can look for specific images as "targets". VuMarks, for example, a QR code-style image highly recognizable by the system, can be used as anchor points or references for any kind of object projected into the world. A magazine could be 'expanded' with this resource, with its pages opening rich interactions like videos, audio, and so on.
  • Recognizing simple objects:  Simple objects like boxes and cylinders can be recognized and used as anchor points. This method is useful for recognizing packages and making them interactive.
  • Recognizing complex objects: Vuforia can also look for complex objects, like toys, computer parts, gadgets, and so on. Those objects are previously scanned, conforming to specific requirements, and can later be recognized by the system. This functionality could be used, for example, to turn toys into live creatures, or to create interactive assistance for mechanics or service people.
  • Looking for words: English words can also be understood by Vuforia. The system can look for specific words and target some kind of interaction on them. This could be useful for learning tools for children or for language translation.
  • Recognizing the world's terrain: One of the most powerful features available on Vuforia is the ability to recognize the world as it is. Vuforia lets the user scan their surroundings and can do some hardcore processing to interpret the world by creating a 3D computer vision of the real world and its objects. Imagine a Pokémon GO-like game where the Pokémons can hide behind real objects. Wouldn't that be awesome?

2.2. Developing With Vuforia

Vuforia is compatible with multiple systems. Its software development kits (SDKs) are available for Android, iOS, UWP, and Unity. Once you download and install the SDK, you'll need to sign up for a developer account and create an app key before you can start to code.

Even though Vuforia is compatible with many systems, the easiest way to create engaging AR experiences using its SDK is definitely using Unity. Don't get me wrong, you can access almost everything that Vuforia offers when developing directly for Android or iOS. However, the process is much simpler when done using the prefabs offered on Vuforia's SDK for Unity.

3. Vuforia Targets

As mentioned before, Vuforia can seek 'targets' on the camera feed to create anchor points or references to be used by AR experiences. Those targets can assume many forms, and any file that has been previously processed by Vuforia target manager can be recognized. Targets can be created by the developer or created during execution by the user.

3.1

3.1. Image Targets

Any kind of image can be a Vuforia Image Target. However, the more detailed and intricate the image, the better it is to be recognized by the algorithm. A lot of factors will be part of the recognizing calculation, but basically the image must have a reasonable level of contrast, resolution, and distinguishing elements. A blue sky photograph wouldn't work very well, but a picture of some grass would work gracefully. Image Targets can be shipped with the application, created later and uploaded to the application through a cloud system, or directly created on the app by the user.

A image target being recognized on a application

3.2. VuMarks

VuMark works very similarly to a QR Code; however, it's much more versatile. It can assume many shapes and colors and adapt to a great number of environments. Its biggest advantage is that it's in total conformity with Vuforia's recognizing algorithm and will be easily 'found' by any Vuforia AR application. Vuforia also offers an Adobe Illustrator plugin that creates VuMarks.

3.3. Cylinder and Cube Targets

It's also possible to use cubes and cylinders as Image Targets. This is very appropriate to create engagement with product packages. Once recognized, the primitive object is used as an anchor point, and it seems to exist for the system's computer vision, allowing virtual objects to interact directly with the primitive. The virtual object could track the real object's position and orientation, for example.

Cylinder and Cube targets

3.4. Objects as Targets

One of the most interesting features of Vuforia is the possibility to recognize complex objects. A toy, a phone, a computer board, and other kinds of objects can be used as targets. 

To use this resource, you have to scan the object using the Vuforia Object Scanner tool, which runs only on Samsung Galaxy S6 and S7. The data scan is uploaded to Vuforia Target Manager, and the scanned object will be recognized by any compatible device using that data.

3.5. Managing Targets

There are multiple ways to create a target: 

  • The application can ship with a series of targets embedded.
  • The app can receive targets online through the cloud system offered by Vuforia.
  • The user themselves can use the device's camera to create a target. 

As a developer, you don't have much control about how the user will create their target; all that you can do is provide the user with some tips about how to chose an appropriate image as a target. However, the situation is different for the targets processed using the Target Manager.

Target Manager

Vuforia's developer portal provides us with the Target Manager tool to help manage all our apps' targets. The manager is very simple to use: you create a database to hold the targets, upload a file that corresponds to a target, and wait until the file is processed. The target will receive a unique ID and a score related to how recognizable it is and will then become part of the database, available for download or for storage in the cloud. 

There are three different types of target databases:

  • Device Databases are local databases of images or object targets that are stored on the user's device.
  • VuMark Databases are local databases of VuMarks that are stored on the user's device.
  • Cloud Databases are databases of Image Targets stored online and queried over the internet.

4. Smart Terrain

When developing a Vuforia app on Unity, there is a really exciting option available, the Smart Terrain. It allows an application to replicate 3D meshes of objects seen by the camera. 

The process works like some kind of scan, where the user uses the device's camera as a 3D scanner. As the camera scans through the ambient environment, the application creates 3D models of the recognized objects, giving the application the possibility to adjust the scenario to the real world, creating a deeply engaging experience.

5. Conclusion

There are hundreds of possibilities to explore with augmented reality, and we're just starting to scratch its surface. Many believe that AR will be a part of our future and that we'll use it on a day-to-day basis. This is a field that promises to grow a lot in the coming years, and Vuforia provides us with cool tools to create engaging experiences.

5.1 What's Next

In the following tutorials of this series, we'll work with some of Vuforia's most important tools. We'll develop a lot of small experiments to illustrate the SDK capabilities, and since Unity is the most AR-friendly environment available, everything will be developed on it. 

It won't be necessary to be a Unity expert to follow the tutorials—since our focus is the Vuforia SDK, I'll provide you with step-by-step guides that require only minimal previous experience with Unity.

If you want to learn a little more about Unity in the meantime, check out some of our other tutorials.

See you soon!

2016-09-12T12:01:07.000Z2016-09-12T12:01:07.000ZTin Megali

Apply Photo Filters With Core Image in Swift

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

The Power of the Core Image Framework

Core Image is an image processing and analysis technology designed to provide near real-time processing for still and video images in iOS and OS X. Apple has made a few great pre-made photo effects that you can easily use for your photography apps, with names such as Instant, Process, Sepia, Tonal, etc.

Core Image Reference

The iOS developer library provides a good explanation of Core Image image processing in the Core Image Reference Collection.

I suggest that you also check out the Core Image Filter Reference page in order to get a complete list of available CIFilters. Please note that not all of these are compatible with iOS; some of them only work on OS X. 

We will use the following Core Image filters:

  • CIPhotoEffectChrome
  • CISepiaTone
  • CIPhotoEffectTransfer
  • CIPhotoEffectTonal
  • CIPhotoEffectProcess
  • CIPhotoEffectNoir
  • CIPhotoEffectInstant
  • CIPhotoEffectFade

Note:This tutorial is written using Xcode 7.3 and Swift 2.2, with a Deployment Target set to 8.0, so your app will work on older devices too.

Let's Get Started!

Create a Project and Add Views

Open Xcode and create a new project, iOS Single View Application. Choose Swift as the language and Universal for devices. You'll get a blank UIViewController in the Storyboard and a couple of .swift files: ViewController.swift and AppDelegate.swift.

Select the controller in the Storyboard and set its size as iPhone 3.5-inch in the right-hand panel, under Simulated Metrics. This will help you to adapt views for the iPhone 4S, the Apple device with the smallest screen size available.

Set controller size to iPhone 4S

We won't use Auto Layout in this tutorial, because it messes up layouts on bigger devices like iPad and iPad Pro. Disable it by selecting File Inspector and uncheck Use Auto Layout. Then click the Disable Size Classes button from the popup.

Disable Auto Layout and Size Classes

Now find a JPEG image—either from the web or from your Mac—and drag it below the Assets.xcassets folder in the Project navigator panel. We'll use this as a sample image that we can apply our filters to. Name this file picture.jpg; we will call it later in the code.

You will have to drag some additional views into the controller. Select the Object library on the bottom-right corner of Xcode and drag a UIView to the center of the screen. Resize the view to 320 x 320 px and center it horizontally. 

Now add two UIImageViews to your Storyboard, by finding them in the Object library and dragging them into the main UIView. Resize these image views to fill that main view (we'll look at how to set their autoresizing  properties later). Assign picture.jpg to the first image view with the Attributes inspector panel.

Assign a jpg image to the first UIImageView

Next, drag a UIScrollView to the bottom of the screen, and set its width to fit the controller's width. You may also add a UILabel to the top of the controller and set its text to Filters. This will be the title of your app. 

Lastly, add a UIButtonto the top-left corner of the screen and make its title Save.

Set Autoresizing and Layout Views

The Size inspectorpanel can be shown by clicking on the little ruler icon in the top-right corner of the screen. Do that now and start editing the view sizes by selecting the UIButton. The Size inspector will show you its x and y coordinates on the screen (keep in mind that x is 0 at the left side of the screen and y is 0 at the top). Set the width and height to 44 px.

Set Save button size and margin

Set the button's autoresizing mask to attach to the top and left sides of the screen.

Now select all the other views, one by one, and adjust their size and position as follows:

Set title Label size and margins

The app title has width 320 px and height 44 px and attaches to the top of the screen.

Set imageViews size and margins

The image views each have a width and height of 320 px.

Set ScrollView size and margins

Finally, the scroll view (for filter options) has a width of 320 px and a height of 80 px.

Declaring Views in the .swift File

One of the nicest features of Xcode is the possibility to split the workspace into two parts and have the Storyboard on one side and a Swift file on the other side. In order for you to do that, you must click on the Assistant Editor icon on the top-right corner of your Xcode window:

Assistant Editor icon

If your ViewController is selected in Storyboard, the right section will automatically show its relative .swift file. In case that doesn't happen, you can try clicking on the horizontal menu on the top of the swift file and switch Manual to Automatic:

Find the controllers swift file in the right side of the Xcode window

Now let's attach some of our views to the ViewController.swift file. From the Document Outline panel, select the UIView that contains the two UIImageViews, hold down Control (or the right mouse button), and drag your mouse pointer underneath to get the class declaration of your view controller.

Release the mouse button and a popup will appear. Type in the name of the UIViewcontainerView—and click the Connect button.

You've just added a declaration for an IBOutlet of type UIView to your .swift file. Do the same thing for the other image views: drag the blue line below each instance you'll declare, and name the first one originalImage and the second one imageToFilter. Make sure that originalImage is the one with picture.jpg as an image. 

Then connect the UIScrollView and name it filtersScrollView. This will store all the buttons for applying filters to your picture.  

We'll declare our UIButton later as an IBAction. This button will allow us to save our filtered image into the Photo Library of our device.

Let's Code!

Creating an Array of Core Image Filters

In Swift, you can declare global variables by simply placing them outside a class declaration, in our case this one:

We need to create an array of CIFilter names:

As mentioned at the beginning of this tutorial, we have to use the original Core Image filter names in order for our app to recognize them. We'll assign these filters to the buttons we'll create later, which will apply the filter to our image.

Hiding the Status Bar

Most of the time, you may want to hide the Status Bar from your screen. Since Xcode 7.0, it is no longer possible to set the hidden property of the Status Bar in Info.plist, so you must add this method right above viewDidLoad()

Creating the Filter Buttons

The viewDidLoad() method is a default instance that Xcode creates each time you add a .swift file to your project; it gets called when the screen and all its views get loaded. If you wanted to perform some action even before that happens, you could use the viewDidAppear() or viewWillAppear() methods, but we don't need to. So let's add a few variables of type CGFloat right below super.viewDidLoad():

Those values are needed to place a row of buttons inside our filtersScrollView. As you can see in the above code, the xCoord is the X position where a button will be placed, yCoord is the Y position, buttonWidth and buttonHeight are its size, and gapBetweenButtons is the space between each button. 

Now we need to actually create the buttons by using a for loop that will duplicate a custom UIButton and place it into the filtersScrollView based on the above values. 

Place this code right below those CGFloat instances:

Let's see what happens in this code. itemCount is a variable we'll use later to add our filter buttons as subviews of the filtersScrollView. You may notice that we've declared this variable with the var prefix. That's because it will be modified by the for loop. If you want to declare constants in Swift, you use the let prefix, as we did for the filterButton.

Using the new for loop syntax of Swift 2.2, we don't need to write i++ anymore. The loop will increment i automatically by counting from 0 to the number of elements of the CIFilterNames array.

Inside that for loop, we create a custom button, set its CGRect values, assign it a tag, and add a target action to it that calls a function we'll see later: filterButtonTapped().

In order to make our button look nice, with round corners, we use the layer property and set its corner radius to 6. Then we clip the image to be contained in its bounds, otherwise it would cover the rounded corners.

Add the Image to the Buttons and Apply Filters

The next piece of code must be added below the comment of the previous one:

Here we initialize a CIContext and CIImage to let Core Image work on originalImage (picture.jpg) that each button will show. Then we init a filter variable of type CIFilter that will be called by each button through the for loop based on the CIFilterNames array.

Our filter instance needs to set its default state, and then it becomes the input key for images. Then we create the data object from it and its image reference, which we'll use to create a UIImage right away that will be attached to the button. 

Since the filters we've selected for this tutorial are pre-made by Apple, we don't need to apply any additional value (such as intensity, color, etc.). If you want to get information about other CIFilters, you may check the Core Image Filter Reference page.

In the last line of this section, we finally set the button's background image that we've previously created.

Adding Buttons to the ScrollView

Just a few more lines to complete our viewDidLoad() method:

We're adding buttons as sub views to the filtersScrollView based on their position and the width and space they should keep between each other. Then finally we close the for loop.

Lastly, we have to set the contentSize of our ScrollView to fit all the buttons. Here's where we finally use the itemCount variable previously declared, converted to CGFloat (because CGSizeMake it doesn't accept Int values).

The Filter Button Action

We're almost done, with just a few more lines of code!

In the ViewController class, outside viewDidLoad(), create the filterButtonTapper() function. This will be called every time you tap on one of the buttons we've generated before.

We need to create an instance of UIButton first, and then set the imageToFilter's image based on that button's background image, which has already been filtered by the code placed into viewDidLoad()

Make sure that the UIImageView called imageToFilter overlays the originalImage, as shown below, otherwise the app will not show you the processed image because the original image will hide it.

imageToFilter must be in front of originalImage

Saving the Processed Picture

We've got to the end of this tutorial, and there's just one more function to add in your .swift file. That's the Save button we've previously placed in the Storyboard. Hold Control and the mouse button, drag a blue line from the UIButton to an empty space within your class, release the mouse button, and a new popup will show up. Here you have to change the Connection type to Action and enter the name of your method—in this case savePicButton—and click the Connect button.

Declare IBAction for the Save button

You've created an IBAction this time, and here's the code that must be placed into it:

The first line simply saves the image contained into imageToFilter directly in the Photo Library of your device or iOS Simulator. Then we fire a simple UIAlertView that confirms that the operation has been made.

OK, let's run our app and see what happens if we tap the buttons on the bottom. If you've done everything correctly, your app should look like this:

App showing image with color filter applied

App showing image with color filter applied

App showing message that image has been saved to Photo Library

Thanks for reading, and I'll see you next time! Please check out some of our other tutorials on Swift and iOS app development.

2016-09-21T13:34:16.000Z2016-09-21T13:34:16.000ZFrancesco Franchini

Apply Photo Filters With Core Image in Swift

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

The Power of the Core Image Framework

Core Image is an image processing and analysis technology designed to provide near real-time processing for still and video images in iOS and OS X. Apple has made a few great pre-made photo effects that you can easily use for your photography apps, with names such as Instant, Process, Sepia, Tonal, etc.

Core Image Reference

The iOS developer library provides a good explanation of Core Image image processing in the Core Image Reference Collection.

I suggest that you also check out the Core Image Filter Reference page in order to get a complete list of available CIFilters. Please note that not all of these are compatible with iOS; some of them only work on OS X. 

We will use the following Core Image filters:

  • CIPhotoEffectChrome
  • CISepiaTone
  • CIPhotoEffectTransfer
  • CIPhotoEffectTonal
  • CIPhotoEffectProcess
  • CIPhotoEffectNoir
  • CIPhotoEffectInstant
  • CIPhotoEffectFade

Note:This tutorial is written using Xcode 7.3 and Swift 2.2, with a Deployment Target set to 8.0, so your app will work on older devices too.

Let's Get Started!

Create a Project and Add Views

Open Xcode and create a new project, iOS Single View Application. Choose Swift as the language and Universal for devices. You'll get a blank UIViewController in the Storyboard and a couple of .swift files: ViewController.swift and AppDelegate.swift.

Select the controller in the Storyboard and set its size as iPhone 3.5-inch in the right-hand panel, under Simulated Metrics. This will help you to adapt views for the iPhone 4S, the Apple device with the smallest screen size available.

Set controller size to iPhone 4S

We won't use Auto Layout in this tutorial, because it messes up layouts on bigger devices like iPad and iPad Pro. Disable it by selecting File Inspector and uncheck Use Auto Layout. Then click the Disable Size Classes button from the popup.

Disable Auto Layout and Size Classes

Now find a JPEG image—either from the web or from your Mac—and drag it below the Assets.xcassets folder in the Project navigator panel. We'll use this as a sample image that we can apply our filters to. Name this file picture.jpg; we will call it later in the code.

You will have to drag some additional views into the controller. Select the Object library on the bottom-right corner of Xcode and drag a UIView to the center of the screen. Resize the view to 320 x 320 px and center it horizontally. 

Now add two UIImageViews to your Storyboard, by finding them in the Object library and dragging them into the main UIView. Resize these image views to fill that main view (we'll look at how to set their autoresizing  properties later). Assign picture.jpg to the first image view with the Attributes inspector panel.

Assign a jpg image to the first UIImageView

Next, drag a UIScrollView to the bottom of the screen, and set its width to fit the controller's width. You may also add a UILabel to the top of the controller and set its text to Filters. This will be the title of your app. 

Lastly, add a UIButtonto the top-left corner of the screen and make its title Save.

Set Autoresizing and Layout Views

The Size inspectorpanel can be shown by clicking on the little ruler icon in the top-right corner of the screen. Do that now and start editing the view sizes by selecting the UIButton. The Size inspector will show you its x and y coordinates on the screen (keep in mind that x is 0 at the left side of the screen and y is 0 at the top). Set the width and height to 44 px.

Set Save button size and margin

Set the button's autoresizing mask to attach to the top and left sides of the screen.

Now select all the other views, one by one, and adjust their size and position as follows:

Set title Label size and margins

The app title has width 320 px and height 44 px and attaches to the top of the screen.

Set imageViews size and margins

The image views each have a width and height of 320 px.

Set ScrollView size and margins

Finally, the scroll view (for filter options) has a width of 320 px and a height of 80 px.

Declaring Views in the .swift File

One of the nicest features of Xcode is the possibility to split the workspace into two parts and have the Storyboard on one side and a Swift file on the other side. In order for you to do that, you must click on the Assistant Editor icon on the top-right corner of your Xcode window:

Assistant Editor icon

If your ViewController is selected in Storyboard, the right section will automatically show its relative .swift file. In case that doesn't happen, you can try clicking on the horizontal menu on the top of the swift file and switch Manual to Automatic:

Find the controllers swift file in the right side of the Xcode window

Now let's attach some of our views to the ViewController.swift file. From the Document Outline panel, select the UIView that contains the two UIImageViews, hold down Control (or the right mouse button), and drag your mouse pointer underneath to get the class declaration of your view controller.

Release the mouse button and a popup will appear. Type in the name of the UIViewcontainerView—and click the Connect button.

You've just added a declaration for an IBOutlet of type UIView to your .swift file. Do the same thing for the other image views: drag the blue line below each instance you'll declare, and name the first one originalImage and the second one imageToFilter. Make sure that originalImage is the one with picture.jpg as an image. 

Then connect the UIScrollView and name it filtersScrollView. This will store all the buttons for applying filters to your picture.  

We'll declare our UIButton later as an IBAction. This button will allow us to save our filtered image into the Photo Library of our device.

Let's Code!

Creating an Array of Core Image Filters

In Swift, you can declare global variables by simply placing them outside a class declaration, in our case this one:

We need to create an array of CIFilter names:

As mentioned at the beginning of this tutorial, we have to use the original Core Image filter names in order for our app to recognize them. We'll assign these filters to the buttons we'll create later, which will apply the filter to our image.

Hiding the Status Bar

Most of the time, you may want to hide the Status Bar from your screen. Since Xcode 7.0, it is no longer possible to set the hidden property of the Status Bar in Info.plist, so you must add this method right above viewDidLoad()

Creating the Filter Buttons

The viewDidLoad() method is a default instance that Xcode creates each time you add a .swift file to your project; it gets called when the screen and all its views get loaded. If you wanted to perform some action even before that happens, you could use the viewDidAppear() or viewWillAppear() methods, but we don't need to. So let's add a few variables of type CGFloat right below super.viewDidLoad():

Those values are needed to place a row of buttons inside our filtersScrollView. As you can see in the above code, the xCoord is the X position where a button will be placed, yCoord is the Y position, buttonWidth and buttonHeight are its size, and gapBetweenButtons is the space between each button. 

Now we need to actually create the buttons by using a for loop that will duplicate a custom UIButton and place it into the filtersScrollView based on the above values. 

Place this code right below those CGFloat instances:

Let's see what happens in this code. itemCount is a variable we'll use later to add our filter buttons as subviews of the filtersScrollView. You may notice that we've declared this variable with the var prefix. That's because it will be modified by the for loop. If you want to declare constants in Swift, you use the let prefix, as we did for the filterButton.

Using the new for loop syntax of Swift 2.2, we don't need to write i++ anymore. The loop will increment i automatically by counting from 0 to the number of elements of the CIFilterNames array.

Inside that for loop, we create a custom button, set its CGRect values, assign it a tag, and add a target action to it that calls a function we'll see later: filterButtonTapped().

In order to make our button look nice, with round corners, we use the layer property and set its corner radius to 6. Then we clip the image to be contained in its bounds, otherwise it would cover the rounded corners.

Add the Image to the Buttons and Apply Filters

The next piece of code must be added below the comment of the previous one:

Here we initialize a CIContext and CIImage to let Core Image work on originalImage (picture.jpg) that each button will show. Then we init a filter variable of type CIFilter that will be called by each button through the for loop based on the CIFilterNames array.

Our filter instance needs to set its default state, and then it becomes the input key for images. Then we create the data object from it and its image reference, which we'll use to create a UIImage right away that will be attached to the button. 

Since the filters we've selected for this tutorial are pre-made by Apple, we don't need to apply any additional value (such as intensity, color, etc.). If you want to get information about other CIFilters, you may check the Core Image Filter Reference page.

In the last line of this section, we finally set the button's background image that we've previously created.

Adding Buttons to the ScrollView

Just a few more lines to complete our viewDidLoad() method:

We're adding buttons as sub views to the filtersScrollView based on their position and the width and space they should keep between each other. Then finally we close the for loop.

Lastly, we have to set the contentSize of our ScrollView to fit all the buttons. Here's where we finally use the itemCount variable previously declared, converted to CGFloat (because CGSizeMake it doesn't accept Int values).

The Filter Button Action

We're almost done, with just a few more lines of code!

In the ViewController class, outside viewDidLoad(), create the filterButtonTapper() function. This will be called every time you tap on one of the buttons we've generated before.

We need to create an instance of UIButton first, and then set the imageToFilter's image based on that button's background image, which has already been filtered by the code placed into viewDidLoad()

Make sure that the UIImageView called imageToFilter overlays the originalImage, as shown below, otherwise the app will not show you the processed image because the original image will hide it.

imageToFilter must be in front of originalImage

Saving the Processed Picture

We've got to the end of this tutorial, and there's just one more function to add in your .swift file. That's the Save button we've previously placed in the Storyboard. Hold Control and the mouse button, drag a blue line from the UIButton to an empty space within your class, release the mouse button, and a new popup will show up. Here you have to change the Connection type to Action and enter the name of your method—in this case savePicButton—and click the Connect button.

Declare IBAction for the Save button

You've created an IBAction this time, and here's the code that must be placed into it:

The first line simply saves the image contained into imageToFilter directly in the Photo Library of your device or iOS Simulator. Then we fire a simple UIAlertView that confirms that the operation has been made.

OK, let's run our app and see what happens if we tap the buttons on the bottom. If you've done everything correctly, your app should look like this:

App showing image with color filter applied

App showing image with color filter applied

App showing message that image has been saved to Photo Library

Thanks for reading, and I'll see you next time! Please check out some of our other tutorials on Swift and iOS app development.

2016-09-21T13:34:16.000Z2016-09-21T13:34:16.000ZFrancesco Franchini
Viewing all 1836 articles
Browse latest View live