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

Google I/O 2015 Aftermath

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

Every year developers sit on the edge of their seats waiting for Google I/O to come along and wow us with the introduction of new features, services, and development tools. Last year Google focused on revolutions by introducing new form factors, such as Android Wear, and Material Design.

This year, Google took the necessary steps of focusing on enhancements to the Android operating system and providing developers with the tools they need to build better applications. On top of this, they introduced some interesting new tech to boot.

Let's take a few minutes to go over what was discussed at the conference, what's available right now, and what will be coming out over the next few months.

1. Android

Arguably the largest focus this year at Google I/O was the Android platform. First and foremost is the announcement of the Android M developer preview, following their earlier precedent from Lollipop of releasing beta versions of the operating system for developers.

Google also announced that they are working with manufacturers to move towards a standard bidirectional USB-C device connector, granting new Android devices the ability to charge three to five times faster.

Continuing their recent focus on efficiency and power consumption, Google announced new APIs and features of the operating system meant to conserve device battery. In addition, Google introduced a plethora of improvements to the Play Store to help engage users and tools for developers to build apps through use of support libraries and new APIs.

Android M Developer Preview

The biggest piece of news coming from Google I/O this year was the announcement of a new version of the Android operating system, Android M, which will be released during Q3 of this year.

M is an enhancement to the current Lollipop operating system and focuses on polish and software quality. This newest iteration of Android includes thousands of bug fixes from Lollipop, new hardware APIs, and improved power management.

Google will be releasing multiple updates to the M preview with bug fixes and additional features, roughly once a month until the official release. The Android M developer preview is currently available for the Nexus 5, 6, 9, and Player.

Devices that support the M preview

Doze

First discussed during the Google I/O Keynote, Doze is a new feature of Android M that uses significant motion detection to determine if a device is being used. If it isn't, then the operating system exponentially backs off network activity to conserve battery while the device is idle.

While a device is in doze mode, it can still wake itself up to respond to alarms and high priority notifications. According to Google, idling two Nexus 9 tablets, one running Android Lollipop and the other running Android M, resulted in the M device battery lasting twice as long.

Android M APIs

With every Android update comes a new set of APIs developers can use to improve their apps. While this list of new APIs is much shorter this year, they are nonetheless impressive.

Many of the new APIs are focused on hardware, such as enhanced authentication using fingerprint scanners, improved stylus support for buttons and gestures, and a 4K display mode. Google has even introduced an API that deals with voice interactions, allowing applications to communicate with users through conversation.

Additional APIs available in Android M are focused on user engagement. One such API is direct sharing, which lets users share information about an app with specific targets, such as email or hangouts contacts.

Another API, App Links, lets devices automatically associate web URLs with a verified application, rather than having to go through an app selection dialog. Even more powerful is the Assist API. Using Assist, you will be able to implement contextually aware Google Now functionality directly into your app. Assist bases results on the content being displayed to the user. The goal is to provide answers and possible actions to the user as they're needed.

In addition to this, Google has added a feature known as Now on Tap. Now on Tap allows users to hold down the device's home button to generate Now cards based on in-app information.

Contextually Aware Google Now in App

Runtime Permissions

For years, users have asked for a solution to the all-or-nothing approach of app permissions in Android. Starting with M, Google has introduced runtime permissions for applications.

Instead of requiring users to accept all permissions at install time, a dialog will prompt users to allow or deny a permission when it is required. If the user denies the permission, the requesting process will terminate and the application will need to fall back on a contingency.

To help users, Android has regrouped permissions into a set of easy to understand categories. It is important to note that these permission categories can be denied or allowed at any time through the device's settings screen.

Example of a permissions dialog

Play Services 7.5

In addition to the M preview, Google has rolled out version 7.5 of Play Services. Luckily, this library includes a lot of new and interesting features. Last year, the JobScheduler API was released, allowing developers to batch operations when certain conditions were met by the system in order to save battery. The downside of the API is that it only ran on Lollipop. With this new version of Play Services, Google has introduced the GcmNetworkManager, which is essentially a backwards compatible JobScheduler that falls back to the JobScheduler when it is available.

Other useful additions include:

  • Google Cloud Messages that can be subscribed to and filtered by topic.
  • App Invites allow users to send an install link directly to their friends.
  • Google Cast remote displays let users view different content on their device and another screen, such as a television.
  • The Google Maps API can now run on Android Wear devices.
  • Google improved Google Fit data and added dozens of newly supported workout exercises.

Design Support Library

Alongside the Play Services update, Google introduced the Design Support Library. Using this support library, developers are now able to implement various user interface components back to API 7, which were previously only available in Android Lollipop or through third-party libraries.

Some of the components available include floating action buttons, navigation drawer headers, and a new container called the CoordinatorLayout, which automatically moves views as other views change size or visibility.

Example of a navigation drawer with a header

Play Store Enhancements

During this year's Keynote, Google also announced a number of new features for the Play Store. One set of improvements revolves around providing statistics to help increase app download rates.

In the updated Google Play Developers Console, developers will now be able to view how many users have looked at their application in the store compared to how many have committed to installing. Developers will also be able to use Experiments, a service that allows them to try variants of their app store listing to see what changes may drive more downloads.

In addition to the application's store listing, developers will be able to create custom Google Play home pages for displaying all of their applications as well as some information about the developer or the company.

Another set of improvements is focused on what content is displayed when users search through the Play Store. The store can now be more aware of specific apps that match a user's search criteria and, when a search is vague, the user will be provided with a set of categories with apps that may meet their needs.

The last major change to the Play Store is a shift in how apps for children and families are found. Apps can now have a rating and a label that indicate whether the content is suitable for families. Users can also search for apps while filtering by specific age groups. Alongside traditional methods of finding apps, the Play Store has also introduced a character search feature, allowing parents to search for apps based on their children's favorite book, movie or cartoon characters.

Updated Developer Console Showing Views vs Installs

Android Pay

Confirming the rumors that had been floating around before Google I/O, Google launched a new service called Android Pay. Using NFC, Android Pay allows users to perform transactions in over 700,000 retail locations that accept contactless payments.

Android Pay keeps security in the forefront by using a virtual account number for transactions, rather than sharing the user's actual card number. Likewise, users on Android M will have an additional layer of security available through the use of hardware fingerprint scanners.

Pay can also be integrated into applications, allowing users to quickly and easily purchase goods from their device. Android Pay will be supported on any device with NFC, back to Android KitKat.

Android Pay Console

Android Development Tools

Two years ago, Google introduced the first beta of Android Studio, and since then they have been continuously improving the IDE to make the lives of developers that much easier.

This year was no exception. Google released Android Studio 1.3 on the canary channel. The newest version includes great features, such as faster gradle build speeds, a new memory profiler, new support annotations, and the ability to bind data models with views through XML layout files.

Android Studio has also added one of the most requested development features, better native development support. Full editing and debugging support with error correction, code completion and debugging for C++ applications are now available for developers using the NDK.

C Debugging in Android Studio

While the tools for building applications have been improved, Google has also added a new service, following their acquisition of Appurify, called Cloud Test Lab. Using Cloud Test Lab, developers can upload their application and Google will run tests on the top 20 most popular Android devices. After completing the tests, Cloud Test Lab will deliver a free report, containing crash logs and a video of the running application.

2. Google Photos

One of the more exciting announcements at Google I/O was the introduction of Google Photos. Breaking away from Google+, Photos is available for iOS, Android, and the web. The service automatically categorizes images and creates collections based on timelines and albums, helping to help organize content.

Searching has been improved by giving users the ability to quickly browse by day, month, or year. Not only does Google Photos store images, it also allows users to perform basic photo editing, create movies, collages, and animations from their pictures. Best of all, Google will store your photos in high resolution for free with unlimited storage.

3. Cardboard

Since Cardboard was announced at Google I/O 2014, over one million viewers have been assembled. This year, Google has made some simple updates to their VR headset, such as adding a button that is usable with more devices and changing the dimensions to support any phone up to six inches.

Google has also updated the Unity SDK to support iOS devices and the company released a version of the viewer application to the Apple's App Store. While the Cardboard headset is interesting in itself, what Google has planned to do with it is what's really magical.

Expeditions

As a part of the Google in Education initiative, Google has introduced a new program called Expeditions. Through Expeditions, preassembled kits with Cardboard headsets, phones, and an instructor tablet will be sent to classrooms to allow children to experience simulated field trips.

Expeditions will consist of high definition, 360 degree videos of locations across the globe. While on these field trips, teachers will be able to discuss the scene the children are seeing and teach them in a more fun and interactive way.

Children viewing Expeditions using Cardboard

Jump

To create the high quality, 360 degree videos that Expeditions and Cardboard will require, Google has created a system it dubs Jump. Jump consists of three parts. The first part is a physical array of sixteen cameras collaborated to film in all angles with multiple points of intersection. While Google will release the schematics for building a Jump rig from scratch, they have also partnered with GoPro to sell one that is preassembled.

GoPro Jump Array

The second part of the Jump system is known as the Assembler. Using powerful computers in the cloud, content from a Jump rig can be uploaded and processed in order to smooth images, balance colors, and create stereoscopic VR videos. When this service is first turned on this summer, it will only be available to select creators until the official launch later this year.

The third and final part of Jump is getting this content to users. This is done by adding support for VR videos on YouTube. This means that anyone with a Cardboard headset can begin accessing it this summer.

4. Internet of Things

With the acquisition of Nest last year, Google has started work on getting involved with the Internet of Things (IoT). As they pointed out during the keynote presentation, one of the biggest challenges facing the Internet of Things right now is the lack of uniform software and communication between devices.

To help overcome this challenge, they've introduced two new technologies, Brillo and Weave. Brillo is an underlying operating system for IoT devices, derived from Android and polished down to be lightweight while still supporting features such as bluetooth communication.

Weave is a common language, similar to JSON, for devices that need to communicate with each other, be it devices in the cloud, a phone, or IoT hardware. As of right now, information is sparse on both Brillo and Weave. Brillo, however, should be released in Q3 of 2015, and Weave will be available by Q4 of this year with some information coming throughout the year.

5. Project Jacquard

As other items in the world become more connected, it makes sense that the concept of wearables will shift to also include clothing. Project Jacquard revolves around the use of strong conductive fabrics that can withstand the strain of industrial looms. The goal of Project Jacquard is to allow innovators to design and create furniture and clothing that can react to touches and gestures to control other electronics embedded in the fabric.

6. Optimization for Lower End Devices

To improve the experience for users across the world, Google has adopted multiple techniques to make browsing from a mobile device more efficient. Chrome is currently using an optimized search page for fourteen countries to support slower connections, such as 2G.

When Chrome is optimized, web pages load four times faster and use 80% less data. Taking the lessons learned from these fourteen countries, Google plans to use optimized web pages across the globe for lower end devices as determined by their new Network Quality Estimator tool.

Other techniques used include displaying a stock thumbnail instead of download images for the user so that they are not using data unnecessarily, and allowing users to save web pages for offline use.

Recently YouTube has begun testing offline video support up to 48 hours in four countries so that videos can be viewed later without an active network connection. Likewise, Google Maps is in the process of allowing offline maps and step-by-step directions, which will be available later this year.

Network Quality Estimator at work

7. More Development Tools

Polymer has finally been officially released as version 1.0. This milestone release includes new features, such the ability to drop in common features like charts and toolbars, and a fast data-binding system.

For iOS developers, Google announced that they are adopting CocoaPods as the primary method to deliver their SDK to iOS developers. 

Conclusion

This year, like most, Google I/O covered a lot of ground. From education with Cardboard to stepping into the Internet of Things arena, Google continues to demonstrate that they are a versatile company that is invested in the development community. We live in interesting times and they're only going to get more interesting.

2015-06-05T18:05:51.000Z2015-06-05T18:05:51.000ZPaul Trebilcox-Ruiz

How to Use Kotlin in Your Android Projects

$
0
0

Introduction

Kotlin, the open source programming language designed by JetBrains, is becoming increasingly popular among Java developers. It is often touted as Java's successor. Compared to Java, it offers a richer development experience, because it is more modern, expressive, and concise.

If you are looking for an alternative programming language for Android development, you should give Kotlin a try. It can easily be used instead of or alongside Java in your Android projects.

In this tutorial, I will show you how to use Kotlin and Kotlin plugins in your Android Studio projects.

Prerequisites

To follow along with me, you need to have:

  • the latest version of Android Studio
  • a basic understanding of Kotlin syntax

If you're unfamiliar with the Kotlin programming language, then I recommend reading the Getting Started section of the Kotlin reference to get up to speed with the language.

1. Installing Kotlin Plugins

In Android Studio's quick start menu, select Configure > Plugins.

Configure Plugins

In the next screen, click Install JetBrains plugin... at the bottom.

Install JetBrains plugin

Select Kotlin Extensions For Android from the list and click Install Plugin on the right.

Install Kotlin Extensions For Android

Because the plugin depends on the Kotlin plugin, you will be asked to install both. Click Yes to begin the installation.

Plugin Dependencies Detected

When the installation completes, restart Android Studio to activate the plugins.

2. Creating a Kotlin Activity

In Android Studio, right-click the name of your package and select New > Kotlin File.

New  Kotlin File

In the dialog that pops up, enter the name of the new Activity and select Class from the drop-down list. I've named my class MainActivity.

New Kotlin file dialog

Once the class has been created, you will see an alert asking you to configure your app module to support Kotlin.

Configure Kotlin alert

Click the link in the alert and, in the dialog that pops up, click OK to choose the default values.

Configure Kotlin dialog

To configure your project to support Kotlin, the Kotlin plugin makes several changes in the build.gradle file. Apply these changes by clicking the Sync Now button as shown below.

Sync Now pop up

At this point, your project's configuration is complete. Go back to the Kotlin class you created a moment ago to start coding in Kotlin.

3. Using Kotlin

To keep the example simple, I will be showing you how to create an Activity with a single TextView that displays a String.

Make sure your class is a subclass of Activity and override its onCreate method. Of course, you have to do that in Kotlin. If you are new to Kotlin, I suggest you use Android Studio's code generation functionality by pressing Control+O to get the method signatures right.

Override Members dialog

Your class should now look like this:

Create an instance of TextView as an assign-once local variable by using the val keyword.

Call its setText method to set the String you want to display and then call setContentView to display the text view.

Like you would for a Java Activity, you need to declare your Kotlin Activity in your app's AndroidManifest.xml for it to be recognized by the Android system. If this is the only Activity in your project, your manifest file should look like this:

You can now compile and run your app on your Android device or emulator. While the Kotlin compiler is slightly slower than that of Java, you are unlikely to see any significant change in your project's build time.

4. Using Kotlin Android Extensions

The Kotlin Android Extensions plugin lets you treat the widgets you define in the layout XML of an Activity as if they were properties of that Activity. In other words, if you use this plugin, you will never have to call findViewById. These properties are aptly called synthetic properties.

To use this feature in your app, you need to add org.jetbrains.kotlin:kotlin-android-extensions as a build script dependency in your app module's build.gradle as shown below. Don't forget to click the Sync Now button to sync your project.

Let's now create an Activity similar to the one we created in the previous step, but use a layout XML to define the TextView. Create a new layout XML file named another_activity.xml. In the layout XML file, define a TextView with an id of myMessage.

Create another Kotlin class, AnotherActivity, that extends Activity and override its onCreate method. This is what the implementation should look like:

Call setContentView in the onCreate method to use the layout XML you just created as the layout of this Activity.

Now, instead of calling findViewById to get a reference to the TextView, you can import it using the following code snippet:

If you had more widgets in your layout, you can import all of them using the following code snippet:

You can now access your TextView using its id as if it were a property of the Activity class. For example, to change the text of the TextView, you can write:

5. Converting Java Classes to Kotlin

You can use the Kotlin plugin to convert existing Java classes to Kotlin classes. To try this feature, create a new Java class with the following implementation. It's a simple Activity that logs the sum of two integers.

Convert the Java class to a Kotlin class by pressing Control+Alt+Shift+J, or, from the menu, selecting Code > Convert Java File to Kotlin File.

Convert Java file to Kotlin file

After the conversion, your class will look like this:

You will also notice that the file's extension has changed from .java to .kt.

Conclusion

In this tutorial, you have learned how to use Kotlin in your Android projects after installing the Kotlin plugin and the Kotlin Android Extensions plugin for Android Studio. As Kotlin and Java classes are largely interoperable, if you are still learning Kotlin, it is best to introduce it in your Android projects gradually.

To learn more about Kotlin, I recommend browsing the Kotlin reference. The Getting Started section will help you get up to speed with this new language.


2015-06-08T16:45:00.000Z2015-06-08T16:45:00.000ZAshraff Hathibelagal

How to Use Kotlin in Your Android Projects

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

Introduction

Kotlin, the open source programming language designed by JetBrains, is becoming increasingly popular among Java developers. It is often touted as Java's successor. Compared to Java, it offers a richer development experience, because it is more modern, expressive, and concise.

If you are looking for an alternative programming language for Android development, you should give Kotlin a try. It can easily be used instead of or alongside Java in your Android projects.

In this tutorial, I will show you how to use Kotlin and Kotlin plugins in your Android Studio projects.

Prerequisites

To follow along with me, you need to have:

  • the latest version of Android Studio
  • a basic understanding of Kotlin syntax

If you're unfamiliar with the Kotlin programming language, then I recommend reading the Getting Started section of the Kotlin reference to get up to speed with the language.

1. Installing Kotlin Plugins

In Android Studio's quick start menu, select Configure > Plugins.

Configure Plugins

In the next screen, click Install JetBrains plugin... at the bottom.

Install JetBrains plugin

Select Kotlin Extensions For Android from the list and click Install Plugin on the right.

Install Kotlin Extensions For Android

Because the plugin depends on the Kotlin plugin, you will be asked to install both. Click Yes to begin the installation.

Plugin Dependencies Detected

When the installation completes, restart Android Studio to activate the plugins.

2. Creating a Kotlin Activity

In Android Studio, right-click the name of your package and select New > Kotlin File.

New  Kotlin File

In the dialog that pops up, enter the name of the new Activity and select Class from the drop-down list. I've named my class MainActivity.

New Kotlin file dialog

Once the class has been created, you will see an alert asking you to configure your app module to support Kotlin.

Configure Kotlin alert

Click the link in the alert and, in the dialog that pops up, click OK to choose the default values.

Configure Kotlin dialog

To configure your project to support Kotlin, the Kotlin plugin makes several changes in the build.gradle file. Apply these changes by clicking the Sync Now button as shown below.

Sync Now pop up

At this point, your project's configuration is complete. Go back to the Kotlin class you created a moment ago to start coding in Kotlin.

3. Using Kotlin

To keep the example simple, I will be showing you how to create an Activity with a single TextView that displays a String.

Make sure your class is a subclass of Activity and override its onCreate method. Of course, you have to do that in Kotlin. If you are new to Kotlin, I suggest you use Android Studio's code generation functionality by pressing Control+O to get the method signatures right.

Override Members dialog

Your class should now look like this:

Create an instance of TextView as an assign-once local variable by using the val keyword.

Call its setText method to set the String you want to display and then call setContentView to display the text view.

Like you would for a Java Activity, you need to declare your Kotlin Activity in your app's AndroidManifest.xml for it to be recognized by the Android system. If this is the only Activity in your project, your manifest file should look like this:

You can now compile and run your app on your Android device or emulator. While the Kotlin compiler is slightly slower than that of Java, you are unlikely to see any significant change in your project's build time.

4. Using Kotlin Android Extensions

The Kotlin Android Extensions plugin lets you treat the widgets you define in the layout XML of an Activity as if they were properties of that Activity. In other words, if you use this plugin, you will never have to call findViewById. These properties are aptly called synthetic properties.

To use this feature in your app, you need to add org.jetbrains.kotlin:kotlin-android-extensions as a build script dependency in your app module's build.gradle as shown below. Don't forget to click the Sync Now button to sync your project.

Let's now create an Activity similar to the one we created in the previous step, but use a layout XML to define the TextView. Create a new layout XML file named another_activity.xml. In the layout XML file, define a TextView with an id of myMessage.

Create another Kotlin class, AnotherActivity, that extends Activity and override its onCreate method. This is what the implementation should look like:

Call setContentView in the onCreate method to use the layout XML you just created as the layout of this Activity.

Now, instead of calling findViewById to get a reference to the TextView, you can import it using the following code snippet:

If you had more widgets in your layout, you can import all of them using the following code snippet:

You can now access your TextView using its id as if it were a property of the Activity class. For example, to change the text of the TextView, you can write:

5. Converting Java Classes to Kotlin

You can use the Kotlin plugin to convert existing Java classes to Kotlin classes. To try this feature, create a new Java class with the following implementation. It's a simple Activity that logs the sum of two integers.

Convert the Java class to a Kotlin class by pressing Control+Alt+Shift+J, or, from the menu, selecting Code > Convert Java File to Kotlin File.

Convert Java file to Kotlin file

After the conversion, your class will look like this:

You will also notice that the file's extension has changed from .java to .kt.

Conclusion

In this tutorial, you have learned how to use Kotlin in your Android projects after installing the Kotlin plugin and the Kotlin Android Extensions plugin for Android Studio. As Kotlin and Java classes are largely interoperable, if you are still learning Kotlin, it is best to introduce it in your Android projects gradually.

To learn more about Kotlin, I recommend browsing the Kotlin reference. The Getting Started section will help you get up to speed with this new language.


2015-06-08T16:45:00.000Z2015-06-08T16:45:00.000ZAshraff Hathibelagal

WWDC 2015 Aftermath

$
0
0

Earlier this week, Apple officially kicked off their annual WWDC (Worldwide Developers Conference) event in San Francisco. As always, the event began with a keynote during which Apple announced updates for their OS X, iOS, and watchOS platforms. This year the keynote also included the official announcement of Apple's new music streaming service, Apple Music.

iOS 9

This year's iOS update is an incremental update and doesn't include as many new features as iOS 8 or iOS 7 had. The clear focus for iOS 9 is refining existing iOS features and usability to make the overall experience better for the user. This is evident by the fact that iOS 9 is supported by every device that runs iOS 8, including the iPhone 4S, iPad 2, iPod Touch 5G, and the very first iPad mini.

For the first time ever, a public beta of iOS 9 will be available sometime in July, enabling non-developers to try out the update and to provide feedback to Apple. A subtle but definitely noticeable change in iOS 9 is the changing of the standard system font from Helvetica Neue to San Fransisco, the font Apple created for the Apple Watch.

The other new aspects of iOS 9 are split into four distinct categories:

  • Intelligence
  • Apps
  • iPad
  • Foundation

Intelligence

Siri is receiving an important update in iOS 9. In addition to improving voice recognition accuracy, the update also adds a number of new capabilities. This includes the ability for more advanced searches. For example, the phrase "Show me photos from Utah." will now show all the photos on your device that match the specified location. Similar searches can also be performed with dates and times, in addition to location.

Siri can now also create contextual reminders based on the app you're currently in. For example, if you're viewing a web page in Safari or a message in Messages, you can ask Siri to "Remind me about this." and Siri will create a reminder that contains the content you are currently looking at or, in the case of a web page, a link to the content. In iOS 9 Siri also gains a more colorful look, similar to that of the Apple Watch.

Siris new look and feel

These improvements culminate in a new feature Apple calls Proactive Assistant. The new assistant can be accessed by swiping to the left of the home screen—where search was located before iOS 8—and provides access to Spotlight search, contacts, and app suggestions by Siri, nearby activities, and news items.

This new Proactive Assistant also adds calendar items automatically for you by detecting event times and locations in emails and messages received on your device. It even learns your daily habits and can present content when it thinks you will need it, for example, music on your daily commute to work.

In terms of privacy, the personal information collected by this assistant is completely in control of the user and does not leave the device. For items that do require communication with Apple's network, the information transmitted is completely anonymous and not linked to your Apple ID.

Proactive Assistant

In iOS 9, Passbook has been rebranded as Wallet and includes some new additions to the Apple Pay service. Apple Pay will be able to store not only credit cards but also store cards for VIP services as well as offers on a merchant-by-merchant basis.

Later this year, Apple Pay will also be launching in the UK. It will be available in a wide range of leading retailers as well as on public transport systems in London.

Apps

The Notes app in iOS 9 gains some important features, including a new formatting toolbar to easily format text, create lists, and even add images. In addition to regular bulleted and numbered lists, the new Notes app lets you create checked lists, which you can tick off as you complete the items in the list.

Notes now also includes a basic drawing tool to illustrate your ideas quickly and easily. Multiple types of content can now be added to your notes, including images and links. When a note includes a link, a clickable button with a thumbnail preview is displayed, taking you directly to the linked web page.

The new Notes app

Maps also received a significant update in iOS 9, especially interesting for people who travel via public transport. A new map category, Transit, displays bus, subway, and other public transport routes and stations.

The data used for these maps is so detailed that, for large stations and buildings, it even shows you exactly where the different entrances and exits are, giving you clear walking directions. When iOS 9 is launched later this year, the following cities will have Transit data available:

Transit Maps

Also launching with iOS 9 is a brand new News app. It will provide beautifully styled articles, designed specifically for iOS devices, based on your interests. Content creators can layout their articles specifically for the iOS News app with specialized layouts, elegant animations, and embedded photo galleries.

At launch, there will be numerous pieces available from major content creators, such as The New York Times and WIRED magazine.

The brand new News app

iPad

With iOS 9, the iPad received a number of great features that will help increase productivity. The first of these new features is the QuickType keyboard. In addition, to the suggestion bar introduced in iOS 8, on iPad this bar will now also show cut, copy, and paste shortcuts as well as other formatting options.

By panning with two fingers across the keyboard, you can also turn it into a trackpad to quickly move the cursor and select portions of text.

The QuickType keyboard will help increase productivity

Split-screen multitasking is finally coming to the iPad in iOS 9. You can now drag in from the right hand edge of the screen to "slide over" another fully functional app. This feature, known as Slide Over, is available on iPad Air, iPad Air 2, iPad mini 2, and iPad mini 3.

In addition to Slide Over, iPads can now also display a video, FaceTime call, or any third party video content in a picture-in-picture resizable view that remains on top of your content, no matter where you are in iOS.

Multitasking with Slide Over

On the iPad Air 2, you can go a step further and have two active apps side by side at the same time, allowing full multitasking between applications.

Split Screen Multitasking

Foundation

iOS 9 also includes many under-the-hood improvements to make the whole experience better across the entire operating system. The first of these improvements is in the form of extended battery life. By making the operating system, apps, and key technologies more efficient, your devices running iOS 9 will be able to last an hour longer per charge. An brand new Low Power mode can add up to another three hours of battery life on top of the existing one hour improvement.

iOS 9 also has a much improved system update process that requires, compared to iOS 8, far less free space to install. To install iOS 9, your device will only need 1.3 GB of free space, compared to the 4.58 GB that iOS 8 required. You will also be able to choose to update your device at a convenient time when you're not using your device.

Finally, the core apps and technologies of iOS 9 have been redesigned to take advantage Metal, Apple's excellent 3D graphics API. This results in the entire system running much faster with smoother animations, making everything feel fluid and natural.

OS X El Capitan

Apple also announced the successor to last year's OS X YosemiteOS X El Capitan. This update to OS X has been developed on the same principles as iOS 9, refinement and improving the operating system as a whole.

Just like iOS, the system font has been changed to San Fransisco and a public beta will be available in July to anyone with an Apple ID. The most important new features and improvements in OS X El Capitan fall under the focuses of experience and performance.

Experience

One of the first new features in OS X El Capitan is Split View. What this enables you to do is fill the screen with two apps side-by-side, eliminating all other distractions. The size of each app in this split view can be customized very easily, without the need to manually drag windows around.

This focus to improve window organization has also led to a more streamlined and functional Mission Control. In this view, windows will no longer be stacked on top of one another and it's easier than ever before to create a new desktop space by simply dragging a window to the top of the screen.

Mission Control is now more powerful than ever

Spotlight search also gained some significant improvements. It can now display weather, stocks, sports information, and even video links. You can now also search using a more natural syntax, such as "Documents I worked on yesterday" and Spotlight will return the correct results for you. This natural search syntax can also be used in Finder and Mail.

The Mail app in El Capitan also received a major update, which is especially useful when used full screen. When composing a new email, you can now minimize the window to the bottom of the app to continue looking at other messages. In this composition window, you can even open multiple tabs to write severals emails side by side. On OS X, Mail now also has swipe gestures, similar to the ones Mail for iOS features.

With OS X El Capitan, Safari also managed to grab a few small usability features. You can now pin websites to the left side of the existing tab bar to keep them readily accessible. While pinned, Safari will also keep that web page active in the background so that they are always up to date whenever you decide to open them. Safari will now also show you which tabs are playing audio and will provide a quick and easy way to mute all tabs in the case of some surprise audio.

Pinned Websites

This year's update to OS X also shares some common functionality with iOS 9, specifically all of the new features outlined earlier in iOS 9's Notes and Maps apps. OS X El Capitan will also have support for third party extensions in the Photos app. These extensions will be available through the Mac App Store.

Performance

The biggest performance boost for OS X El Capitan is going to come from the availability of Apple's Metal Graphics API on Mac. Introduced last year for specific devices alongside iOS 8, Metal is a replacement to both OpenGL and OpenCL, and will speed up the system-level graphics of OS X by up to 50% and allow for 10x faster draw call performance.

Metal for Mac

The overall improvements across the entire operating system will also allow for 1.4x faster app launch and 2x faster app switching.

watchOS 2

Not even three months after the Apple Watch officially launched, Apple announced the next version of the Apple Watch operating system, watchOS 2. The most significant aspect of this update is the ability for native apps. On watchOS 2, apps can now run on Apple Watch instead of on a paired iPhone.

Native apps will also be able to utilize all of the hardware capabilities of the watch, including the microphone, speaker, digital crown, and various sensors. Of course, performance will improve drastically with the arrival of native apps.

The watchOS 2 update will also bring with it numerous new features, including three new faces, Time Lapse, Photo, and Photo Album. These faces, in particular Photo and Photo Album, let the user customize their Apple Watch even more.

In addition to these new watch faces, existing faces will also be able to take advantage of the new third party complications available. Any native Apple Watch will be able to create its own complication, which the user can choose to put on their current watch face.

Third Party Complications

With watchOS 2, your Apple Watch will also gain the ability to Time Travel. From the home screen, you can turn the digital crown to go both forwards and backwards in time, enabling you to have a look at the weather, calendar events, and other time-sensitive information.

Your Apple Watch will also gain a new Nightstand mode. This allows your watch to still be useful when you are no longer wearing it and it's charging for the night. In this mode, your watch will display the time, date, and alarm, whenever it is touched. When your alarm goes off in the morning, the digital crown and side button on your watch will function as snooze and off buttons respectively.

Nightstand Mode while Charging

Developer Tools

In addition to announcing updates to OS X, iOS, and watchOS, Apple also announced new developer tools to create applications for its popular platforms.

The most important announcement is arguably the announcement of Swift 2.0 and the decision to make Swift open source later this year. This new version of the Swift language includes better error handling, an improved syntax, and a much faster compiler.

Xcode 7, the next generation of Apple's popular IDE, brings with it a great deal of new features, including advanced user interface testing and an improved interface builder. For the first time, it will be able to run iOS apps on a physical device without the need for a paid Apple developer account.

Swift 20

Apple Music

This year's "One more thing ..." was focused on music. Apple announced their brand new music streaming service, Apple Music. In addition to streaming all the music that is available on iTunes, Apple Music will also provide a 24/7 worldwide radio station, called Beats 1, and a channel for artists to easily communicate with fans, Connect.

Apple Music memberships will be available for $9.99 per month for a single user or $14.99 per month for a family membership, which can be shared with up to six family members. In a very interesting move, Apple Music will not only be available on iOS and OS X, but also on Windows and Android devices. Apple Music will be available on June 30.

Apple Music

Conclusion

At this year's WWDC, Apple announced a lot of new things regarding their products and services. Free updates for OS X, iOS, watchOS, and Xcode are all coming later this year, with developer betas already available to developers.

Apple's new music streaming service, Apple Music, is launching June 30. It will include a free three-month trial. We will post many more articles and tutorials on Tuts+ to tell you all about iOS 9, OS X El Capitan, and watchOS, so be sure to look out for those.

If you'd like to watch the keynote of this year's WWDC, then you can do so on Apple's website.

2015-06-10T10:25:34.000Z2015-06-10T10:25:34.000ZDavis Allie

WWDC 2015 Aftermath

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

Earlier this week, Apple officially kicked off their annual WWDC (Worldwide Developers Conference) event in San Francisco. As always, the event began with a keynote during which Apple announced updates for their OS X, iOS, and watchOS platforms. This year the keynote also included the official announcement of Apple's new music streaming service, Apple Music.

iOS 9

This year's iOS update is an incremental update and doesn't include as many new features as iOS 8 or iOS 7 had. The clear focus for iOS 9 is refining existing iOS features and usability to make the overall experience better for the user. This is evident by the fact that iOS 9 is supported by every device that runs iOS 8, including the iPhone 4S, iPad 2, iPod Touch 5G, and the very first iPad mini.

For the first time ever, a public beta of iOS 9 will be available sometime in July, enabling non-developers to try out the update and to provide feedback to Apple. A subtle but definitely noticeable change in iOS 9 is the changing of the standard system font from Helvetica Neue to San Fransisco, the font Apple created for the Apple Watch.

The other new aspects of iOS 9 are split into four distinct categories:

  • Intelligence
  • Apps
  • iPad
  • Foundation

Intelligence

Siri is receiving an important update in iOS 9. In addition to improving voice recognition accuracy, the update also adds a number of new capabilities. This includes the ability for more advanced searches. For example, the phrase "Show me photos from Utah." will now show all the photos on your device that match the specified location. Similar searches can also be performed with dates and times, in addition to location.

Siri can now also create contextual reminders based on the app you're currently in. For example, if you're viewing a web page in Safari or a message in Messages, you can ask Siri to "Remind me about this." and Siri will create a reminder that contains the content you are currently looking at or, in the case of a web page, a link to the content. In iOS 9 Siri also gains a more colorful look, similar to that of the Apple Watch.

Siris new look and feel

These improvements culminate in a new feature Apple calls Proactive Assistant. The new assistant can be accessed by swiping to the left of the home screen—where search was located before iOS 8—and provides access to Spotlight search, contacts, and app suggestions by Siri, nearby activities, and news items.

This new Proactive Assistant also adds calendar items automatically for you by detecting event times and locations in emails and messages received on your device. It even learns your daily habits and can present content when it thinks you will need it, for example, music on your daily commute to work.

In terms of privacy, the personal information collected by this assistant is completely in control of the user and does not leave the device. For items that do require communication with Apple's network, the information transmitted is completely anonymous and not linked to your Apple ID.

Proactive Assistant

In iOS 9, Passbook has been rebranded as Wallet and includes some new additions to the Apple Pay service. Apple Pay will be able to store not only credit cards but also store cards for VIP services as well as offers on a merchant-by-merchant basis.

Later this year, Apple Pay will also be launching in the UK. It will be available in a wide range of leading retailers as well as on public transport systems in London.

Apps

The Notes app in iOS 9 gains some important features, including a new formatting toolbar to easily format text, create lists, and even add images. In addition to regular bulleted and numbered lists, the new Notes app lets you create checked lists, which you can tick off as you complete the items in the list.

Notes now also includes a basic drawing tool to illustrate your ideas quickly and easily. Multiple types of content can now be added to your notes, including images and links. When a note includes a link, a clickable button with a thumbnail preview is displayed, taking you directly to the linked web page.

The new Notes app

Maps also received a significant update in iOS 9, especially interesting for people who travel via public transport. A new map category, Transit, displays bus, subway, and other public transport routes and stations.

The data used for these maps is so detailed that, for large stations and buildings, it even shows you exactly where the different entrances and exits are, giving you clear walking directions. When iOS 9 is launched later this year, the following cities will have Transit data available:

Transit Maps

Also launching with iOS 9 is a brand new News app. It will provide beautifully styled articles, designed specifically for iOS devices, based on your interests. Content creators can layout their articles specifically for the iOS News app with specialized layouts, elegant animations, and embedded photo galleries.

At launch, there will be numerous pieces available from major content creators, such as The New York Times and WIRED magazine.

The brand new News app

iPad

With iOS 9, the iPad received a number of great features that will help increase productivity. The first of these new features is the QuickType keyboard. In addition, to the suggestion bar introduced in iOS 8, on iPad this bar will now also show cut, copy, and paste shortcuts as well as other formatting options.

By panning with two fingers across the keyboard, you can also turn it into a trackpad to quickly move the cursor and select portions of text.

The QuickType keyboard will help increase productivity

Split-screen multitasking is finally coming to the iPad in iOS 9. You can now drag in from the right hand edge of the screen to "slide over" another fully functional app. This feature, known as Slide Over, is available on iPad Air, iPad Air 2, iPad mini 2, and iPad mini 3.

In addition to Slide Over, iPads can now also display a video, FaceTime call, or any third party video content in a picture-in-picture resizable view that remains on top of your content, no matter where you are in iOS.

Multitasking with Slide Over

On the iPad Air 2, you can go a step further and have two active apps side by side at the same time, allowing full multitasking between applications.

Split Screen Multitasking

Foundation

iOS 9 also includes many under-the-hood improvements to make the whole experience better across the entire operating system. The first of these improvements is in the form of extended battery life. By making the operating system, apps, and key technologies more efficient, your devices running iOS 9 will be able to last an hour longer per charge. An brand new Low Power mode can add up to another three hours of battery life on top of the existing one hour improvement.

iOS 9 also has a much improved system update process that requires, compared to iOS 8, far less free space to install. To install iOS 9, your device will only need 1.3 GB of free space, compared to the 4.58 GB that iOS 8 required. You will also be able to choose to update your device at a convenient time when you're not using your device.

Finally, the core apps and technologies of iOS 9 have been redesigned to take advantage Metal, Apple's excellent 3D graphics API. This results in the entire system running much faster with smoother animations, making everything feel fluid and natural.

OS X El Capitan

Apple also announced the successor to last year's OS X YosemiteOS X El Capitan. This update to OS X has been developed on the same principles as iOS 9, refinement and improving the operating system as a whole.

Just like iOS, the system font has been changed to San Fransisco and a public beta will be available in July to anyone with an Apple ID. The most important new features and improvements in OS X El Capitan fall under the focuses of experience and performance.

Experience

One of the first new features in OS X El Capitan is Split View. What this enables you to do is fill the screen with two apps side-by-side, eliminating all other distractions. The size of each app in this split view can be customized very easily, without the need to manually drag windows around.

This focus to improve window organization has also led to a more streamlined and functional Mission Control. In this view, windows will no longer be stacked on top of one another and it's easier than ever before to create a new desktop space by simply dragging a window to the top of the screen.

Mission Control is now more powerful than ever

Spotlight search also gained some significant improvements. It can now display weather, stocks, sports information, and even video links. You can now also search using a more natural syntax, such as "Documents I worked on yesterday" and Spotlight will return the correct results for you. This natural search syntax can also be used in Finder and Mail.

The Mail app in El Capitan also received a major update, which is especially useful when used full screen. When composing a new email, you can now minimize the window to the bottom of the app to continue looking at other messages. In this composition window, you can even open multiple tabs to write severals emails side by side. On OS X, Mail now also has swipe gestures, similar to the ones Mail for iOS features.

With OS X El Capitan, Safari also managed to grab a few small usability features. You can now pin websites to the left side of the existing tab bar to keep them readily accessible. While pinned, Safari will also keep that web page active in the background so that they are always up to date whenever you decide to open them. Safari will now also show you which tabs are playing audio and will provide a quick and easy way to mute all tabs in the case of some surprise audio.

Pinned Websites

This year's update to OS X also shares some common functionality with iOS 9, specifically all of the new features outlined earlier in iOS 9's Notes and Maps apps. OS X El Capitan will also have support for third party extensions in the Photos app. These extensions will be available through the Mac App Store.

Performance

The biggest performance boost for OS X El Capitan is going to come from the availability of Apple's Metal Graphics API on Mac. Introduced last year for specific devices alongside iOS 8, Metal is a replacement to both OpenGL and OpenCL, and will speed up the system-level graphics of OS X by up to 50% and allow for 10x faster draw call performance.

Metal for Mac

The overall improvements across the entire operating system will also allow for 1.4x faster app launch and 2x faster app switching.

watchOS 2

Not even three months after the Apple Watch officially launched, Apple announced the next version of the Apple Watch operating system, watchOS 2. The most significant aspect of this update is the ability for native apps. On watchOS 2, apps can now run on Apple Watch instead of on a paired iPhone.

Native apps will also be able to utilize all of the hardware capabilities of the watch, including the microphone, speaker, digital crown, and various sensors. Of course, performance will improve drastically with the arrival of native apps.

The watchOS 2 update will also bring with it numerous new features, including three new faces, Time Lapse, Photo, and Photo Album. These faces, in particular Photo and Photo Album, let the user customize their Apple Watch even more.

In addition to these new watch faces, existing faces will also be able to take advantage of the new third party complications available. Any native Apple Watch will be able to create its own complication, which the user can choose to put on their current watch face.

Third Party Complications

With watchOS 2, your Apple Watch will also gain the ability to Time Travel. From the home screen, you can turn the digital crown to go both forwards and backwards in time, enabling you to have a look at the weather, calendar events, and other time-sensitive information.

Your Apple Watch will also gain a new Nightstand mode. This allows your watch to still be useful when you are no longer wearing it and it's charging for the night. In this mode, your watch will display the time, date, and alarm, whenever it is touched. When your alarm goes off in the morning, the digital crown and side button on your watch will function as snooze and off buttons respectively.

Nightstand Mode while Charging

Developer Tools

In addition to announcing updates to OS X, iOS, and watchOS, Apple also announced new developer tools to create applications for its popular platforms.

The most important announcement is arguably the announcement of Swift 2.0 and the decision to make Swift open source later this year. This new version of the Swift language includes better error handling, an improved syntax, and a much faster compiler.

Xcode 7, the next generation of Apple's popular IDE, brings with it a great deal of new features, including advanced user interface testing and an improved interface builder. For the first time, it will be able to run iOS apps on a physical device without the need for a paid Apple developer account.

Swift 20

Apple Music

This year's "One more thing ..." was focused on music. Apple announced their brand new music streaming service, Apple Music. In addition to streaming all the music that is available on iTunes, Apple Music will also provide a 24/7 worldwide radio station, called Beats 1, and a channel for artists to easily communicate with fans, Connect.

Apple Music memberships will be available for $9.99 per month for a single user or $14.99 per month for a family membership, which can be shared with up to six family members. In a very interesting move, Apple Music will not only be available on iOS and OS X, but also on Windows and Android devices. Apple Music will be available on June 30.

Apple Music

Conclusion

At this year's WWDC, Apple announced a lot of new things regarding their products and services. Free updates for OS X, iOS, watchOS, and Xcode are all coming later this year, with developer betas already available to developers.

Apple's new music streaming service, Apple Music, is launching June 30. It will include a free three-month trial. We will post many more articles and tutorials on Tuts+ to tell you all about iOS 9, OS X El Capitan, and watchOS, so be sure to look out for those.

If you'd like to watch the keynote of this year's WWDC, then you can do so on Apple's website.

2015-06-10T10:25:34.000Z2015-06-10T10:25:34.000ZDavis Allie

iOS 9: Getting Started with UIStackView

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

Like every iteration of iOS, iOS 9 brings forth a lot of new features. UIKit changes with every release of iOS, but one particular addition in iOS 9 will change how developers fundamentally think about creating user interfaces on iOS, UIStackView. In this tutorial, you will learn how to use UIStackView to create user interfaces.

This article assumes you are familiar with the basics of Auto Layout. If this subject is new to you, then our introductory tutorial about Auto Layout is a good place to start. To understand why stack views are so helpful and how they operate, a solid understanding of Auto Layout is required.

1. Demo Preview

Using UIStackView, we are going to build a mock screen that prompts the user to leave a rating for their app. The user can add or remove stars in the user interface to indicate their rating. It will look like this when we are finished.

This is what the result will look like

Download the starter project from GitHub and open it. You'll see that there are two stack views inside Main.Storyboard.

This is the storyboard of the starter project

We will use the two stack views to lay out the user interface. Before we begin coding, let's first take brief look at how a stack view works.

2.UIStackView Overview

At its core, the stack view is an interface for laying out several subviews, either vertically or horizontally. If you have Android development experience, it's similar to the LinearLayout control.

One of the main advantages of the stack view is that it will automatically create Auto Layout constraints for each subview that's added to it. You also have finite control over how those subviews are sized and positioned. There are options to configure the sizing of the views, where they should be arranged, as well as how much padding should be between the subviews.

Laying Out Content

To see the options of a stack view, open Main.Storyboard and select one of of the stack views. In the Attributes Inspector, notice the options listed under Stack View.

The options of a stack view

The Axis determines if the stack view arranges its subviews horizontally or vertically. The Alignment controls how the actual subviews should be aligned. Distribution defines how the subviews are sized and Spacing controls the minimum spacing between the subviews of the stack view.

To simplify these terms, think of it like this. Alignment controls the X and Y values while Distribution controls height and width. The other two values can also affect alignment. Baseline Relative, if checked, will derive vertical spacing of each subview from its baseline. Layout Margins Relative places the subviews relative to the standard layout margins if selected.

Another important thing to remember when working with a stack view is that it's built to be a container view. Because of that, it's a nonrendering subclass of UIView. It's not draw to the canvas like other UIView subclasses. This means that setting properties like backgroundColor or overriding the drawRect: method will have no effect on the stack view.

subviews and arrangedSubviews

Before we start working with stack views, I'd like to focus on the difference between a stack view's subViews and arrangedSubviews properties. If you wish to add a subview for the stack view to manage, you do so by calling addArrangedSubview: or insertArrangedSubview:atIndex:. The arrangedSubViews array is a subset of its subViews property.

To remove a subview that the stack view manages, you need to call both removeArrangedSubview: and removeFromSuperview. Removing an arranged subview ensures the stack view will no longer manage that view's constraints. It doesn't take it out of the view hierarchy. This is very important to remember.

Now that we have a solid understanding of how the stack view works, let's start using a stack view.

3. Configuring the Vertical Stack View

Open Main.Storyboard and select the top stack view. In the Attributes Inspector, make the following changes:

  • set Alignment to Center
  • set Distribution to Equal Spacing
  • set Spacing to 30

This will tell the stack view to try and add constraints that center all of the subviews vertically and size them so that they fill the stack view's axis evenly. In addition, it will add 30 points of padding to the subviews.

If the subviews are not able to fit inside the stack view, it will shrink them based on their respective compression resistance priorities. This could happen if you were to add subviews to the stack view at run time as we'll see later.

If there is any ambiguity, the stack view will fall back to shrinking the subviews based on their index in its arrangedSubviews array until they fit the stack view's bounds.

4. Adding Vertical Stack Subviews

Add a label, an image view, and a button to the top stack view by dragging them in the document outline. Ensure the label is at the top, the image view in the middle, and the button at the bottom. The storyboard's document outline should look like this after you've added these subviews:

Adding subviews to the top stack view

Next, we'll need to edit some of the properties of the subviews we just added, using the Attributes Inspector. For the label, change its Text to "How do you like our app?" and select Center for Text Alignment. As for the image view, enter "logo" for the Image and Aspect Fit for the Content Mode. For the button, set its Text to "Add Star!".

Go ahead and run the app. You'll see that with very little work, you have added three subviews that respond to any changes in orientation, size class, etc. In fact, you didn't even have to manually add any constraints.

While the app is running, click the Debug View Hierarchy button at the bottom of the Xcode window to initiate live view debugging.

Live view debugging in Xcode

Select any of the three subviews you added earlier. Look at the size inspector and notice the constraints that were added by the stack view. The picture below is showing the constraints added for the button.

The Auto Layout constraints of the stack views button

5. Adding Stars

The button to add stars for our mock app isn't hooked up yet. Let's fix that now. Stop the app and open the storyboard. Create an IBAction with a name of addStar for the Touch Up Inside event.

Adding an IBAction

Add the following code inside the addStar(_:) method:

We add a star image to the horizontal stack view with an animation. Remember, since stack views manage Auto Layout constraints for us, we only need to call layoutIfNeeded to create an animation.

Build and run the app again and add a star. You'll see that the end result is not what we were hoping for.

This is not what we were hoping for

If you look at the Attributes Inspector with the bottom stack view selected, the problem should be clear. Since both the Alignment and Distribution are set to Fill, the stack view is stretching the star to fill its bounds.

This will also cause more problems when more stars are added. We want the stars to be centered, not stretched to fit the width of the stack view. Change Alignment to Center and Distribution to Fill Equally. Finally, update the addStar(_:) method by setting the image view's Content Mode to Aspect Fit.

Build and run the app one more time. Add a few stars and notice how the stack view correctly centers them along its axis.

This looks much better

6. Nesting Stack Views

Our app wouldn't be very helpful without the ability to remove stars. Open the storyboard and add a horizontal stack view to the top stack view's view hierarchy. Make sure it's positioned below the image view for the logo and above the button.

Adding a stack view to another stack view

Drag the "Add Star!" button inside the newly added stack view and add second button to the new stack view. Change the button's title to "Remove Star" and select red for the text color. The document outline should now look like this:

The new stack view contains two buttons

Edit the attributes of the new stack view in the Attributes Inspector, making the following changes:

  • set Alignment to Center
  • set Distribution to Equal Spacing
  • set Spacing to 10
Adjusting the attributes of the new stack view

7. Removing Stars

Create an IBAction for the "Remove Star" button with a name of removeStar for the Touch Up Inside event.

Create an action for the removeStar button

Add the following code to the removeAction(_:) method:

Build and run the app. You should now be able to both add and remove stars. Change the orientation of the iOS Simulator or rotate your testing device to see how the app behaves by adjusting its user interface. Remember that we've built the the user interface of this app without having to manually add a single constraint.

Keep in mind that the removeFromSuperview call in the removeStar(_:) method is essential to remove the subview from the view hierarchy. Recall that removeArrangedSubview(_:) only tells the stack view that it no longer needs to manage the subview's constraints. The subview, however, remains in the view hierarchy until we remove it from its superview by calling removeFromSuperview on it.

Conclusion

The UIStackView class greatly simplifies developing user interfaces. This is a good thing, especially when the hardware the application runs on can vary so much. With UIStackView, developers can spend less time setting up tedious constraints for simple scenarios, shifting the heavy lifting to UIKit.

If you got stuck at any point during this tutorial, feel free to download the finished project from GitHub.

2015-06-15T16:50:18.000Z2015-06-15T16:50:18.000ZJordan Morgan

Getting Started With Android: Creating a Customized Toolbar

$
0
0

Creating native Android apps allows you to deliver a first-class mobile experience to your users. In this short video tutorial from my recent Android course, I'll show you how to add a customized toolbar to the top of your Android application.

Note: Be sure that the AppCompat version is set exactly as shown in the video. The sample app may not be compatible with newer versions of the library.

Watch the Tutorial

Watch the Full Course

In the full course, Getting Started With Android, I'll take you through native Android development, from setup to creating a finished app. 

In 20 detailed video lessons, I'll help you create a sample Android app for a zoo. You will create a list of exhibits that opens into a detail page, a gallery and a Google Maps section. You will also implement a navigation drawer and toolbar, while learning the basics of material design. 

2015-06-18T16:45:51.000Z2015-06-18T16:45:51.000ZPaul Trebilcox-Ruiz

Getting Started With Android: Creating a Customized Toolbar

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

Creating native Android apps allows you to deliver a first-class mobile experience to your users. In this short video tutorial from my recent Android course, I'll show you how to add a customized toolbar to the top of your Android application.

Note: Be sure that the AppCompat version is set exactly as shown in the video. The sample app may not be compatible with newer versions of the library.

Watch the Tutorial

Watch the Full Course

In the full course, Getting Started With Android, I'll take you through native Android development, from setup to creating a finished app. 

In 20 detailed video lessons, I'll help you create a sample Android app for a zoo. You will create a list of exhibits that opens into a detail page, a gallery and a Google Maps section. You will also implement a navigation drawer and toolbar, while learning the basics of material design. 

2015-06-18T16:45:51.000Z2015-06-18T16:45:51.000ZPaul Trebilcox-Ruiz

iOS 9: Staying Organized with Storyboard References

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

Even though storyboards have been around since iOS 5, many developers are reluctant to use them in their projects. A typical remark is that storyboards are great for small projects, but fall short for larger projects.

Apple has taken this feedback to heart and resolved many common problems by introducing storyboard references. In this tutorial, I will show you what storyboard references are and how they can help you break down your project's user interfaces into manageable pieces.

1. The Problem

From a designer's perspective, storyboards are great. They are a visual representation of a project's user interface. Interface Builder makes adding and connecting scenes a breeze. Unfortunately, storyboards also have a number of drawbacks.

Complexity

Most projects have one storyboard that contains the application's user interface. That's the goal of storyboards. Right? Yes and no. It's true that the goal of storyboards is to visually lay out the user interface. The problem is that storyboards can quickly become unwieldy and complex for larger projects.

Source Control

Another hurdle when working with storyboards is collaboration. Storyboards can make collaborating with team members a true challenge. A storyboard is stored as one file. This means that every change you or a team member makes to a storyboard affects the same file. At some point, this will inevitably lead to merge conflicts. This is less of a problem when working with XIB files since each XIB file represents one scene of the user interface.

2. The Solution

Before iOS 9

The solution is simple, breaking up storyboards into a set of smaller storyboards. But how do you connect the storyboards? Before iOS 9, developers would connect storyboards in code by loading the storyboard and invoking instantiateInitialViewController() on the storyboard. The following code snippet shows how this works.

It forces developers to make the connection in code, making it unclear how multiple storyboards are connected. It's not obvious how one storyboard is connected to another storyboard. Let's see how storyboard references solve these problems in iOS 9.

iOS 9

Storyboard references are a great addition to the storyboard toolchain. In Interface Builder, the destination of a segue can now also be another storyboard. What's more, a storyboard can be referenced multiple times, making it easy to reuse storyboards in multiple places. Let's create a simple project to show you how easy it is to get started with storyboard references.

3. Project Setup

Instead of starting with a sample project, I'm going to show you how to use storyboard references from scratch. Before you continue, make sure that you have Xcode 7 installed. Storyboard references are only available in iOS 9, which requires Xcode 7.

Open Xcode 7 and create a new project by choosing New > Project... from Xcode's File menu. Select the Tabbed Application template from the iOS > Application section on the left.

Choosing a Template

Configure the project by giving it a name and setting Devices to iPhone. For this tutorial, it doesn't matter whether you set Language to Swift or Objective-C. Tell Xcode where it should store the project and hit Create.

Configuring the Project

If you're new to storyboards, then you may be surprised that Xcode has created two storyboards for us. Main.storyboard is the project's main storyboard and contains the application's user interface. LaunchScreen.storyboard is a storyboard that Xcode uses to dynamically create a launch screen for the application. We won't be using LaunchScreen.storyboard in this tutorial.

4. Creating the User Interface

Our storyboard currently contains a tab bar controller and two view controllers. Let's make it a bit more interesting by embedding the view controllers in a navigation controller. Select the top view controller and select Embed In > Navigation Controller from Xcode's Editor menu. Do the same for the second view controller. This is what your storyboard should now look like.

Embedding the View Controller in a Navigation Controller

Even though the storyboard isn't complicated, it contains enough complexity to show you how storyboard references work and how they can benefit your projects. It's time for some refactoring.

5. Refactoring Storyboards

When a project's code base becomes unwieldy or too complex to maintain, it is time for refactoring. Refactoring simply means reorganizing or restructuring the code base to make it easier to maintain. This often includes breaking up large chunks of code into smaller bits, modularizing the code base.

While storyboards are a great tool to create user interfaces, storyboards can also become too complex or too large to maintain. In iOS 9, a storyboard can be split up into multiple smaller storyboards. Apple refers to this process as refactoring.

Because each view controller of the tab bar controller can be seen as a separate user interface, it makes sense to put each tab of the tab bar controller into a separate storyboard. This is very easy in Xcode 7.

Start by selecting the top view controller and its navigation controller. From Xcode's Editor menu, choose Refactor to Storyboard. Xcode will ask you to name the storyboard it's about to create for the selection you've made. Name the storyboard FirstTab.storyboard and click Save.

Refactoring to a Storyboard

Xcode will create a new storyboard that includes the navigation controller and its root view controller. In this storyboard, the navigation controller automatically becomes the initial view controller of the storyboard as you can see in the below screenshot.

The New Storyboard

Note that Main.storyboard has become much simpler. The navigation controller and its root view controller have been replaced by a storyboard reference named FirstTab. If you double-click the storyboard reference, Xcode will automatically open FirstTab.storyboard, the storyboard it references.

The Refactored Storyboard

6. Exploring Storyboard References

Storyboard references are quite powerful. A storyboard reference will by default instantiate the initial view controller of the referenced storyboard, but it is possible to link to any scene in the storyboard that has a Storyboard ID.

Create a new UIViewController subclass and name it ThirdViewController. Open FirstTab.storyboard and drag a new view controller from the Object Library on the right. From the Object Library, add a label to the view of the new view controller and set its text to Third View. With the new view controller selected in the storyboard, set Class to ThirdViewController and Storyboard ID to ThirdView in the Identity Inspector on the right.

Adding a Third View Controller

Head back to Main.storyboard and select the storyboard reference you created earlier. Open the Attributes Inspector on the right to see the attributes of the storyboard reference. The Attributes Inspector shows us that the storyboard reference references the FirstTab storyboard. The Referenced ID is empty at the moment.

Set Referenced ID to ThirdView and you'll see that the storyboard reference updates its label to reflect the change. Run the application in the iOS Simulator to see the result. This illustrates that you can use storyboard references to link to any scene in a storyboard, even if the scene isn't connected by a segue with other scenes in the storyboard.

Configuring the Storyboard Reference

Note that we can also specify the bundle of the referenced storyboard. This is especially useful if you need to link to a scene in a storyboard of an external framework.

Before we continue our exploration of storyboard references, I'd like to point out that the storyboard of a storyboard reference can be the same storyboard to which the reference belongs. This may sound strange, but it can be very useful if you want to reuse certain scenes in a storyboard or if you're working with a very complex storyboard.

7. Adding Storyboard References

We've created FirstTab.storyboard by choosing Refactor to Storyboard from Xcode's Editor menu. Storyboard references are also available from the Object Library. Open the Object Library on the right and add a storyboard reference to Main.storyboard.

Select the tab bar controller in the storyboard and create a segue to the storyboard reference by holding Control and dragging to the new storyboard reference.

Create a Segue to the Storyboard Reference

From the menu that appears, choose view controllers from the Relationship Segue section.

Create a Relationship Segue

Select the new storyboard reference and set Storyboard ID to FirstTab. Run the application in the iOS Simulator to see the result. Note that the second tab of the tab bar controller shows the third view controller while the third tab shows the first view controller embedded in a navigation controller.

The Final Result

Conclusion

Storyboard references are powerful. Not only do they make storyboards manageable and modular, they make it very easy to reuse storyboards and even hook into storyboards at arbitrary places.

I strongly believe that storyboard references will result in a much higher adoption rate of storyboards by developers. Storyboard references are exactly what developers have been asking for.

2015-06-19T17:38:52.405Z2015-06-19T17:38:52.405ZBart Jacobs

An Introduction to Kotlin

$
0
0

Introduction

Ever since Apple released the Swift programming language for iOS, lots of Android developers have wanted a similar language for Android development. If you are one of those developers, you are going to love Kotlin, a JVM language that is remarkably similar to Swift.

Kotlin is a statically-typed language, developed by JetBrains, whose syntax is more expressive and concise than that of Java. With features like higher-order functions, lambda expressions, operator overloading, string templates, and more, Kotlin has a lot more to offer than Java. Because Java and Kotlin are highly interoperable, they can be used together in the same project.

If you are a competent programmer in Java, you will be able to learn Kotlin in a very short time. In this tutorial I will be showing you how to use Kotlin’s most frequently used constructs.

Prerequisites

To follow along with me, you will need:

1. Classes

To create a class in Kotlin, you have to use the class keyword. For example, here’s how you create an empty class called Person:

Adding Properties

A class usually has properties and member functions (also called methods). Let’s add two properties to the Person class, name of type String and age of type Int.

As you can see, the syntax for creating variables is slightly different from that of Java. To create a variable in Kotlin, you must use the var keyword. However, if you want your variable to be a read-only/assign-once variable, use the val keyword instead.

For the sake of null safety, Kotlin also makes a distinction between variables that can be null and variables that can never be null. In our previous example, both the variables name and age can never be null. If they are null, the compiler will raise an error.

To create a variable that can hold null, you need to add a ? after the variable’s type. For example:

Now that we have a class, creating an instance of it is easy:

No, Kotlin doesn’t have the new keyword. Once the instance has been created, you can access its properties the same way you would in Java:

Using Constructors

Initializing the individual properties of our instance the way we just did is not a good coding practice. A better way to do this would be by using a constructor. Kotlin’s syntax to create such a constructor is very compact:

In fact, if you have nothing else to add to your class, you don’t need the curly braces. The following code works just fine:

It might already be obvious to you that there’s no way you can add custom code to this constructor. This constructor, which is part of the class’s header, is called the primary constructor.

To add more constructors to your class, known as secondary constructors, you should use the constructor keyword. Secondary constructors should delegate to the primary constructor using the this keyword. Let’s add a secondary constructor to our class that initializes the value of a property named email:

To create an instance using the secondary constructor, you write something like this:

Adding Member Functions

In Kotlin, functions are created using the fun keyword. Let’s add a simple member function named isEligibleToVote that returns a Boolean value:

Note that the return value’s type is indicated at the end of the function header. You can call this method the same way you would in Java:

Creating Extensions

Kotlin lets you extend a class by adding additional functions to it without modifying its original definition. Such functions are known as extensions. The names of these functions should be preceded by the names of the classes they extend.

For example, to add an extension called isTeenager to the Person class, you write the following code outside the class:

This feature is especially useful when you want to extend classes that do not belong to your project’s code base. For example, the following code snippet adds an extension containsSpaces to the String class:

Creating Derived Classes

It’s important to keep the following in mind when creating a derived class:

  • You must use a : instead of Java’s extends keyword.
  • The header of the base class should have the open annotation.
  • If your base class has a constructor that takes parameters, your derived class should initialize those parameters in the header itself.

Let’s create a class named Employee that derives from Person:

Overriding Member Functions

In Kotlin, you have to explicitly state that a member function can be overridden by using the open annotation in the method’s header in the base class. In the derived class, open functions can be overriden using the override annotation.

For example, to override the isEligibleToVote method, you add the following code snippet to the Employee class:

Creating Static Methods

Kotlin does not allow you to create static methods. However, it does allow you to create package level functions that do not belong to any class.

The main method is perhaps the best known static method. If you want to add the main method to a package named com.tutsplus.code.tutorial, then your code would look like this:

2. Functions

You’ve already learned how to create simple functions in the previous examples. The syntax you used to create those functions was very similar to that of Java. Kotlin, however, lets you to do a lot more with functions.

Creating Single Expression Functions

If a function returns the value of a single expression, then you can use the = operator after the function header followed by the expression to define the function.

For example, to add a method to the Person class that returns true if the person is an octogenarian, you would write:

As you can see, this shorthand syntax is more compact and readable.

Higher Order Functions and Lambda Expressions

Higher order functions are functions that can return functions or accept functions as parameters. A lambda expression, on the other hand, is just a function that has no name. Usually, lambda expressions and higher order functions are used together.

Consider the following example that demonstrates the syntax of a lambda expression:

This is a simple lambda expression that takes two parameters, x and y, and returns their sum. As you might have guessed, the parameters of the function are listed before the -> operator and the body of the function starts after the -> operator. This lambda expression can be assigned to a variable and used as follows:

Note that the type of the variable that holds the lambda expression specifies the types of its parameters and its return value.

Creating a higher order function that can accept the above lambda expression as a parameter is just as easy. For example, to create a function that doubles the result of the lambda expression, you would write:

You can call this function as follows:

Alternatively, you can pass the lambda expression directly to the higher order function:

Lambda expressions are often used with arrays. For example, consider the following array of Int values:

If you want to square the value of each item in the array, you can use the map function along with a lambda expression as follows:

3. Ranges

Range expressions are used very frequently in Kotlin. You already used them while creating the isTeenager and isOctogenarian methods.

To create a range, all you need is the .. operator.

To create a range in descending order, use the downTo function instead.

If you don’t want the step to be 1, you can specify a custom value using the step function.

You will see more range expressions later in this tutorial.

4. Conditional Constructs

if

In Kotlin, if is an expression that returns different values depending on whether the condition has been satisfied. The following example illustrates how this works.

when

The when expression is equivalent to Java’s switch. However, it is a lot more versatile. For instance, consider the following example.

As you can see, when can not only take single values but also expressions as its conditions.

5. Looping Constructs

for..in

In Kotlin, you can use the for..in loop to loop through arrays, collections, and anything else that provides an iterator. Its syntax is almost identical to that of Java, except for the use of the in operator instead of Java’s : operator. The following example shows you how to loop through an array of String objects.

With the help of range expressions, you can make this loop behave like a traditional, C-style, for loop.

while and do..while

The syntax of while and do..while loops in Kotlin is identical to the syntax used in Java. For example, the following Kotlin code loops over an array of String objects using a while loop:

6. String Templates

Kotlin lets you embed variables and expressions in strings by wrapping them in a pair of curly braces, prefixed by a $ symbol. For example:

Conclusion

In this tutorial, you learned the basics of the Kotlin programming language. Even though we covered several constructs here, Kotlin has a lot more to offer. In fact, as of June 2015, Kotlin is still available only as a preview. It is likely to see several improvements and new features in the coming months.

If you want to know how to use Kotlin in Android Studio, then take a look at How to Use Kotlin in Your Android Projects . To learn more about the Kotlin language, I recommend visiting the Kotlin documentation.

2015-06-22T16:10:58.000Z2015-06-22T16:10:58.000ZAshraff Hathibelagal

An Introduction to Kotlin

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

Introduction

Ever since Apple released the Swift programming language for iOS, lots of Android developers have wanted a similar language for Android development. If you are one of those developers, you are going to love Kotlin, a JVM language that is remarkably similar to Swift.

Kotlin is a statically-typed language, developed by JetBrains, whose syntax is more expressive and concise than that of Java. With features like higher-order functions, lambda expressions, operator overloading, string templates, and more, Kotlin has a lot more to offer than Java. Because Java and Kotlin are highly interoperable, they can be used together in the same project.

If you are a competent programmer in Java, you will be able to learn Kotlin in a very short time. In this tutorial I will be showing you how to use Kotlin’s most frequently used constructs.

Prerequisites

To follow along with me, you will need:

1. Classes

To create a class in Kotlin, you have to use the class keyword. For example, here’s how you create an empty class called Person:

Adding Properties

A class usually has properties and member functions (also called methods). Let’s add two properties to the Person class, name of type String and age of type Int.

As you can see, the syntax for creating variables is slightly different from that of Java. To create a variable in Kotlin, you must use the var keyword. However, if you want your variable to be a read-only/assign-once variable, use the val keyword instead.

For the sake of null safety, Kotlin also makes a distinction between variables that can be null and variables that can never be null. In our previous example, both the variables name and age can never be null. If they are null, the compiler will raise an error.

To create a variable that can hold null, you need to add a ? after the variable’s type. For example:

Now that we have a class, creating an instance of it is easy:

No, Kotlin doesn’t have the new keyword. Once the instance has been created, you can access its properties the same way you would in Java:

Using Constructors

Initializing the individual properties of our instance the way we just did is not a good coding practice. A better way to do this would be by using a constructor. Kotlin’s syntax to create such a constructor is very compact:

In fact, if you have nothing else to add to your class, you don’t need the curly braces. The following code works just fine:

It might already be obvious to you that there’s no way you can add custom code to this constructor. This constructor, which is part of the class’s header, is called the primary constructor.

To add more constructors to your class, known as secondary constructors, you should use the constructor keyword. Secondary constructors should delegate to the primary constructor using the this keyword. Let’s add a secondary constructor to our class that initializes the value of a property named email:

To create an instance using the secondary constructor, you write something like this:

Adding Member Functions

In Kotlin, functions are created using the fun keyword. Let’s add a simple member function named isEligibleToVote that returns a Boolean value:

Note that the return value’s type is indicated at the end of the function header. You can call this method the same way you would in Java:

Creating Extensions

Kotlin lets you extend a class by adding additional functions to it without modifying its original definition. Such functions are known as extensions. The names of these functions should be preceded by the names of the classes they extend.

For example, to add an extension called isTeenager to the Person class, you write the following code outside the class:

This feature is especially useful when you want to extend classes that do not belong to your project’s code base. For example, the following code snippet adds an extension containsSpaces to the String class:

Creating Derived Classes

It’s important to keep the following in mind when creating a derived class:

  • You must use a : instead of Java’s extends keyword.
  • The header of the base class should have the open annotation.
  • If your base class has a constructor that takes parameters, your derived class should initialize those parameters in the header itself.

Let’s create a class named Employee that derives from Person:

Overriding Member Functions

In Kotlin, you have to explicitly state that a member function can be overridden by using the open annotation in the method’s header in the base class. In the derived class, open functions can be overriden using the override annotation.

For example, to override the isEligibleToVote method, you add the following code snippet to the Employee class:

Creating Static Methods

Kotlin does not allow you to create static methods. However, it does allow you to create package level functions that do not belong to any class.

The main method is perhaps the best known static method. If you want to add the main method to a package named com.tutsplus.code.tutorial, then your code would look like this:

2. Functions

You’ve already learned how to create simple functions in the previous examples. The syntax you used to create those functions was very similar to that of Java. Kotlin, however, lets you to do a lot more with functions.

Creating Single Expression Functions

If a function returns the value of a single expression, then you can use the = operator after the function header followed by the expression to define the function.

For example, to add a method to the Person class that returns true if the person is an octogenarian, you would write:

As you can see, this shorthand syntax is more compact and readable.

Higher Order Functions and Lambda Expressions

Higher order functions are functions that can return functions or accept functions as parameters. A lambda expression, on the other hand, is just a function that has no name. Usually, lambda expressions and higher order functions are used together.

Consider the following example that demonstrates the syntax of a lambda expression:

This is a simple lambda expression that takes two parameters, x and y, and returns their sum. As you might have guessed, the parameters of the function are listed before the -> operator and the body of the function starts after the -> operator. This lambda expression can be assigned to a variable and used as follows:

Note that the type of the variable that holds the lambda expression specifies the types of its parameters and its return value.

Creating a higher order function that can accept the above lambda expression as a parameter is just as easy. For example, to create a function that doubles the result of the lambda expression, you would write:

You can call this function as follows:

Alternatively, you can pass the lambda expression directly to the higher order function:

Lambda expressions are often used with arrays. For example, consider the following array of Int values:

If you want to square the value of each item in the array, you can use the map function along with a lambda expression as follows:

3. Ranges

Range expressions are used very frequently in Kotlin. You already used them while creating the isTeenager and isOctogenarian methods.

To create a range, all you need is the .. operator.

To create a range in descending order, use the downTo function instead.

If you don’t want the step to be 1, you can specify a custom value using the step function.

You will see more range expressions later in this tutorial.

4. Conditional Constructs

if

In Kotlin, if is an expression that returns different values depending on whether the condition has been satisfied. The following example illustrates how this works.

when

The when expression is equivalent to Java’s switch. However, it is a lot more versatile. For instance, consider the following example.

As you can see, when can not only take single values but also expressions as its conditions.

5. Looping Constructs

for..in

In Kotlin, you can use the for..in loop to loop through arrays, collections, and anything else that provides an iterator. Its syntax is almost identical to that of Java, except for the use of the in operator instead of Java’s : operator. The following example shows you how to loop through an array of String objects.

With the help of range expressions, you can make this loop behave like a traditional, C-style, for loop.

while and do..while

The syntax of while and do..while loops in Kotlin is identical to the syntax used in Java. For example, the following Kotlin code loops over an array of String objects using a while loop:

6. String Templates

Kotlin lets you embed variables and expressions in strings by wrapping them in a pair of curly braces, prefixed by a $ symbol. For example:

Conclusion

In this tutorial, you learned the basics of the Kotlin programming language. Even though we covered several constructs here, Kotlin has a lot more to offer. In fact, as of June 2015, Kotlin is still available only as a preview. It is likely to see several improvements and new features in the coming months.

If you want to know how to use Kotlin in Android Studio, then take a look at How to Use Kotlin in Your Android Projects . To learn more about the Kotlin language, I recommend visiting the Kotlin documentation.

2015-06-22T16:10:58.000Z2015-06-22T16:10:58.000ZAshraff Hathibelagal

A Fast, Accurate Way to Test Internet Explorer on iOS, Mac OS X, and Android

$
0
0

Earlier this year, the Microsoft team launched a new tool to make it easier to test sites in IE regardless of which platform you’re on; seriously! It’s part of their work on Microsoft Edge and its new rendering engine and new user-agent string, which is a fork of Trident that’s far more interoperable with the mobile Web.

In this tutorial, I want to demonstrate what this looks like in Chrome on my MacBook and how to set it up.

tl;dr? Here are some Vines to show you it in action:

The tool is called RemoteIE and is designed to offer a virtualized version of the latest version of IE. This allows you to test out the latest version of IE without having to have a virtual machine installed. And if you want to test for past versions of IE, you can always use the free virtual machines on http://dev.modern.ie by starting here.

Getting It All Set Up

I ran through the steps to use the tool myself and wanted to document everything in case you run into any hiccups.

First, head on over to RemoteIE which will take you to this page:

modernie signin page

You’ll need a Microsoft account to use the service since it needs to associate the service to that account.

Application permissions page

If you have a Live.com or Outlook.com account you can use that, or you can register for a new one. No, you don’t need to use those services for anything else if you don’t want to, but they’ve actually gotten way better and might be worth a look.

Next, you’ll want to select which server is closest to you so you have the best possible performance:

Select a server location

At this point you’ll be asked to download the Microsoft Remote Desktop app for whichever platform you want. This could be for

  • Mac OS X
  • iPhone or iPad
  • Android
  • Windows x86 or x64
  • Windows RT
Download page

As you can see, I was serious when I said this would be available cross-platform. On your Mac, download the app from the Apple App Store. Clicking on the Mac link will direct you to the online Apple store site.

Microsoft Remote Desktop app in Apple App Store

Click on the View in Mac App Store button so that you can launch the App Store app on your Mac. You’ll be presented by a confirmation notice from Chrome (or your favorite OS X browser) to launch the external app:

Chrome confirmation page

And after you confirm it you’ll be in the App Store entry:

Microsoft Remote Desktop App Store page

In my case, I already had the app installed which is why it shows “Open”. If you don’t have it installed, go ahead and do so. Once you've installed it, look for it in Finder:

Microsoft Remote Desktop in Finder

Or if you’re like me, use the awesome Alfred to find it:

Typing Microsoft remote d in Alfred

Now, the next step is why I wanted to create this tutorial, since it isn’t immediately obvious once you run Remote Desktop what to do. When you launch the app, if you take a look at the header, you’ll see an entry called Microsoft RemoteApp. That’s what you’ll want to click:

Microsoft RemoteApp button

From there, you’ll now be asked for your Microsoft account information to determine what app subscriptions you have available:

Enter email address
Loading subscriptions

Now that it’s figured out that you’re legit, you’ll see a dialog showing what your app subscriptions are:

Subscriptions list

Again, I want to help you avoid confusion here since the UX at this specific point is a little off. When you click on the checkbox for “Internet Explorer (email: iewebeco@microsoft.com)”, an entry for “Internet Explorer->IE Technical Preview” will be added to the main Microsoft Remote Desktop app BUT the dialog with the checkbox I just mentioned doesn’t disappear. See here:

Subscription box checked

So heads up. Once you see the entry in the main app that says IE Technical Preview, you can close the dialog box with the checkbox. You can see in the previous image how I highlighted the close dialog icon.

We’re almost done. Next, go ahead and double-click on IE Technical Preview to launch your virtualized version of IE. It’ll take just a minute to spin everything up so be patient:

Please wait for the User Profile Service page

And once it’s up, you have a full-blown version of IE 11 Technical Preview ready for you. Notice in the following image how the F12 Developer Tools are there for you:

the F12 Developer Tools are there for you

More Testing Tools

This is a great new tool, and it’ll definitely lower the friction to testing on the latest version of IE, but there are some limitations that should be noted, including the inability to access the local file system. It would be great if that were possible, but VMs can be tricky to deal with, especially from a security perspective.

Of course, there are other free tools that can help you test for IE:

If you want more details, you can check out the Remote.IE announcement on the IE Blog. So now that you’ve got this all set up, let us know if it’s helping you spend less time testing.

This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and the new EdgeHTML rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ http://dev.modern.ie/.

2015-06-23T19:19:57.950Z2015-06-23T19:19:57.950ZRey Bango

A Fast, Accurate Way to Test Internet Explorer on iOS, Mac OS X, and Android

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

Earlier this year, the Microsoft team launched a new tool to make it easier to test sites in IE regardless of which platform you’re on; seriously! It’s part of their work on Microsoft Edge and its new rendering engine and new user-agent string, which is a fork of Trident that’s far more interoperable with the mobile Web.

In this tutorial, I want to demonstrate what this looks like in Chrome on my MacBook and how to set it up.

tl;dr? Here are some Vines to show you it in action:

The tool is called RemoteIE and is designed to offer a virtualized version of the latest version of IE. This allows you to test out the latest version of IE without having to have a virtual machine installed. And if you want to test for past versions of IE, you can always use the free virtual machines on http://dev.modern.ie by starting here.

Getting It All Set Up

I ran through the steps to use the tool myself and wanted to document everything in case you run into any hiccups.

First, head on over to RemoteIE which will take you to this page:

modernie signin page

You’ll need a Microsoft account to use the service since it needs to associate the service to that account.

Application permissions page

If you have a Live.com or Outlook.com account you can use that, or you can register for a new one. No, you don’t need to use those services for anything else if you don’t want to, but they’ve actually gotten way better and might be worth a look.

Next, you’ll want to select which server is closest to you so you have the best possible performance:

Select a server location

At this point you’ll be asked to download the Microsoft Remote Desktop app for whichever platform you want. This could be for

  • Mac OS X
  • iPhone or iPad
  • Android
  • Windows x86 or x64
  • Windows RT
Download page

As you can see, I was serious when I said this would be available cross-platform. On your Mac, download the app from the Apple App Store. Clicking on the Mac link will direct you to the online Apple store site.

Microsoft Remote Desktop app in Apple App Store

Click on the View in Mac App Store button so that you can launch the App Store app on your Mac. You’ll be presented by a confirmation notice from Chrome (or your favorite OS X browser) to launch the external app:

Chrome confirmation page

And after you confirm it you’ll be in the App Store entry:

Microsoft Remote Desktop App Store page

In my case, I already had the app installed which is why it shows “Open”. If you don’t have it installed, go ahead and do so. Once you've installed it, look for it in Finder:

Microsoft Remote Desktop in Finder

Or if you’re like me, use the awesome Alfred to find it:

Typing Microsoft remote d in Alfred

Now, the next step is why I wanted to create this tutorial, since it isn’t immediately obvious once you run Remote Desktop what to do. When you launch the app, if you take a look at the header, you’ll see an entry called Microsoft RemoteApp. That’s what you’ll want to click:

Microsoft RemoteApp button

From there, you’ll now be asked for your Microsoft account information to determine what app subscriptions you have available:

Enter email address
Loading subscriptions

Now that it’s figured out that you’re legit, you’ll see a dialog showing what your app subscriptions are:

Subscriptions list

Again, I want to help you avoid confusion here since the UX at this specific point is a little off. When you click on the checkbox for “Internet Explorer (email: iewebeco@microsoft.com)”, an entry for “Internet Explorer->IE Technical Preview” will be added to the main Microsoft Remote Desktop app BUT the dialog with the checkbox I just mentioned doesn’t disappear. See here:

Subscription box checked

So heads up. Once you see the entry in the main app that says IE Technical Preview, you can close the dialog box with the checkbox. You can see in the previous image how I highlighted the close dialog icon.

We’re almost done. Next, go ahead and double-click on IE Technical Preview to launch your virtualized version of IE. It’ll take just a minute to spin everything up so be patient:

Please wait for the User Profile Service page

And once it’s up, you have a full-blown version of IE 11 Technical Preview ready for you. Notice in the following image how the F12 Developer Tools are there for you:

the F12 Developer Tools are there for you

More Testing Tools

This is a great new tool, and it’ll definitely lower the friction to testing on the latest version of IE, but there are some limitations that should be noted, including the inability to access the local file system. It would be great if that were possible, but VMs can be tricky to deal with, especially from a security perspective.

Of course, there are other free tools that can help you test for IE:

If you want more details, you can check out the Remote.IE announcement on the IE Blog. So now that you’ve got this all set up, let us know if it’s helping you spend less time testing.

This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and the new EdgeHTML rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ http://dev.modern.ie/.

2015-06-23T19:19:57.950Z2015-06-23T19:19:57.950ZRey Bango

Create a Native Apple Watch App for watchOS 2

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

In this tutorial, you will learn how to take advantage of new APIs and functionality in watchOS 2 to make a native Apple Watch application. This includes picker interface elements, native animations, and alert controllers.

Introduction

At WWDC 2015, Apple announced the first major update to their Apple Watch platform, watchOS 2. Along with many new features and improvements, the most important aspect of this update for developers is the ability to create native Apple Watch apps. These native apps perform better and give developers access to new features, including the digital crown, microphone, and health sensors.

In this tutorial, I will show you how to create a native WatchKit application and briefly outline some of the new APIs available in watchOS 2. I will also show you how to upgrade an existing non-native watchOS 1 app to a native watchOS 2 app.

This tutorial requires that you are running Xcode 7 on a Mac running OS X Yosemite (10.10) or later. This tutorial builds on the concepts and WatchKit APIs available in watchOS 1. If you are not yet comfortable with the WatchKit framework, then start with one of our introductory tutorials on WatchKit.

1. Setting Up the Project

Open Xcode and create a new project. In Xcode 7, the new project wizard includes a watchOS section on the left. Choose the iOS App with WatchKit App template from the watchOS > Application section. Click Next to continue.

Choosing a Template

Fill in the information as shown in the below screenshot. Uncheck the checkboxes at the bottom, because we won't be needing those for this tutorial.

Configuring the Project

Complete the project setup and take a look at the folders Xcode has created for us. You should see three groups or folders in the Project Navigator on the left:

  • The Demo folder contains the source files and resources of the iOS application.
  • The Demo WatchKit App folder houses the storyboard and resources of the WatchKit application.
  • The Demo WatchKit Extension includes the source files and resources of the WatchKit extension, the brains of the WatchKit application so to speak.

Before we can start adding anything, we need to configure Xcode to build and run the correct target. In the top left of your Xcode window, next to the greyed out stop button, click the active scheme, Demo, and choose the following option:

Choosing the Correct Scheme and Simulator

Click the play button to build and run your app. In your dock, you should see two simulator icons appear. One of these is the regular iOS Simulator while the other is the Apple Watch Simulator.

The iOS Simulator on the Left and the Apple Watch Simulator on the Right

If the blank screen of your Apple Watch app does not appear automatically on the Apple Watch Simulator, then complete the following steps:

1. Navigate to the Apple Watch app on the iOS Simulator. You can find the Apple Watch app on the second home screen page.

Apple Watch App Location

2. Click on the Demo table view cell as shown below.

Select the Demo Table View Cell

3. Enable the Show App on Apple Watch switch as shown below.

Show App on Apple Watch

4. In the Apple Watch Simulator, navigate to the home screen by pressing Command+Shift+H or choosing Home from the Hardware menu of the Apple Watch Simulator.

Apple Watch home screen

If this doesn't immediately work, then toggle the switch on the iOS Simulator on and off. It may also help to quit Xcode and run the WatchKit app again.

If everything is working correctly, click the icon of the Apple Watch app in the Apple Watch Simulator. You should see a black screen with the time displayed in the top right.

Initial app screen

2. Creating the User Interface

It's time to start using some of the new APIs introduced in watchOS 2. In Xcode, open Interface.storyboard in the Demo WatchKit App folder and and add the following components to the Interface Controller Scene:

  • slider
  • picker
  • button
Interface Controller Scene

Select the slider and set its Maximum and Steps properties to in the Attributes Inspector.

Slider attributes

Double click the button and change its title to "Show Alert". Open the Assistant Editor so that you have the storyboard on the left and the contents of InterfaceController.swift on the right. Create an outlet for the slider by control-dragging from the slider in the storyboard to the InterfaceController class. Name the outlet slider. Do the same for the picker and name the outlet picker.

Create outlets for the slider and the picker

Control-drag from the button to the InterfaceController on the right to create an action. Name the action showAlertPressed. This action will be executed when the user taps the button.

Create an action for the button

Close the Assistant Editor on the right and open InterfaceController.swift in Xcode's code editor.

The slider and button that you added to the InterfaceController class should be familiar if you've worked with the WatchKit framework. The picker, however, is one of the new interface elements available in watchOS 2.

A picker for Apple Watch is represented by the WKInterfacePicker class. It works similarly to its iOS counterpart, UIPickerView. Users interact with a WKInterfacePicker instance by tapping it, scrolling through WKPickerItem objects with the digital crown, and then tapping again to select an item. A WKInterfacePicker can show items in one of three different styles:

  • List: This style displays picker items in a vertically stacked list for the user to scroll through. These items have a title and an optional accessory image. This is the only WKInterfacePicker style that supports text-based items and can show multiple items at once.
  • Stacked: This picker style presents a series of images as vertically animated cards. As the user turns the digital crown, the old card animates off-screen and the new card animates on-screen from the bottom of the picker. Items for this style can only contain images.
  • Image Sequence: This style shows a sequence of images without the transitions being animated. Turning the crown immediately displays the next or previous image in the sequence. Items for this picker style can also only contain images.

For this tutorial, you are going to create a simple list style picker with text-based items. Add the following code to awakeWithContext(_:) method of the InterfaceController class:

Build and run your app. You will see that the first three picker items are visible.

Visible picker items

To interact with your picker interface element, click it once and then scroll on your Mac's mouse or trackpad as you normally would. This will simulate the digital crown of the watch. You will then be able to scroll through the picker items.

Choosing picker items

3. Animation

Along with new interface elements and new ways for users to interact with Apple Watch apps, watchOS 2 supports native animations for WatchKit interface objects. The following attributes of interface elements are animatable in watchOS 2 apps:

  • alpha (opacity)
  • width and height
  • horizontal and vertical alignment
  • background color and tint color
  • content insets for groups

Animation is done through a single WKInterfaceController instance method, animateWithDuration(_:animations:). As a simple example, you are going to animate the slider by making it fade out and shrink towards the top of the screen. Add the following code to the willActivate method of the InterfaceController class:

Build and run your app and, once your app has finished launching, you should see the slider slowly shrinking and fading out.

Adding animation in watchOS 2

In the animation closure, you can animate any of the properties listed above. This applies to any of the interface elements in your app. This allows for another level of customization in your app's interface and also provides a much smoother way of hiding and showing elements.

4. Alerts

watchOS 2 also enables apps the present an alert interface very similar to that of a UIAlertView or UIAlertController on iOS. These alerts are shown by calling the presentAlertControllerWithTitle(_:message:preferredStyle:actions:) method on a WKInterfaceController instance.

The title and message parameters of this method are strings to be displayed on the alert's interface. The third parameter is a WKAlertControllerStyle enum:

  • Alert displays an alert sheet with stacked buttons and a default Cancel button at the bottom.
  • SideBySideButtonsAlert displays two buttons side by side.
  • ActionSheet displays one or two custom buttons with a Cancel button in the top left corner.

The fourth parameter is an array of WKAlertAction objects, which provide details for the alert buttons. This array must contain at least one object and for SideBySideButtonsAlert it must contain two.

WKAlertAction object is created with a title, style (WKAlertActionStyle.DefaultWKAlertActionStyle.Cancel, or WKAlertActionStyle.Destructive) and a block to be executed when that action is selected. Add the following code to the button's showAlertPressed action:

Build and run your app. When you press the Show Alert button, you will see an alert interface animate in and display the two actions you created.

Displaying a simple alert on watchOS 2

5. Upgrading to watchOS 2

When you open an existing Xcode project with a WatchKit app in Xcode 7, the following warning will show up in the Issue navigator on the left:

Project warning

Clicking the warning will show a list of the settings that need to be changed in your application to transition an existing WatchKit app to watchOS 2. At the bottom, you will see the following item:

WatchKit app setting change

If you click Perform Changes, Xcode will upgrade your existing WatchKit app for you. Once the upgrade has completed, you are ready to build, test, and ship a native app for watchOS 2.

Conclusion

The new APIs and features that you learned about in this tutorial are only the tip of the iceberg. Picker interface elements, alert controllers, and native animations are just some of the new features you can take advantage of in your Apple Watch apps on watchOS 2.

We will be posting many more tutorials on Tuts+ in the coming months, covering the new features and APIs available on watchOS 2. Be sure to look for those and feel free to leave any comments or questions you have in the comments below.

2015-06-24T17:15:27.000Z2015-06-24T17:15:27.000ZDavis Allie

Mobile Devices: the Gap Between Creation and Consumption

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

Can you create for the web using your mobile device?

This question has erupted from the mouths of web designers and programmers since the earliest models of smart phones. How capable are modern mobile devices where creating is concerned?

In this article, I will discuss some of the major hurdles which mobile phones face, with regard to creating for the web. We’ll mention a few tools along the way, but we’ll be focusing more on the discussion of how the mobile device is fundamentally different from a desktop or a laptop, and what opportunities and restrictions this brings to light.

We’re Making the Wrong Arguments

When two things are combined to make a fundamentally novel thing, we refer to this process as synthesis. It’s often difficult for our brains to determine the final effects of synthesis.

For example, before the first iPhone was revealed, people predicted what the iPod-inspired cell phone device would look like. Naturally, they predicted some qualities of the cell phone, and some qualities of the iPod, combined.

The synthesized product of two things does not always retain the appearance of the two things it is made from.

When it comes to creating digital products with mobile devices, this synthesis is still in progress. Many of the tools we’ve created have tried to shove the paradigms of development and creation that we are used to from laptops and desktops into the mobile device. Most of these tools replicate interface elements and workflows on the iPhone, simply adapting the interfaces enough to allow for touch inputs.

While this might work in a pinch (for example, if you’re stuck on a bus and your server goes down, or if you need to touch up a photo to send to a content editor), using many of these tools is impossible at worst and painful at best.

We have not yet found what true synthesis for mobile devices and the process of creation should look like.

What Can Mobile do Well?

In order to fully understand the future state of tooling for mobile devices as content creation platforms, we must look at the platform’s functions on their own. What do mobile devices excel at?

Mobility

Mobile devices are first of all, by nature, mobile. This allows for creation with very little setup or teardown. In contrast, even a laptop requires a flat surface and some space to operate; mobile devices typically only require one hand to operate at a nominal level. This provides for much more immediate access.

Senses

Mobile devices typically have much more sensing ability than the average laptop. Few mobile devices are manufactured without GPS, gyroscopes, and other motion detection abilities. These sensing tools provide access to raw information about the device and the developer’s current situation than is typically unavailable on laptop devices. This kind of information could be used, for example, to capture organic motion, hyper-accurate location information, or even auto-adaptation for the developer using the phone based on their physical orientation or location.

Media Capture

Mobile devices are able to generate relatively high quality media, specifically video and still images due to ever-increasing camera quality. Desktops and laptops typically are much more limited in this arena, providing tools for editing but not the hardware for capturing.

Touch

Mobile phones are optimized for touch. Laptops and desktops, typically, are not touch-enabled. This provides for unique opportunities in terms of interacting with visual interfaces that previously was impossible. For example, multi-touch display input provides potential for rich interactions that are entirely impossible to emulate on a desktop machine with a mouse.

Testing Connectivity

Mobile devices are much more accurate at testing mobile connectivity issues, as they can be hard-limited on which types of network access is used for data transfer. This is also not emulated, but is a real-life limitation that can be imposed on the phone.

Best Mobile-first Testing

Perhaps the most compelling feature of a mobile device is that it is the most effective testing platform for itself. Thus, if we can target the iPhone while creating on an iPhone, we are more able to see a direct relation between our creating space and what the final product will look like.

What do Mobile Devices do Poorly?

Typing

Specifically (and importantly), typing code on a mobile device is very difficult. Punctuation is far more prevalent in most programming languages than any spoken language. Typing punctuation is currently quite difficult. Furthermore, the limits of typing with two thumbs or pecking forefingers are quickly felt by programmers who have tried to write code on a mobile phone or tablet.

Filesystems

Until a significant shift in computing occurs, filesystems are core to the way programmers and web developers work. Unfortunately, mobile devices (and particularly Apple devices) don’t provide an easy-to-manipulate filesystem. Let’s propose an example exercise. How would you do the following on a mobile device?

  1. Clone a git repository
  2. Rename a few files in that repository
  3. Change permissions on a file in the repo
  4. Run an npm install or a bundle install from the root of that directory
  5. Push that directory to a remote repository
  6. Share the contents of that file with a coworker
  7. Run some commands to pre-process some of the files

As you can see, answering any of these questions requires a series of steps that are relatively non-intuitive for most developers. The most common solution for these questions, on a mobile device, is to find some kind of terminal emulator that allows the developer to get back to a Unix system, where they can run command line commands and have further control over their system.

Multi-tasking

Phones are pretty terrible at multi-tasking. Tablets are better, but still not great. Part of the reason for this is the screen real estate; it’s impossible for my phone to represent the amount of data that my 4k screen can represent. It’s also a product of how we use our phones most commonly: one app at a time. On a computer, we typically have multiple applications open, and visible, at all times.

The Need for Simulation

Creating from mobile devices also introduces a need for better simulation. When creating on a desktop, testing the use cases of other desktops is relatively simple, given that you have a screen that covers the largest likely screen sizes. It is also trivial to resize your browser window to match that of a given mobile device, providing for an easily accessed preview of the consequences and layout effects. This kind of simulation is quite literally impossible on mobile phones, as the screen size prohibits testing and simulating screens larger than itself without translating to a zoomed-out perspective of the same digital artefact.

This is also true of testing forthcoming technologies, such as VR, wearables, and super-size screens like 4k TVs. Until mobile devices support better emulation techniques, or some process for testing external peripherals, it will be difficult to make a switch for most developers who are creating for these endpoints.

Should Everything Be An “App”?

Another issue with the mobile development world is that, for the most part, mobile phones are built with the idea that applications are standalone feature packages. This collides with one of the arguably most powerful concepts used by developers: the unix philosophy of doing one very small thing, very well, and composing many of those small things to make complex, powerful workflows.

Development is a craft which traditionally requires raw, powerful tools. The current toolset looks more like a multi-tool Leatherman which doesn’t have everything you need to complete the task at hand. The workflow of a developer who creates primarily on a mobile device would necessarily be significantly different than the workflow of a developer who works on a laptop or desktop. This, on its own, is a challenge; the collective direction of the industry relies on the support and efforts being in relatively the same direction. In other words, we benefit from larger numbers of people adopting similar tools, practices, and workflows, because we experience similar problems and share solutions with each other. However, if we are using very different tools from one another, the collective knowledge suffers from that shift, as fewer people experience the same problems.

If it Walks and Quacks Like a Duck...

We should be creating tools that are intended to be used on a phone, rather than retrofitting tools that are intended to be used on a different medium to be simply accessible on a phone. We should take into account the strengths of the media, and avoid building tools that exploit the weaknesses.

The Future of the Web: Evolving Our Processes

The future of the web looks increasingly different from the present. We know that change is a part of this industry, but what kind of changes should we anticipate or bring on, and how will it affect the way we utilize mobile devices for creation?

One possible answer to this question is to offload the work mobile devices are bad at (namely, the coding) to be done based on predetermined models, algorithmic intelligence, and optimized techniques. This is how TheGrid.io claims to work, touting “websites that design themselves.” Of course, the reinvention of the WYSIWYG is certainly a constant work in progress.

As we uncover new and profound ways to interact with different devices, we should keep in mind a few simple truths: 

  1. We should never be so tied to a process that we forget the importance of the outcome. 
  2. We should prefer tools that evolve versus tools that adapt. (Evolution is a fundamental change in interaction, while adaptation is a shallow affordance that translates one interaction into an unnatural input designed for a different interaction.) 
  3. A great craftsman doesn’t change his toolset often, but is willing to invest in high quality tools up front that last a lifetime

Conclusion

Mobile devices have embedded themselves into the world, and they are here to stay. It is our job as creators to assess and push these devices to their potential, and to seek new avenues that spark creativity through new possibilities. We should look at these devices not simply as smaller computers, but in terms of their strengths. Once we learn to harness the strength of mobile, true synthesis will take place, and the now-painful process of creating for the web on mobile will become an indispensable skill.

2015-06-26T09:03:43.428Z2015-06-26T09:03:43.428ZJonathan Cutrell

An Introduction to ClockKit

$
0
0

Introduction

At WWDC 2015, Apple announced its first major update to the Apple Watch software, watchOS 2. This new update brought with it many new APIs and features for developers to take advantage of, including native apps, access to more of the Apple Watch's hardware, and better communication with the parent iOS app.

In this tutorial, I am going to be showing you how to take advantage of another new feature, the ability to create custom watch complications using the ClockKit framework. This tutorial requires that you are running Xcode 7 on OS X Yosemite (10.10) or later.

If you don't know already, Apple Watch complications are the small interface elements that display information on the watch face.

Apple Watch complications

The above screenshot shows how five complications are displayed on the Modular watch face in addition to the time in the top-right corner.

1. Setting Up the Project

Create a new project in Xcode, using the watchOS > Application > iOS App with WatchKit App template.

Project template

Next, configure the project as shown below, making sure the Include Complication is checked.

Project options

Once Xcode has created your project, open the ClockKit Introduction WatchKit Extension in the Project Navigator. You will see a new Complications Configuration section as shown below.

Complications Configuration

The five checkboxes under Supported Families represent the different complication families that your app supports. In this tutorial, we are going to focus on the Modular Large family. You can uncheck the other checkboxes for now.

Modular Large family choice

As stated in Apple's watchOS 2 Transition Guideit is highly encouraged that your app supports all five families. The following image shows where these different families are used.

Apple Watch complication families
Image Credit: Apple watchOS 2 Transition Guide

2. Setting Up the Complication

To teach you how to use ClockKit, you are going to create a simple complication that shows the time, name, and genre of fake TV shows on a particular station throughout the day.

To begin, open ComplicationController.swift in the ClockKit Introduction WatchKit Extension folder. Xcode has automatically created this file for you. It contains a ComplicationController class, which conforms to and implements the CLKComplicationDataSource protocol.

The methods associated with this protocol are how you provide data to ClockKit about the complications you want to show. The methods of the protocol contain a handler that you must call to pass data back to ClockKit.

Timelines

When providing data to ClockKit, you do so in the form of a timeline. You do this by filling up your complication's timeline with data objects that are linked to a specific point in time. These data objects are modeled by the CLKComplicationTimelineEntry class. When a particular point in time is reached, ClockKit automatically displays the correct content for your app.

Your timeline entries are retrieved and cached by ClockKit well before the time they are intended to be displayed. This means that the data must be able to be retrieved and scheduled in advance. Each application has a limited budget of time to refresh its content in the background. In other words, complications are not a replacement for push notifications or the notification center.

The major benefit of providing data this way is to maintain an excellent user experience. The content for each complication is immediately available when the user raises her wrist. One of the other benefits of using this timeline data model is the ability to easily adopt the new Time Travel feature in watchOS 2. This is when the user turns the digital crown while looking at the watch face and the data of the complications reflects the time that has been travelled to.

In your code, under the Timeline Configuration mark, you will see four methods that are required to configure the timeline. To make this tutorial simple and easy to understand, we are only going to support forwards time travel and provide data for up to 24 hours. To do this, updated the implementation of the first three methods as shown below.

The fourth method in the Timeline Configuration section, getPrivacyBehaviorForComplication(_:withHandler:), is used to specify whether or not you want your complication's content to be shown when the device is locked or not. The default value passed to the handler, ShowOnLockScreen, means that the data will always be visible.

Templates

Scroll to the bottom of the ComplicationController class and find the getPlaceHolderTemplateForComplication(_:withHandler:) method. In this method, you create and pass a CLKComplicationTemplate back to the handler for the data that you want to show. In this tutorial, you are going to use the CLKComplicationTemplateModularLargeStandardBody template, which displays three lines of text. For each TV show, these three lines are going to be:

  • start and end time 
  • name
  • genre

There are quite a few templates available across the five complication families. The following image shows the available templates and highlights the one that we are going to be using in this tutorial.

Available watch complication templates
Image Credit: Creating Complications with ClockKit (WWDC 2015)

Text Providers

Because space for content is limited on an watch display, even more so in the small sizes of watch face complications, you provide text-based data to ClockKit, using CLKTextProvider objects. These providers aim to avoid truncating content, which results in a bad user experience. With these text providers, you describe your intentions about what content you want displayed and then ClockKit handles the final formatting for you.

For example, if you want to display a date in your complication, you use the CLKDateTextProvider with a specified date and set of units (month, day, hour, etc.). That will correctly format the date for the available space. An example of this would be taking the date "Thursday, October 22" and being able to format it to:

  • Thur, October 22
  • Thur, Oct 22
  • Oct 22
  • 22

For a complete list of the text providers and templates available in ClockKit, you can look at Apple's ClockKit Framework Reference.

Now that you know about the basic templates and text providers, you are ready to create a template for your complication. In the getPlaceHolderTemplateForComplication(_:withHandler:) method, add the following code:

With this code, you create a Standard Body template for the Modular Large family and give it three text providers. The CLKSimpleTextProvider objects should be straightforward. The CLKTimeIntervalTextProvider takes two dates and formats them into a string, such as "10:00AM-3:30PM" or "1:00-2:45PM".

3. Testing the Complication

Now that we have configured our timeline and provided ClockKit with a template for our complication, we can finally test out the results of our work. In the top left of your Xcode window, choose your complication target and one of the available simulators. Click the play button to build and run your app.

Choosing the complication target

When the Apple Watch simulator launches, you will most likely be presented with the following watch face:

Initial watch face

To test out your complication, you need to complete a few steps.

Step 1

Press Command+Shift+2 to simulate a force touch and click on the watch face.

Watch face chooser

Step 2

Press Command+Shift+1, swipe to the right to the Modular face and click on the Customize button.

Modular face option

Step 3

Swipe to the right, tap the middle complication, and scroll to the bottom, using your trackpad or mouse to simulate the digital crown.

Complication picker

Step 4

Simulate a force touch again to get back to the watch face chooser and choose the Modular face.

Modular face with your complication

Congratulations. You have just gotten you very first ClockKit complication to show up on an Apple Watch watch face. Now it's time for you to start filling it out with some actual (fake) data.

4. Providing Data to ClockKit

Before we create any timeline entries for our complication, we are first going to create a Show struct to easily model our data and then create values of this new type. Add the following code snippet to ComplicationController.swift, before the start of the ComplicationController class definition.

As you can see, we create the Show structure and create a static array that contains four shows. You will use this array as your complication's data source.

In the ComplicationController class, find the getCurrentTimelineEntryForComplication(_:withHandler:) method and add the following code to it:

You first create a complication template, just as you did before, and fill it with content. You then create a CLKComplicationTimelineEntry object with two parameters:

  • a date
  • a template

The date you specify here is where this entry will be positioned on the timeline and shown to the user. For our app, we give our timeline entry a date of fifteen minutes before the show is due to start so that it will show up on the user's watch just before the show is on.

Next, you need to provide ClockKit with all the other shows you have created for your complication. This is done in the getTimelineEntriesForComplication(_:afterDate:limit:withHandler:) method. The limit parameter in this method is there so that a single application can't overload the ClockKit cache with data and knows exactly how many timeline entries it needs to provide.

Add the following code to the getTimelineEntriesForComplication(_:afterDate:limit:withHandler:) method in ComplicationController.swift:

You first create an empty array of CLKComplicationTimelineEntry objects. You then iterate through the shows you created earlier. For each show, if it starts after the date provided by ClockKit and the limit of entries hasn't been exceeded, then you create a template and append this to the array.

At the end of this method, you call the handler with your array. Passing nil or an empty array to the handler will tell ClockKit that you have no more data to provide and it will stop querying your CLKComplicationDataSource object until more data is required.

With these methods in place, you are now ready to see your completed complication. Click the play button to build and run your app. When the simulator first launches, you will see your complication showing the data for the first show that you created.

Complication showing first show

If you then scroll with your trackpad or mouse to enter Time Travel mode, you will see that the other shows you created are displayed by your complication at the correct point in time.

Time travel

Conclusion

In this tutorial, you learned the fundamentals of the ClockKit framework and how to create a custom watch face complication for the Apple Watch. This included the five complication families, basic templates and text providers, and timeline-based data.

In your complication, you also built in support for the watchOS 2 time travel feature and adding in new data as time progresses. As always, if you have any comments or questions, leave them in the comments below.

2015-06-26T17:15:21.000Z2015-06-26T17:15:21.000ZDavis Allie

An Introduction to ClockKit

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

Introduction

At WWDC 2015, Apple announced its first major update to the Apple Watch software, watchOS 2. This new update brought with it many new APIs and features for developers to take advantage of, including native apps, access to more of the Apple Watch's hardware, and better communication with the parent iOS app.

In this tutorial, I am going to be showing you how to take advantage of another new feature, the ability to create custom watch complications using the ClockKit framework. This tutorial requires that you are running Xcode 7 on OS X Yosemite (10.10) or later.

If you don't know already, Apple Watch complications are the small interface elements that display information on the watch face.

Apple Watch complications

The above screenshot shows how five complications are displayed on the Modular watch face in addition to the time in the top-right corner.

1. Setting Up the Project

Create a new project in Xcode, using the watchOS > Application > iOS App with WatchKit App template.

Project template

Next, configure the project as shown below, making sure the Include Complication is checked.

Project options

Once Xcode has created your project, open the ClockKit Introduction WatchKit Extension in the Project Navigator. You will see a new Complications Configuration section as shown below.

Complications Configuration

The five checkboxes under Supported Families represent the different complication families that your app supports. In this tutorial, we are going to focus on the Modular Large family. You can uncheck the other checkboxes for now.

Modular Large family choice

As stated in Apple's watchOS 2 Transition Guideit is highly encouraged that your app supports all five families. The following image shows where these different families are used.

Apple Watch complication families
Image Credit: Apple watchOS 2 Transition Guide

2. Setting Up the Complication

To teach you how to use ClockKit, you are going to create a simple complication that shows the time, name, and genre of fake TV shows on a particular station throughout the day.

To begin, open ComplicationController.swift in the ClockKit Introduction WatchKit Extension folder. Xcode has automatically created this file for you. It contains a ComplicationController class, which conforms to and implements the CLKComplicationDataSource protocol.

The methods associated with this protocol are how you provide data to ClockKit about the complications you want to show. The methods of the protocol contain a handler that you must call to pass data back to ClockKit.

Timelines

When providing data to ClockKit, you do so in the form of a timeline. You do this by filling up your complication's timeline with data objects that are linked to a specific point in time. These data objects are modeled by the CLKComplicationTimelineEntry class. When a particular point in time is reached, ClockKit automatically displays the correct content for your app.

Your timeline entries are retrieved and cached by ClockKit well before the time they are intended to be displayed. This means that the data must be able to be retrieved and scheduled in advance. Each application has a limited budget of time to refresh its content in the background. In other words, complications are not a replacement for push notifications or the notification center.

The major benefit of providing data this way is to maintain an excellent user experience. The content for each complication is immediately available when the user raises her wrist. One of the other benefits of using this timeline data model is the ability to easily adopt the new Time Travel feature in watchOS 2. This is when the user turns the digital crown while looking at the watch face and the data of the complications reflects the time that has been travelled to.

In your code, under the Timeline Configuration mark, you will see four methods that are required to configure the timeline. To make this tutorial simple and easy to understand, we are only going to support forwards time travel and provide data for up to 24 hours. To do this, updated the implementation of the first three methods as shown below.

The fourth method in the Timeline Configuration section, getPrivacyBehaviorForComplication(_:withHandler:), is used to specify whether or not you want your complication's content to be shown when the device is locked or not. The default value passed to the handler, ShowOnLockScreen, means that the data will always be visible.

Templates

Scroll to the bottom of the ComplicationController class and find the getPlaceHolderTemplateForComplication(_:withHandler:) method. In this method, you create and pass a CLKComplicationTemplate back to the handler for the data that you want to show. In this tutorial, you are going to use the CLKComplicationTemplateModularLargeStandardBody template, which displays three lines of text. For each TV show, these three lines are going to be:

  • start and end time 
  • name
  • genre

There are quite a few templates available across the five complication families. The following image shows the available templates and highlights the one that we are going to be using in this tutorial.

Available watch complication templates
Image Credit: Creating Complications with ClockKit (WWDC 2015)

Text Providers

Because space for content is limited on an watch display, even more so in the small sizes of watch face complications, you provide text-based data to ClockKit, using CLKTextProvider objects. These providers aim to avoid truncating content, which results in a bad user experience. With these text providers, you describe your intentions about what content you want displayed and then ClockKit handles the final formatting for you.

For example, if you want to display a date in your complication, you use the CLKDateTextProvider with a specified date and set of units (month, day, hour, etc.). That will correctly format the date for the available space. An example of this would be taking the date "Thursday, October 22" and being able to format it to:

  • Thur, October 22
  • Thur, Oct 22
  • Oct 22
  • 22

For a complete list of the text providers and templates available in ClockKit, you can look at Apple's ClockKit Framework Reference.

Now that you know about the basic templates and text providers, you are ready to create a template for your complication. In the getPlaceHolderTemplateForComplication(_:withHandler:) method, add the following code:

With this code, you create a Standard Body template for the Modular Large family and give it three text providers. The CLKSimpleTextProvider objects should be straightforward. The CLKTimeIntervalTextProvider takes two dates and formats them into a string, such as "10:00AM-3:30PM" or "1:00-2:45PM".

3. Testing the Complication

Now that we have configured our timeline and provided ClockKit with a template for our complication, we can finally test out the results of our work. In the top left of your Xcode window, choose your complication target and one of the available simulators. Click the play button to build and run your app.

Choosing the complication target

When the Apple Watch simulator launches, you will most likely be presented with the following watch face:

Initial watch face

To test out your complication, you need to complete a few steps.

Step 1

Press Command+Shift+2 to simulate a force touch and click on the watch face.

Watch face chooser

Step 2

Press Command+Shift+1, swipe to the right to the Modular face and click on the Customize button.

Modular face option

Step 3

Swipe to the right, tap the middle complication, and scroll to the bottom, using your trackpad or mouse to simulate the digital crown.

Complication picker

Step 4

Simulate a force touch again to get back to the watch face chooser and choose the Modular face.

Modular face with your complication

Congratulations. You have just gotten you very first ClockKit complication to show up on an Apple Watch watch face. Now it's time for you to start filling it out with some actual (fake) data.

4. Providing Data to ClockKit

Before we create any timeline entries for our complication, we are first going to create a Show struct to easily model our data and then create values of this new type. Add the following code snippet to ComplicationController.swift, before the start of the ComplicationController class definition.

As you can see, we create the Show structure and create a static array that contains four shows. You will use this array as your complication's data source.

In the ComplicationController class, find the getCurrentTimelineEntryForComplication(_:withHandler:) method and add the following code to it:

You first create a complication template, just as you did before, and fill it with content. You then create a CLKComplicationTimelineEntry object with two parameters:

  • a date
  • a template

The date you specify here is where this entry will be positioned on the timeline and shown to the user. For our app, we give our timeline entry a date of fifteen minutes before the show is due to start so that it will show up on the user's watch just before the show is on.

Next, you need to provide ClockKit with all the other shows you have created for your complication. This is done in the getTimelineEntriesForComplication(_:afterDate:limit:withHandler:) method. The limit parameter in this method is there so that a single application can't overload the ClockKit cache with data and knows exactly how many timeline entries it needs to provide.

Add the following code to the getTimelineEntriesForComplication(_:afterDate:limit:withHandler:) method in ComplicationController.swift:

You first create an empty array of CLKComplicationTimelineEntry objects. You then iterate through the shows you created earlier. For each show, if it starts after the date provided by ClockKit and the limit of entries hasn't been exceeded, then you create a template and append this to the array.

At the end of this method, you call the handler with your array. Passing nil or an empty array to the handler will tell ClockKit that you have no more data to provide and it will stop querying your CLKComplicationDataSource object until more data is required.

With these methods in place, you are now ready to see your completed complication. Click the play button to build and run your app. When the simulator first launches, you will see your complication showing the data for the first show that you created.

Complication showing first show

If you then scroll with your trackpad or mouse to enter Time Travel mode, you will see that the other shows you created are displayed by your complication at the correct point in time.

Time travel

Conclusion

In this tutorial, you learned the fundamentals of the ClockKit framework and how to create a custom watch face complication for the Apple Watch. This included the five complication families, basic templates and text providers, and timeline-based data.

In your complication, you also built in support for the watchOS 2 time travel feature and adding in new data as time progresses. As always, if you have any comments or questions, leave them in the comments below.

2015-06-26T17:15:21.000Z2015-06-26T17:15:21.000ZDavis Allie

Coloring Android Apps with Palette

$
0
0

One of the defining features of material design is the use of color to compliment and emphasize content on the screen. Using the Palette class, developers can extract prominent colors from a bitmap for use in their apps to customize user interface elements.

In this article, you will learn how to create a Palette object from a bitmap. Contained within each Palette is a set of Swatch objects that will allow you to work with specific color profiles and a list of visible colors from the image.

Example of the Palette colors generated from a base image

1. Creating a Palette

To get started, you will need to import the palette support library into your project by including the following line in the dependencies node of your project's build.gradle file. Since this is a v7 support library, the Palette related classes are available back to Android API 7.

After running a gradle sync on your project, you are able to generate a Palette from a bitmap. This can be done using the Palette.Builder either synchronously by calling the generate() method without any parameters, or asynchronously by calling generate(Palette.PaletteAsyncListener listener). Because it can take time to create the Palette, it is recommended that the synchronous method only be called from a background thread. In addition to the two generate methods, the Palette.Builder class has a couple of other useful methods that come with their own trade-offs:

  • maximumColorCount(int numOfSwatches) allows you to change how many Swatch objects should be generated from the bitmap. The default for the builder is 16. The more Swatch objects you generate, the longer it will take to generate the Palette.
  • resizeBitmapSize(int maxDimension) resizes the bitmap so that its largest dimension will only be as large as the passed value of this method. The larger your bitmap, the longer it will take to generate a Palette. Likewise, smaller bitmaps will process faster, but you will lose out on color precision.

The following code snippet shows how to create a bitmap from a local resource and asynchronously create a Palette object.

Once you have a Palette, you can begin working with the associated Swatch objects.

2. Swatches

Swatch objects represent colors generated from an image's palette. Each Swatch contains:

  • an RGB (Red, Green, Blue) and HSL (Hue, Saturation, Lightness) value for a color.
  • a population value reflecting the number of pixels represented by the Swatch.
  • a color value that can be used for title text when displayed on the Swatch's primary color.
  • a color value that can be used for a body of text when displayed on the Swatch's primary color.

Swatch Profiles

Each Palette has a set of six predefined color profiles:

  • vibrant
  • light vibrant
  • dark vibrant
  • muted
  • light muted
  • dark muted

While each of these can be useful depending on your app design, vibrant and dark vibrant are the most commonly used. One thing to note is that any of these profiles may be null, so you should handle this situation accordingly. In the sample project, in the onGenerated(Palette palette) method from the asynchronous Palette.Builder, you can see how to extract each profile Swatch.

setViewSwatch(TextView view, Palette.Swatch swatch) is a method that accepts a Swatch and TextView, and sets the TextView background and text colors from values in the Swatch. You'll notice that we first check to see if the Swatch is null and, if it is, we simply hide the view.

Example of profile Swatch colors

Additional Swatches

In addition to the standard profile Swatch objects, each Palette contains a list of general Swatch objects generated from the bitmap. These can be retrieved from the Palette as a List by using the getSwatches() method.

In the sample project, this List is retrieved and placed into an ArrayAdapter<Palette.Swatch> that then displays the Swatch primary color and body text color, as well as the number of pixels represented in the bitmap by this Swatch. One thing to pay attention to is that the list is not in any particular order. In the sample project, I have sorted the items by their population value.

In this code snippet, mAdapter is the adapter of Swatch objects with the following methods:

Example of generated Swatches from a bitmap

Conclusion

In this article, you have learned about the Palette support library and how to extract swatches of color from a bitmap. This will allow you to customize your user interface elements, such as backgrounds and text, so that they compliment images within your app. When coupled with the Color and ColorUtil classes (available in the v4 support library), you have even more options available for the colorization of your app.

2015-06-29T18:15:56.000Z2015-06-29T18:15:56.000ZPaul Trebilcox-Ruiz

Coloring Android Apps with Palette

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

One of the defining features of material design is the use of color to compliment and emphasize content on the screen. Using the Palette class, developers can extract prominent colors from a bitmap for use in their apps to customize user interface elements.

In this article, you will learn how to create a Palette object from a bitmap. Contained within each Palette is a set of Swatch objects that will allow you to work with specific color profiles and a list of visible colors from the image.

Example of the Palette colors generated from a base image

1. Creating a Palette

To get started, you will need to import the palette support library into your project by including the following line in the dependencies node of your project's build.gradle file. Since this is a v7 support library, the Palette related classes are available back to Android API 7.

After running a gradle sync on your project, you are able to generate a Palette from a bitmap. This can be done using the Palette.Builder either synchronously by calling the generate() method without any parameters, or asynchronously by calling generate(Palette.PaletteAsyncListener listener). Because it can take time to create the Palette, it is recommended that the synchronous method only be called from a background thread. In addition to the two generate methods, the Palette.Builder class has a couple of other useful methods that come with their own trade-offs:

  • maximumColorCount(int numOfSwatches) allows you to change how many Swatch objects should be generated from the bitmap. The default for the builder is 16. The more Swatch objects you generate, the longer it will take to generate the Palette.
  • resizeBitmapSize(int maxDimension) resizes the bitmap so that its largest dimension will only be as large as the passed value of this method. The larger your bitmap, the longer it will take to generate a Palette. Likewise, smaller bitmaps will process faster, but you will lose out on color precision.

The following code snippet shows how to create a bitmap from a local resource and asynchronously create a Palette object.

Once you have a Palette, you can begin working with the associated Swatch objects.

2. Swatches

Swatch objects represent colors generated from an image's palette. Each Swatch contains:

  • an RGB (Red, Green, Blue) and HSL (Hue, Saturation, Lightness) value for a color.
  • a population value reflecting the number of pixels represented by the Swatch.
  • a color value that can be used for title text when displayed on the Swatch's primary color.
  • a color value that can be used for a body of text when displayed on the Swatch's primary color.

Swatch Profiles

Each Palette has a set of six predefined color profiles:

  • vibrant
  • light vibrant
  • dark vibrant
  • muted
  • light muted
  • dark muted

While each of these can be useful depending on your app design, vibrant and dark vibrant are the most commonly used. One thing to note is that any of these profiles may be null, so you should handle this situation accordingly. In the sample project, in the onGenerated(Palette palette) method from the asynchronous Palette.Builder, you can see how to extract each profile Swatch.

setViewSwatch(TextView view, Palette.Swatch swatch) is a method that accepts a Swatch and TextView, and sets the TextView background and text colors from values in the Swatch. You'll notice that we first check to see if the Swatch is null and, if it is, we simply hide the view.

Example of profile Swatch colors

Additional Swatches

In addition to the standard profile Swatch objects, each Palette contains a list of general Swatch objects generated from the bitmap. These can be retrieved from the Palette as a List by using the getSwatches() method.

In the sample project, this List is retrieved and placed into an ArrayAdapter<Palette.Swatch> that then displays the Swatch primary color and body text color, as well as the number of pixels represented in the bitmap by this Swatch. One thing to pay attention to is that the list is not in any particular order. In the sample project, I have sorted the items by their population value.

In this code snippet, mAdapter is the adapter of Swatch objects with the following methods:

Example of generated Swatches from a bitmap

Conclusion

In this article, you have learned about the Palette support library and how to extract swatches of color from a bitmap. This will allow you to customize your user interface elements, such as backgrounds and text, so that they compliment images within your app. When coupled with the Color and ColorUtil classes (available in the v4 support library), you have even more options available for the colorization of your app.

2015-06-29T18:15:56.000Z2015-06-29T18:15:56.000ZPaul Trebilcox-Ruiz

Swift 2.0: Exit Early With guard

$
0
0

Does it surprise you that I’m dedicating a tutorial to a simple addition as the guard statement? I hope you’ll better understand my excitement at the end of this tutorial. During this tutorial, I hope to convince you that guard is anything but a redundant addition to the Swift programming language.

Minimizing Complexity

Conditionals are a fundamental component of every programming language. Objective-C and Swift are no exception to this rule. If you plan to write an application of any complexity, conditionals will cross your path, there’s no escaping them.

Unfortunately, conditionals are often the very cause of complexity. Nested conditionals in particular can lead to difficult to find bugs, hard to understand code, and easily overlooked edge cases.

To keep nested if statements to a minimum, I frequently use the following pattern in Objective-C.

The idea is to bail out as soon as possible. The if statements in the example represent a set of requirements that need to be met before the rest of the method’s body is executed.

The above example translates to the following slightly more complex equivalent.

Do you see the problem lurking in this example? We’re already nested two levels deep without having done anything interesting.

It’s easy to translate the above pattern to Swift. The syntax looks similar, but due to customers being an optional, we need to unwrap the customers argument before we can access its value.

Exiting Early

Swift 2 introduces the guard statement. It was designed specifically for exiting a method or function early. The guard statement is ideal for getting rid of deeply nested conditionals whose sole purpose is validating a set of requirements. Take a look at the updated example in which I’ve replaced every if statement with the new guard statement.

There are several things worth noting. Let’s start with the syntax.

Syntax

The guard keyword emphasizes that we are validating a requirement. We are guarding against something. In the example, we explicitly check if reachable and connected are true. If they aren’t, then we exit the method early. The point is that the syntax is more explicit about the requirements than a regular if statement.

Exit

Note that a guard statement always has an else clause. The else clause is executed if the condition of the guard statement evaluates to false. Using guard makes much more sense when you’re validating requirements.

In the else clause, you must transfer control away from the scope in which the guard statement appears. We use a return statement in the above example, but you could, for example, use a continuestatement if you’re in a loop or throw an error. Take a look at the updated example below in which we throw an error in the else clause. Note the throws keyword in the method declaration to indicate that fetchListOfCustomers(_:) is a throwing method.

Powerful

A guard statement is just as powerful as an if statement. You can use optional bindings and even the use of where clauses, introduced in Swift 1.2, is permitted. I’m sure you agree that the example is easy to understand, eliminating unnecessary nested conditionals.

Scope

An important difference with if statements is the scope of variables and constants that are assigned values using an optional binding. In the above example, the customers constant was assigned a value using an optional binding. The customers constant is accessible from the scope the guard statement appears in. This is an important detail and one of the key advantages of using guard.

Conclusion

If you thought that guard was a simple variation on Swift’s if statement, then I hope I’ve convinced you otherwise. While if statements will continue to be your tool of choice in most situations, guard has a number of advantages in certain situations. This is especially true if used in combination with error handling, which was also introduced in Swift 2.

2015-07-01T18:50:44.000Z2015-07-01T18:50:44.000ZBart Jacobs
Viewing all 1836 articles
Browse latest View live