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

6 Do's and Don’ts for a Great Android User Experience

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

The most popular Android apps have something in common: they all provide a great user experience. In this post, I'll share some tips that will help your app stand out.

Regardless of the kind of app you have in mind, or your target audience, designing a great user experience can help to ensure your app is a success. In this article, I’m going to share six things you should, and should not do, to make sure your app delivers the best possible experience to your end-users.

Since creating and launching an Android app is a multi-step process, I’ll be touching on every part of the Android development lifecycle—from making tough decisions about which versions of Android you should support, to creating a product that’ll appeal to a global audience, right through to analyzing your app’s post-launch performance.

1. Don’t Get Hung Up on Trying to Support Every Version of Android

While it’s natural to want to get your app in front of as many users as possible, don’t fall into the trap of assuming that supporting more versions of Android is always the best approach.

The key to attracting a large audience is to provide the best possible user experience, and setting your sights on supporting as many versions of Android as possible can actually damage the overall user experience.

The major issue is that as you continue to travel back through Android’s release history, it’s going to become harder to make your app play nicely with the earlier releases.

Sometimes, there may be a clear point where your app becomes incompatible with earlier releases of Android. For example, if your app absolutely requires access to Bluetooth Low Energy (BLE), then your app isn’t going to be able to run on anything earlier than Android 4.3—the version where BLE support was added to the Android platform.

However, sometimes this line may not be quite so clear-cut, and you may find yourself debating whether to modify or even remove non-critical features, in order to create something that can run on a particular version of Android. Small compromises can gradually chip away at the quality of the user experience, so always take stock of the impact these changes will have on your users.

In addition, customizing, optimizing and testing your app for each different version of Android requires time and effort, so you’ll also need to ask yourself whether this investment is worth the potential rewards. Basically, how many more users could you potentially gain by supporting each version of Android? You can get an indication of how many Android devices are running each release of the Android platform, by checking out the stats at Google's Dashboard.

Ultimately, there’s no universal right or wrong answer, so you’ll need to weigh up the pros and cons and decide what makes the most sense for your particular project.

Once you’ve decided which versions of Android you’re going to support, add this information to your module-level build.gradle file using minSdkVersion (the lowest API your app is compatible with), targetSdkVersion (the highest API level you’ve tested your app against), and compileSdkVersion (the version of the Android SDK that Gradle should use to compile your app).

To make sure your app benefits from the latest Android features while remaining compatible with earlier releases, it’s recommended that you set your minSdkValue as low as possible, while setting targetSdkVersion and compileSdkVersion to the latest version of the Android SDK.

2. Do Design for Multiple Screens

When you’re working on an Android app, it’s not uncommon to spend most of your time testing that app on your own Android smartphone or tablet. Particularly during the early stages of app development, creating multiple Android Virtual Devices (AVDs) will probably be the last thing on your mind.

However, don’t lose sight of the bigger picture! It’s easy to get hung up on designing for the one screen that’s physically in front of you, but it’s essential that your app looks good and functions correctly across a wide range of Android devices.

The Android system will automatically scale your layouts, drawables and other resources so they render at the appropriate size for the current screen, but for the best user experience you should aim to create the illusion that your app was designed for the user’s specific device. Relying on auto-scaling alone isn’t going to cut it!

To make sure your app delivers the best user experience across a wide range of devices, you’ll need to provide alternate resources that are optimized for different devices, such as drawables that target Android’s generalized density buckets, and alternate layouts that are optimized for landscape mode.

Once you’ve created your alternate resources, you’ll need to create alternate directories that are tagged with the appropriate configuration qualifiers, and then place the resources inside these directories—for example, a res/layout-land directory would contain layouts that are designed for landscape orientation. The Android system will then automatically load the resource that best matches the current screen configuration at runtime.

While most configuration qualifiers are relatively straightforward, providing resources that target different screen sizes is a bit more complex, requiring you to specify the exact dpi value where the system should start using this resource. So, you basically need to tell the system, “I want to use this layout when my app is being displayed on devices with 800dpi or more available screen width.”

You arrive at these values by testing your app across a wide range of different AVDs and making a note of all the screen sizes that your default resources are struggling with—for example, maybe your default layout starts to look cluttered once the device falls below a certain dpi threshold.

There are three screen size configuration qualifiers that you can use in your projects:

  • smallestWidth sw<value>dp. Allows you to specify the minimum horizontal space that must be available before the system can use the resources in this directory. For example, if you had a set of layouts that require 800dpi or more, you’d create a res/layout-sw800dp directory. Note that a device’s smallestWidth is a fixed value that doesn’t change when the user switches their device between portrait and landscape orientation.

  • Available screen width w<value>dp. The minimum horizontal space that must be available before the system can use these resources. A device’s w<value>dp value does change when the user switches between portrait and landscape mode.

  • Available screen height: h<value>dp. The minimum height that must be available before the system can use these resources. The device’s h<value>dp value will change depending on whether the user is holding their device in landscape or portrait.

Designing for multiple screens is mostly about creating alternate versions of your project’s resources and adding them to the appropriate directories—then rinse and repeat. However, there are some additional tricks you can use when creating these alternate resources that can really help create the illusion that your app was designed for the user’s specific device:

  • Use density-specific drawables in combination with 9-patch images. If the system needs to resize an image to fit the current screen then by default it’ll resize the whole image, which can lead to blurry, pixelated or otherwise odd-looking images. For the best possible results, you should specify the exact pixels that the system should replicate if it needs to resize your image, by delivering your project’s drawables as 9-patch images. Provide multiple 9-patch versions of each drawable, where each 9-patch targets a different screen density, and the system will then load the 9-patch image that’s the best fit for the current screen density and stretch the 9-patch image’s ‘stretchable’ sections, if required. You can create 9-patch images using any PNG editor, or you can use the Draw 9-patch editor that’s included in the Android SDK (you’ll find it in sdk/tools/Draw9patch.bat).

  • Create multiple dimens.xml files. It’s recommended that you define your layout’s values in a separate dimens.xml file rather than hard-coding them into your project. However, you can take this one step further and create multiple dimens.xml files that target different screen sizes and densities. For example, you might create a values-ldpi/dimens.xml file where you define the values that your app should use when it’s installed on a device that falls into the ‘low’ density category. The system will then load the appropriate dimensions for the current device, and apply them to your layout.

  • Consider using fragments. Fragments provide you with a way of dividing a single Activity into separate components that you can then display in different ways, depending on the current screen configuration. For example, you may choose to display multiple fragments side-by-side in a multi-pane layout when your app is installed on a device with a larger screen, and as separate Activities when space is more limited. The simplest way to add a fragment to your layout is by inserting a <fragment> element into your layout resource file. Alternatively, you can add fragments to a layout via your application code—this method may be more complicated, but it gives you the added flexibility of being able to add, remove or replace fragments at runtime.

3. Do Consider Supporting Different Languages

Android is a global operating system, so if your app is going to provide the best user experience to this global audience then you should consider localizing your app for different languages, and potentially different regions.

Typically, the biggest part of localizing an app is translating your project’s strings.xml file into the different language(s) you want to support. Unless you happen to be fluent in your target languages, you’re going to need to enlist the help of a translator. If you don’t have anyone in mind, then the Developer Console’s Google Play App Translation services can point you in the direction of potential translators.

Youll find a Purchase Translations option in the Google Play Developer Console

Once you’ve chosen a translator, you should take a critical look at your strings.xml file before sending it off for translation. Check for things like spelling mistakes and typos, and make sure your strings.xml is formatted in a way that makes it easy to read, bearing in mind that your translator may not be an Android developer themselves.

You should also provide as much context as possible, so make sure you add a comment to each string explaining what this string is for, where and when it’ll appear in your app, and any restrictions the translator needs to be aware of. For example, if a string needs to remain under 10 characters long in order to fit its allocated space in your layout, then this is something the translator needs to be aware of!

Once the translator has returned your translated strings.xml file(s), you’ll need to create a directory for each alternative file, which means you’ll need to work out what configuration qualifiers to use.

A locale configuration qualifier consists of an ISO code, which is essentially a language code, and an optional country or regional code, which is preceded by a lowercase r. For example, if you wanted to provide French (fr) text for people located in Canada (can), then you’d create a res/values-fr-rcan directory.  

If you do provide localized text, then bear in mind that some strings may expand or shrink significantly during translation, so you’ll need to test that your layouts can accommodate all versions of your project’s strings.

The easiest way to test your localized resources is to install your app on an AVD and then emulate the different locations and language settings. At this point, the system will load the localized versions of your resources and display them in your app.

You can change the locale settings in a running AVD by issuing the following Android Debug Bridge (adb) commands:

Followed by:

Note, you’ll need to replace the fr-CAN with whatever configuration qualifier you want to test against.

If you’ve designed your app with best practices in mind, then your layouts should be flexible enough to display the majority of your localized strings. However, if the length of your strings varies dramatically then you may need to provide alternate layouts that are optimized for different locales.

While your project’s strings.xml file is generally the main resource you’ll need to localize, you should also consider whether there are other resources you might need to translate such as drawables that contain text, video or audio that contains dialogue, or any resources that might be inappropriate for the locale you’re targeting.

Once you’re confident that you’ve provided all the necessary localized resources and you’ve performed your own round of testing, you should consider arranging a beta test with native speakers in each of your target locales. Native speakers can often pick up on mistakes that even a translator may overlook, and may be able to give you some advice about how you can make your app more appealing to this particular section of your audience. You can arrange this kind of targeted beta testing via the Google Play Developer Console.

When you’re finally ready to launch your app, make sure you take the time to create localized versions of your app’s Google Play page, as this will instantly make your app more attractive to international users who are browsing the Google Play store. You should also try and provide screenshots that clearly show the localized text inside your app, so users aren’t left wondering whether you’ve just translated your app’s Google Play page, and not the actual text inside your app.

And the hard work doesn’t end once you’ve launched your app! Once you've attracted your international audience, you’ll need to hang onto them by providing ongoing support across multiple languages—even if that means resorting to machine translators like Google Translate. At the very least, you should keep an eye on your Google Play reviews, to see whether users in certain locales are reporting similar issues, which may indicate an issue with one or more of your app’s localized resources.

4. Don’t Forget About Accessibility!

As an app developer, you’ll want to make sure that everyone can enjoy using your app, so it’s important to consider how accessible your app is to people who may be experiencing it without sound, colour or other visuals, or anyone who interacts with their Android device via an accessibility tool such as a screen reader.

Android is designed with accessibility in mind, so it has a number of built-in accessibility features that you can utilize without having to make any fundamental changes to your application’s code.

Let's look at a number of minor tweaks you can make to your project, which will have a huge impact on your app’s accessibility:

Consider Supplying Additional Content Descriptions

Accessibility services such as TalkBack read onscreen text out loud, making them an important tool for helping users with vision-related problems interact with their Android devices.  

When designing your Android app, you should consider how easy it'll be for users to navigate your app using its onscreen text alone. If you do need to provide some additional context, then you can add a content description to any of your app’s UI components, which will then be read aloud by services such as TalkBack. To add a content description, open your project’s layout resource file and add an android:contentDescription attribute to the UI component in question, followed by the description you want to use.

Support Focus Navigation

Users with limited vision or limited manual dexterity may find it easier to interact with their device using a directional controller, such as a trackpad, D-pad or keyboard, or software that emulates a directional controller. To make sure your app supports this kind of focus navigation, you’ll need to add the android:focusable="true” attribute to each of your app’s navigational components.

When users navigate your app using directional controls, focus gets passed from one UI element to another in an order that's determined automatically using an algorithm. However, you can override these defaults and specify which UI component should gain focus when the user moves in a particular direction, by adding the following XML attributes to any of your UI components: android:nextFocusUp, android:nextFocusDown, android:nextFocusLeft, and android:nextFocusRight. For example:

Make Your Text Resizable

Users with vision impairments may choose to increase the size of the font that appears across their device. To make sure any font changes are reflected in your app, define your text in scale pixels—and don’t forget to test what impact Android’s various font sizes will have on your app’s UI, just in case you need to make some adjustments to your layout.

Use Recommended Touch Target Sizes

To help people with manual dexterity challenges navigate your app, it’s recommended that you set all touch targets to 48 x 48 dpi or higher, and make sure the space between these targets is at least 8 dpi.

Consider Disabling Timed-Out Controls

Some UI components may disappear automatically after a certain period of time has elapsed—for example, video playback controls often disappear once a video has been playing for a few moments. 

The problem is that accessibility services such as Talkback don’t read controls until the user has focused on them, so if a timed-out control vanishes before the user has a chance to focus on it, then they won’t be aware that these controls even exist. For this reason, you should consider upgrading timed-out controls to permanent controls whenever accessibility services are enabled.

5. Do Put Your App’s Performance to the Test

Just because your app doesn’t crash or throw any errors during testing, doesn’t automatically mean it’s performing well, as some performance problems can be insidious and difficult to spot during regular testing. No-one enjoys using an app that takes forever to load, lags whenever you try and interact with it, and gobbles up the available memory, so you should always put your app through a number of performance-based tests before releasing it into the wild.

The Android SDK comes with a wide range of tools that you can use to specifically test your app’s performance. In this section, we’re going to look at a few of the ones you’ll definitely want to use; however, there are many more that are worth investigating (you’ll find more information in the official Android docs).

Note that all of these tools can only communicate with a running app, so you’ll need to make sure the app you want to test is installed on either an AVD or a physical device that’s connected to your development machine.

Before we get started, it’s worth noting that if you do identify a problem with your app’s performance, it’s recommended that you time your code before trying to fix this problem. You can then time your code again after you believe you’ve fixed the problem, and you'll be able to see exactly what impact your changes have had on your app’s performance.

You can time your code using TraceView, which you access by selecting the Android Device Monitor’s DDMS tab, then selecting the device and the process you want to profile, and giving the Start Method Profiling icon a click (where the cursor is positioned in the following screenshot).

In the Android Device Monitor select the DDMS tab followed by Start Method Profiling

At this point you can select either Trace based profiling (traces the entry and exit of every method) or Sample based profiling (collects the call stacks at a frequency specified by you). Once you’ve made your selection, spend some time interacting with your app. When you’re ready to see the results, you can load the trace file into the viewer by giving the Stop Method Profiling icon a click. The trace file displays each thread’s execution as a separate row, so you can see exactly how long each part of your project takes to run.

Identifying Overdraw

When the system draws your app’s UI, it starts with the highest-level container and then works its way through your view hierarchy, potentially drawing views on top of one another in a process known as overdraw. While a certain amount of overdraw is inevitable, you can reduce the time it takes your app to render by identifying and removing any instances of excessive or unnecessary overdraw.

If you have a device running Android 4.2 or higher, you can check the amount of overdraw present in any app installed on that device, by selecting Settings > Developer Options > Debug GPU Overdraw > Select overdraw areas. The system will then add a coloured overlay to each area of the screen, indicating the number of times each pixel has been drawn:

  • No Color. This pixel was painted once.

  • Blue. An overdraw of 1x. These pixels were painted twice.

  • Green. An overdraw of 2x.

  • Light red. An overdraw of 3x.

  • Dark red. An overdraw of 4x or more.

Most apps include some level of overdraw, but if you spot large areas of overdraw in your app then you should look at whether there’s any way of reducing the number of times each pixel is being redrawn, and one of the effective methods is removing unnecessary views.

The Android Device Monitor’s Hierarchy Viewer provides a high-level overview of your app’s entire view hierarchy, which can help you identify views that aren’t contributing anything to the final rendered image the user sees onscreen. 

To launch Hierarchy Viewer, click the Android Device Monitor’s Hierarchy View button, and then select the device and the Activity you want to inspect, followed by the blue Load the view hierarchy into the tree view icon.  

In the Android Device Monitor select the Hierarchy View button followed by Load the view hierarchy into the tree view

You may also want to export the Hierarchy Viewer output as a Photoshop document. This is a particularly effective technique for identifying views that aren’t contributing anything to the final UI, as each view is displayed as a separate Photoshop layer, meaning you can hide and reveal each layer and see exactly what impact this will have on the final image the user sees onscreen.

To create a PSD document, simply give the Capture the window layers as a Photoshop document icon a click.

Spotting Memory Leaks

Garbage collection (GC) is a normal system behaviour that’s important for ensuring your app and the device as a whole continue to run smoothly.

However, if your app isn’t managing memory properly—maybe it’s leaking memory or allocating a large number of objects in a short period of time—then this can trigger more frequent GC events that also run for longer. You can take a look at exactly what GC events are occurring in your app in the main Android Studio window; open the Android Monitor tab towards the bottom of the window, followed by the Monitors tab. The Memory Monitor tool will then start recording your app’s memory usage automatically.

Select the Android Monitor tab towards the bottom of the main Android Studio window followed by the Monitors tab

If you keep interacting with your app, then eventually you’ll see a sudden drop in the amount of allocated memory, indicating that a GC event has occurred. Repeat this process, making sure you explore different areas of your app, and see what impact this has on the GC events. If you do spot any strange GC behaviour, then you’ll want to investigate further as this may indicate a problem with the way your app is using memory.

There are a couple of tools you can use to gather more information about your app’s memory usage. Firstly, you can use the Android Device Monitor’s Heap tab to see how much heap memory each process is using, which will flag up any processes that are gobbling up available memory.

To use the Heap tool, select the Android Device Monitor’s DDMS tab, followed by the process you want to examine, and then click the Update heap button. The Heap tab won’t display any data until after a GC event has occurred, but if you’re feeling impatient you can always trigger a GC event by giving the Cause GC button a click.

Open the Heap tool by selecting DDMS  Heap

Another tool that can help you gather information about your app’s memory usage is Allocation Tracker, which lets you see exactly what objects your app is allocating to memory. To use Allocation Tracker, select the Android Device Monitor’s DDMS tab, followed by Allocation Tracker and the process you want to examine.

Click the Start Tracking button and spend some time interacting with your app, especially any parts that you suspect may be causing your app’s memory management problems. To see all the data Allocation Tracker has gathered during the sampling period, select the Start Tracking button, followed by the Get Allocations button.

6. Do Use Analytics Tools

Understanding your audience is a crucial part of creating a successful app.

Having access to data about who your audience is and how they’re using your app means you can make more informed decisions about how to build on your app’s success—and improve on the areas where your app isn’t doing quite so well.

Gathering this kind of user data is particularly useful for enabling you to identify trends across different sections of your audience. For example, you might decide that a certain segment of your audience is particularly valuable—maybe they’re racking up the largest percentage of in-app purchases, or they’re investing an above-average amount of time in your app. Armed with this information, you can take extra steps to support these users, making sure that your most valuable users remain engaged with your app.  

At the other end of the scale, you might discover an area where your app is struggling. For example, maybe users who are running a particular version of Android have considerably lower engagement rates, or are more likely to uninstall your app. In this scenario, you might want to test your app on this particular version of Android to see whether there’s a bug or any other error that might be ruining the user experience for this section of your user base.

Basically, the more data you can gather about your audience and their behaviour, the greater your chances of keeping your existing user happy, attracting new users, and generally delivering an all-round great experience for everyone who comes into contact with your app.

In this section I’m going to look at two services that can put a wealth of information at your fingertips: Firebase Analytics and the Google Play Developer Console.

Firebase

You can use Firebase Analytics to gather data about your users, such as their age, gender and location, plus information on over 500 in-app events. You can even define your own custom events, if required.

To add Firebase Analytics to your project, you’ll need Google Play services 10.0.1 or higher and the Google Repository version 26 or higher, so open the SDK Manager and make sure these components are up to date. You’ll also need to be running Android Studio 1.5 or higher, and be signed up for a free Firebase account.

If you're running Android 2.2 or later, then you can connect your app to Firebase Analytics using the Firebase Assistant. Open Android Studio, launch the project in question, and:

  • Select Tools > Firebase from the Android Studio toolbar.

Launch the Firebase Assistant by selecting Tools from the Android Studio toolbar followed by Firebase

  • Click to expand the Analytics section, then select the Log an Analytics event link.

  • Click the Connect to Firebase button.

  • In the dialogue that appears, opt to create a new Firebase project.

  • Click the Connect to Firebase button.

  • After a few moments, you should see a Connected message.

  • Give the Add analytics to your app button a click.

  • In the subsequent dialogue, click Accept changes.

And that’s it! You can now view all your Firebase Analytics data by logging into the Firebase Console, selecting the project you want to examine, and then selecting Analytics. This data will update periodically throughout the day.

The Developer Console

You can also gain a valuable insight into your app’s performance and user behaviour via the Developer Console.

To view this data, log into your Developer Console account, select the app you want to examine, and then select Dashboard from the left-hand menu.

The Developer Console contains lots of useful information, so it’s well worth taking the time to explore its various sections in detail. However, there are a few areas that may be of particular interest:

  • User Acquisition Performance. This section contains a breakdown of how users are finding your app’s Google Play listing, for example the percentage of users who landed on your page via a UTM-tagged link, an AdWords ad, or the number of people who simply found your app by browsing the Google Play store.

  • Finance. If you’ve implemented a monetization strategy, such as in-app products or a subscription option, then you can use the Developer Console to review your app’s financial performance. The Finance section contains information such as the average amount each paying user is investing in your app, how much revenue is being generated by each product you offer through your app, and how much each section of your user base is spending, based on factors such as their geographical location, age, and the version of Android they’re using.

  • Crashes & ANRs. This section contains all the data users have submitted about application crashes and application not responding (ANR) errors, giving you a chance to identify and fix any issues that may be occurring in your app before users start leaving you negative reviews on Google Play. Note that crashes that aren’t reported by your users won’t appear in the Developer Console.

You may also want to consider downloading the Google Play Developer Console app, which lets you review all this information on the go.

Conclusion

In this article, we looked at six things you should and shouldn’t do when you’re developing an Android app. What are your golden rules for designing a great user experience? Leave a comment below and let us know.

In the meantime, check out some of our other courses and tutorials on Android programming!

2017-02-02T12:57:44.000Z2017-02-02T12:57:44.000ZJessica Thornsby

How to Make Calls and Use SMS in Android Apps

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

In this tutorial, you'll learn about the Android Telephony and SMS API. You'll learn how to make a call from your app and how to monitor phone call events, as well as how to send and receive SMS.

1. How to Make A Call 

To start off, I'll show you how to initiate a call from your application either by using the phone dialer app or directly from your app to make it easier for your users.

Create a New Android Studio Project

Fire up Android Studio and create a new project with an empty activity called MainActivity.

Android Studio create  a new Activity screenshot

Lay Out the Screen

For now, our layout will just have an EditText field and a Dial button:

Emulator dial screen with phone number given

Modify the MainActivity Class

In the code block below, we are creating an ACTION_DIAL intent to display the phone dialer. The phone number is parsed from our tel URI scheme: tel:XXXXXXXX. Note that you don't need any permission for this to work:

If you run the app and click the dial button, you'll be taken to the dialer app, and from there you have to actually dial the number. You can change this flow to actually make the call from within your app by simply changing the ACTION_DIAL intent to ACTION_CALL instead. This will require the android.permission.CALL_PHONE permission, though. 

Emulator screen defualt phone dialer with the phone number

2. Monitoring Phone Call Events

In this section, we are going to learn how to monitor phone call events in the Android system. The phone can be in three states: 

  1. idle (when it is unused)
  2. ringing (when there is an incoming call)
  3. off-hook (when the call is answered)

Add the Permission 

We need the permission READ_PHONE_STATE to be able to monitor the phone state. Add it to AndroidManifest.xml:

Create the PhoneStateListener Object

We create an object of the PhoneStateListener class, and then override its onCallStateChanged() method (in IntelliJ it is easy to do this with Control-O, and then select or search for the method to override). We'll handle changes to the call state changes by displaying a Toast. Note that we can also access the incoming phone numbers when this method is triggered:

Depending on your application needs, you could also override one of these other event methods: onCellInfoChanged()onCallForwardingIndicatorChanged()onCellLocationChanged(), or onSignalStrengthChanged().

Listening to the Phone Call State

In order to begin listening to the phone call state, we need to get the TelephonyManager from the system service and initialize it in onCreate().

In the onResume() method, we can begin to listen using the TelephonyManagerlisten() method, passing it the PhoneStateListener instance and the static LISTEN_CALL_STATE. We stop listening in the onStop() method by passing the LISTEN_NONE as the second argument to listen().

Other phone listening options possible are LISTEN_CELL_LOCATIONLISTEN_SIGNAL_STRENGTHLISTEN_CALL_FORWARDING_INDICATOR, and LISTEN_CELL_INFO.

Finally, run the app and make sure an incoming call comes in. 

Emulator incoming call states

This monitoring will only work when the app is in the foreground. For this to work in the background (when our application is not running), we would need to create a BroadcastReceiver so that even if the app isn't running, we can still monitor for phone call states. Depending on your app requirements, that could be a much better way to listen for phone call state changes. I'll show you how to do this in the next section.

Be aware that we are only monitoring incoming calls. For us to monitor outgoing calls, we need additional permissions. To monitor outgoing calls, include the following line in your AndroidManifest.xml file.

How to Use the Emulator to Make Calls and Send SMS Messages

You can use your emulator to simulate making a call or sending an SMS message, but you'll need to do a little setup. Open your emulator, click the last button on the right-side navigation bar to open the extended control dialog, and then select the phone control button. 

Using emulator to make call and send SMS

3. Monitoring Phone Call Events in the Background

Create a BroadcastReceiver

Just like in the previous section, we need to create an event listener to monitor phone state changes. The major difference is that this time we'll extend the BroadcastReceiver base class so we can listen for the phone call state even if the application is not running. Be sure not to register the listener more than once! Our check for this is on line 36.

Modify AndroidManifest.xml

A broadcast receiver works only if it is registered. We need to tell the Android system about our broadcast receiver by registering it in the AndroidManifest.xml file by connecting our PhoneCallStateReceiver class to the <intent-filter> that describes the system broadcast we wish to receive—in this case, PHONE_STATE.

Monitoring Outgoing Calls

For outgoing calls, you need to include the NEW_OUTGOING_CALL action intent <action android:name="android.intent.action.NEW_OUTGOING_CALL"/> in the <intent-filter> of the receiver in AndroidManifest.xml

To get the phone number of the intended outgoing call, inside the onReceive(Context, Intent) method, we get the number from the intent as an extra. To prevent that intended call from going through, we can call setResultData() and pass it a null argument. The resultData is used as the actual number to call. 

You can learn more about broadcasts and broadcast receivers in our tutorial here on Envato Tuts+:

4. Sending SMS Messages

You have just two major choices for sending SMS: using the device SMS client application or skipping the client by sending the SMS directly from your app. We'll look at both scenarios, and you can decide which one is better for your use case. Let's start by sending an SMS using the device SMS client.

Set Up the Layout

First, we need to modify our main layout to have an EditText field for the message and a Send Message button.

Modify the MainActivity 

Inside our onCreate() method in our MainActivity class, create an intent with ACTION_SENDTO as the first argument and a smsto:<phone number> URI as the second argument. The text message will be the value of the sms_body extra: 

Here, the SMS client will monitor the status of the message delivery. 

Run the App

When all required fields are entered, clicking the Send SMS button will open the user's SMS client, or will give the user options to select an app if one hasn't already been chosen.

Send SMS flow

5. Sending SMS Messages Directly

Next let's see how to send the SMS directly from our application instead of using the device SMS client. 

Add Permission in AndroidManifest.xml

As usual, we need to register the permission in AndroidManifest.xml.

Modify the MainActivity class 

Next, for Android 6.0 (API level 23) and above, we need to request the SEND_SMS permission during runtime. 

To learn more about Android runtime permissions and how they've changed in version 6.0, check out our tutorial here on Envato Tuts+:

To send an SMS, we get the default SmsManager instance and then call its sendTextMessage() method, passing in the phone number as the first argument and the message as the second argument:

To monitor the status of delivery, the SMSManagersendTextMessage() method has two optional PendingIntent parameters: sentIntent and deliveryIntent.

If you want to use sentIntent, watch for the result code Activity.RESULT_OK on success, or one of RESULT_ERROR_GENERIC_FAILURERESULT_ERROR_RADIO_OFF, and RESULT_ERROR_NULL_PDU to indicate an error.

6. Receiving an SMS Message

For your app to begin receiving SMS messages from the user's phone, its best to have a broadcast receiver registered so that it can be alerted when a new SMS arrives even if your app is not running in the foreground. 

Add the Permission 

Add the RECEIVE_SMS permission to AndroidManifest.xml:

Next, we need to check and see if the app has permission to receive SMS messages at runtime. So in the MainActivity class, check for the RECEIVE_SMS permission. If it is not found, request it.

Create a Broadcast Receiver

We are retrieving each object of the SmsMessage class by using the method createFromPdu(byte[] pdu), passing it a PDU (protocol data unit). We are then adding it to our messages array. 

To support API 23 and above, you should include the format String extra (either "3gpp" for GSM/UMTS/LTE messages in 3GPP format or "3gpp2" for CDMA/LTE messages in 3GPP2 format). 

Now, run the app, close it, and send your emulated phone an SMS.

Emulator showing a toast when it receives an SMS in the background

Conclusion

In this tutorial, you learned about:

  • making a call from your app
  • monitoring phone call events
  • sending SMS messages using either the device messaging app or directly from your own app
  • receiving SMS messages in the background

There's lots more you can do with phone calls and SMS messages in Android. Visit the Android Telephony API and the SMSManager API documentation to learn more. 

In the meantime, check out some of our other posts on Android development!

2017-02-15T09:51:07.000Z2017-02-15T09:51:07.000ZChike Mgbemena

Kickstart Your iOS Career With These 6 Courses

$
0
0

Do you want to develop apps for iOS devices?

If so, these six courses will give you the solid foundation you need. With expert guidance from Envato Tuts+ instructors Derek Jensen and Markus Mühlberger, you'll see what's new in iOS 10 and learn all the fundamentals of Swift, the programming language that developers use to create iOS apps. Then you'll move on to more complex topics like unit testing and creating Apple TV apps.

1.What's New in iOS 10

With every new version of iOS, Apple introduces a bunch of new features and enhancements to the developer experience. These are especially exciting to the mobile development community, because they create whole new possibilities for the kinds of app we can code for our users.

In this course, Envato Tuts+ instructor Markus Mühlberger will show you some of the coolest new features for developers in iOS 10. You'll learn how to make a sticker pack, create a custom extension, provide haptic feedback, and even have a conversation with your users with SiriKit!

 

2.Create iOS Apps With Swift 3

Swift is a programming language from Apple, designed specifically for creating iOS, macOS, and watchOS apps. Swift has a powerful type system for safe programming and adds many features to make the lives of programmers easier. Even though it's only a couple of years old, Swift is already very popular with iOS developers.

In this course you will learn how to use Swift 3 to create iOS apps. Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. You'll learn about all the basic features of the language, from variables to classes. You'll also get an introduction to using Xcode for app development as you follow along with Markus implementing the course project: an interactive Fibonacci sequence viewer.

 

3. Up and Running With Swift 2

This course will start from the foundations to give you a thorough understanding of the Swift language. It will introduce Swift's types, control flow and object-orientation syntax, with a special emphasis on the features that make Swift unique. 

 

4. iPhone App Development With Swift

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

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

 

5. Unit Testing With Swift and XCTest

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

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

 

6. Create an Apple TV App With Swift

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

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

 

Start Learning With a Free Trial

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

2017-02-15T13:21:02.278Z2017-02-15T13:21:02.278ZAndrew Blackman

Kickstart Your iOS Career With These 6 Courses

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

Do you want to develop apps for iOS devices?

If so, these six courses will give you the solid foundation you need. With expert guidance from Envato Tuts+ instructors Derek Jensen and Markus Mühlberger, you'll see what's new in iOS 10 and learn all the fundamentals of Swift, the programming language that developers use to create iOS apps. Then you'll move on to more complex topics like unit testing and creating Apple TV apps.

1.What's New in iOS 10

With every new version of iOS, Apple introduces a bunch of new features and enhancements to the developer experience. These are especially exciting to the mobile development community, because they create whole new possibilities for the kinds of app we can code for our users.

In this course, Envato Tuts+ instructor Markus Mühlberger will show you some of the coolest new features for developers in iOS 10. You'll learn how to make a sticker pack, create a custom extension, provide haptic feedback, and even have a conversation with your users with SiriKit!

 

2.Create iOS Apps With Swift 3

Swift is a programming language from Apple, designed specifically for creating iOS, macOS, and watchOS apps. Swift has a powerful type system for safe programming and adds many features to make the lives of programmers easier. Even though it's only a couple of years old, Swift is already very popular with iOS developers.

In this course you will learn how to use Swift 3 to create iOS apps. Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. You'll learn about all the basic features of the language, from variables to classes. You'll also get an introduction to using Xcode for app development as you follow along with Markus implementing the course project: an interactive Fibonacci sequence viewer.

 

3. Up and Running With Swift 2

This course will start from the foundations to give you a thorough understanding of the Swift language. It will introduce Swift's types, control flow and object-orientation syntax, with a special emphasis on the features that make Swift unique. 

 

4. iPhone App Development With Swift

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

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

 

5. Unit Testing With Swift and XCTest

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

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

 

6. Create an Apple TV App With Swift

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

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

 

Start Learning With a Free Trial

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

2017-02-15T13:21:02.278Z2017-02-15T13:21:02.278ZAndrew Blackman

How to Create a Camera App With Ionic 2

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

As a prudent developer, you might be wary of creating hybrid applications that depend on Android's native APIs. A few years ago, I was too, what with Android having so many version-specific and device-specific quirks. Today, however, we can trust hybrid application development frameworks to handle most of those quirks transparently. Ionic 2, which builds on Apache Cordova, is one such framework.

Ionic 2 has wrappers for several popular Cordova plugins that allow you to easily make use of Android's native resources, such as cameras, hardware sensors, and the file system. In this tutorial, I'll show you how to use those wrappers alongside Ionic 2 UI components to create a simple camera app.

Prerequisites

To follow along, you'll need:

  • the latest version of the Android SDK
  • Node.js v6.7.0 or higher
  • a device or emulator running Android 4.4 or higher
  • a basic understanding of TypeScript and Angular 2

1. Install Cordova and Ionic

Both Ionic and Cordova are available as NPM modules, so the easiest way to install them is to use the npm command. Here's how you can install both of them globally:

Once the installation is complete, type in the following to make sure that the Ionic command-line interface, or CLI for short, is configured correctly.

The output of the above command should look like this:

2. Create a New Project

Ionic's CLI makes it very easy for you to create new Ionic 2 projects with all the required configuration files and boilerplate code. It also offers several starter templates to choose from. For now, let us simply create a project using the blank starter template.

At this point, you'll have a new directory called MyCameraApp. For the rest of this tutorial, we'll be working inside this directory.

3. Configure the Project

By default, an Ionic 2 project isn't configured to target any mobile platform. Here's how you add support for Android:

You must also manually point Ionic 2 to the location where you installed the Android SDK. If you are using Mac or Linux, use the export command to do so.

4. Install Ionic Plugins

Our camera app needs access to the device's camera and file system, both of which are native resources. If you're familiar with Cordova, you might be aware that hybrid applications usually interact with such resources through plugins. Although you can use a Cordova plugin directly in an Ionic 2 project, it is much easier to use its Ionic Native wrapper instead.

To access the camera, we'll use the cordova-plugin-camera-preview plugin. It allows us to not only take pictures, but also apply several image filters to them. Here's how you can add it to your project:

We'll, of course, have to save the pictures we take on external storage media, such as SD cards. To do so, we'll use the cordova-plugin-file plugin.

Lastly, in order to support Android devices running API level 23 or higher, we'll need the cordova.plugins.diagnostic plugin.

5. Define the Layout

Our app's user interface will be composed of the following components:

  • a camera preview window
  • a floating action button to take pictures
  • a floating action button to apply image filters

We'll be creating the camera preview window programmatically in a later step. For now, let's create an HTML layout containing just two floating action buttons.

Because our blank app already has a page, we'll be using it instead of creating a new one. To modify its layout, open src/pages/home/home.html. Empty its contents and add a new <ion-content> tag to it.

To create a floating action button, you can create an ordinary HTML button and add the ion-fab attribute to it. Additionally, by wrapping the <button> tag inside an <ion-fab> tag, you can position it.

A floating action button usually has an icon. By using the <ion-icon> tag, you can add any Ionicon to it.

Accordingly, add the following to your layout file:

As you can see in the above code, we've added click event handlers to both the buttons. We'll define them later.

6. Acquire Permissions

On devices running Android API level 23 or higher, you must explicitly ask the user for permissions to access the camera and file system during runtime. To do so in your hybrid app, you can use methods available in the Diagnostic Ionic Native wrapper.

Start by opening src/pages/home/home.ts and importing Diagnostic.

Inside the constructor of the HomePage class, add a call to a new checkPermissions() method. Additionally, add a ToastController object to the class using dependency injection. We'll be using it to display Ionic 2 toasts, which are almost identical to native Android's snackbars.

After making the above changes, your code should look like this:

Inside the checkPermissions() method, use the isCameraAuthorized() method of the Diagnostic class to check if the app already has permissions to access both the camera and the file system. Because the method returns a Promise object, you must use a callback to handle its result.

If the app doesn't have the required permissions, you can use the requestCameraAuthorization() method to ask for them.

If the user does grant the permissions, or if our app already has them, we can go ahead and initialize the camera preview inside initializePreview(), a method we'll be creating in the next step. Otherwise, let's simply display a toast containing an error message using the create() and present() methods of the ToastController class.

Accordingly, add the following code inside the checkPermissions() method:

Here's what the camera authorization dialog looks like on a device running Android Marshmallow:

Camera authorization dialog

7. Create Camera Preview

The CameraPreview Ionic Native wrapper lets you display a live camera preview inside your hybrid app. However, because the preview uses an Android fragment instead of an HTML element, adding it to our page is slightly complicated.

Before you start, make sure you import both CameraPreview and CameraPreviewRect.

Using a CameraPreviewRect object, you can specify the position and size of the camera preview. For now, let's make it fill the device's screen completely.

At this point, we have everything we need to start the camera preview. Therefore, call the startCamera() method of the CameraPreview class and pass the CameraPreviewRect object to it. You must also, of course, specify the camera you want to use. In this tutorial, we'll use the rear camera only.

The camera preview will be placed beneath our HTML page, and will not be visible unless we make the background of our app transparent. The easiest way to do so is to add a CSS rule inside the src/app/app.scss file.

8. Take Pictures

While defining the layout of our page, we've already added a click handler to the button the user will press to take pictures. Let us now define the handler.

Taking a picture with the CameraPreview Ionic Native wrapper is as simple as calling the takePicture() method and specifying the desired resolution of the picture. For now, let's use 320 x 320 as the maximum dimensions of our picture.

It is worth noting that specifying large resolutions can lead to out-of-memory errors.

9. Apply Image Effects

The CameraPreview wrapper allows you to easily apply several common image effects, also called image filters, to your pictures in real time. We've already added a click handler to the button the user will press to apply the image effects. Therefore, all we need to do now is define it.

To keep our code simple, every time the user presses the button, let us pick a random effect from an array of effects, and apply it. You can use the JavaScript Math.random() function to pick a random effect, and the setColorEffect() method of the CameraPreview class to apply it.

You can run the app now and tap the FAB multiple times to see various image effects being applied to the camera preview window.

Camera preview with the mono effect

10. Move Pictures to External Storage

Our app places all the pictures it takes inside its application storage directory, which is a private data directory. If you prefer storing those pictures on external storage media, thus making them available to third-party photo gallery apps, you must manually move them. To do so, you can use the File Ionic Native wrapper.

As always, import the wrapper before using it. Additionally, declare cordova as an externally initialized global variable. It offers constants that let you easily refer to all the frequently used directories of the Android file system.

We should be moving the pictures to the external storage directory as soon as they are taken. Therefore, subscribe to the setOnPictureTakenHandler() method of the CameraPreview class. The method returns an array containing the absolute paths of the picture and its thumbnail. For now, we'll be moving the picture only.

Accordingly, add the following code towards the end of the initializePreview() method:

Inside the moveFileToExternalStorage() method, we can use the moveFile() method of the File class to actually move the picture. The moveFile() method expects source and destination directories and filenames as its arguments.

To determine the path of your application's external storage directory, use the cordova.file.externalApplicationStorageDirectory constant. Similarly, to determine the path of your application's private storage directory, use the cordova.file.applicationStorageDirectory constant.

Additionally, to extract the filename of the picture from its absolute path, you can simply use JavaScript's split() and pop() methods. I suggest you also display a toast after the move operation is complete.

Our camera app is now complete. You can view its pictures using any photo gallery app you have on your device.

Conclusion

In this tutorial, you learned how to use Ionic 2 and plugin wrappers available in Ionic Native to create a hybrid app that can take pictures, apply image effects to them, and store them on external storage media. Although we focused only on the Android platform today, you can be sure that our app will work, with minimal changes, on iOS devices too.

To learn more about Ionic 2, you can refer to its extensive documentation. Our check out our Ionic 2 course here on Envato Tuts+!

2017-02-16T10:11:10.258Z2017-02-16T10:11:10.258ZAshraff Hathibelagal

How to Create a Camera App With Ionic 2

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

As a prudent developer, you might be wary of creating hybrid applications that depend on Android's native APIs. A few years ago, I was too, what with Android having so many version-specific and device-specific quirks. Today, however, we can trust hybrid application development frameworks to handle most of those quirks transparently. Ionic 2, which builds on Apache Cordova, is one such framework.

Ionic 2 has wrappers for several popular Cordova plugins that allow you to easily make use of Android's native resources, such as cameras, hardware sensors, and the file system. In this tutorial, I'll show you how to use those wrappers alongside Ionic 2 UI components to create a simple camera app.

Prerequisites

To follow along, you'll need:

  • the latest version of the Android SDK
  • Node.js v6.7.0 or higher
  • a device or emulator running Android 4.4 or higher
  • a basic understanding of TypeScript and Angular 2

1. Install Cordova and Ionic

Both Ionic and Cordova are available as NPM modules, so the easiest way to install them is to use the npm command. Here's how you can install both of them globally:

Once the installation is complete, type in the following to make sure that the Ionic command-line interface, or CLI for short, is configured correctly.

The output of the above command should look like this:

2. Create a New Project

Ionic's CLI makes it very easy for you to create new Ionic 2 projects with all the required configuration files and boilerplate code. It also offers several starter templates to choose from. For now, let us simply create a project using the blank starter template.

At this point, you'll have a new directory called MyCameraApp. For the rest of this tutorial, we'll be working inside this directory.

3. Configure the Project

By default, an Ionic 2 project isn't configured to target any mobile platform. Here's how you add support for Android:

You must also manually point Ionic 2 to the location where you installed the Android SDK. If you are using Mac or Linux, use the export command to do so.

4. Install Ionic Plugins

Our camera app needs access to the device's camera and file system, both of which are native resources. If you're familiar with Cordova, you might be aware that hybrid applications usually interact with such resources through plugins. Although you can use a Cordova plugin directly in an Ionic 2 project, it is much easier to use its Ionic Native wrapper instead.

To access the camera, we'll use the cordova-plugin-camera-preview plugin. It allows us to not only take pictures, but also apply several image filters to them. Here's how you can add it to your project:

We'll, of course, have to save the pictures we take on external storage media, such as SD cards. To do so, we'll use the cordova-plugin-file plugin.

Lastly, in order to support Android devices running API level 23 or higher, we'll need the cordova.plugins.diagnostic plugin.

5. Define the Layout

Our app's user interface will be composed of the following components:

  • a camera preview window
  • a floating action button to take pictures
  • a floating action button to apply image filters

We'll be creating the camera preview window programmatically in a later step. For now, let's create an HTML layout containing just two floating action buttons.

Because our blank app already has a page, we'll be using it instead of creating a new one. To modify its layout, open src/pages/home/home.html. Empty its contents and add a new <ion-content> tag to it.

To create a floating action button, you can create an ordinary HTML button and add the ion-fab attribute to it. Additionally, by wrapping the <button> tag inside an <ion-fab> tag, you can position it.

A floating action button usually has an icon. By using the <ion-icon> tag, you can add any Ionicon to it.

Accordingly, add the following to your layout file:

As you can see in the above code, we've added click event handlers to both the buttons. We'll define them later.

6. Acquire Permissions

On devices running Android API level 23 or higher, you must explicitly ask the user for permissions to access the camera and file system during runtime. To do so in your hybrid app, you can use methods available in the Diagnostic Ionic Native wrapper.

Start by opening src/pages/home/home.ts and importing Diagnostic.

Inside the constructor of the HomePage class, add a call to a new checkPermissions() method. Additionally, add a ToastController object to the class using dependency injection. We'll be using it to display Ionic 2 toasts, which are almost identical to native Android's snackbars.

After making the above changes, your code should look like this:

Inside the checkPermissions() method, use the isCameraAuthorized() method of the Diagnostic class to check if the app already has permissions to access both the camera and the file system. Because the method returns a Promise object, you must use a callback to handle its result.

If the app doesn't have the required permissions, you can use the requestCameraAuthorization() method to ask for them.

If the user does grant the permissions, or if our app already has them, we can go ahead and initialize the camera preview inside initializePreview(), a method we'll be creating in the next step. Otherwise, let's simply display a toast containing an error message using the create() and present() methods of the ToastController class.

Accordingly, add the following code inside the checkPermissions() method:

Here's what the camera authorization dialog looks like on a device running Android Marshmallow:

Camera authorization dialog

7. Create Camera Preview

The CameraPreview Ionic Native wrapper lets you display a live camera preview inside your hybrid app. However, because the preview uses an Android fragment instead of an HTML element, adding it to our page is slightly complicated.

Before you start, make sure you import both CameraPreview and CameraPreviewRect.

Using a CameraPreviewRect object, you can specify the position and size of the camera preview. For now, let's make it fill the device's screen completely.

At this point, we have everything we need to start the camera preview. Therefore, call the startCamera() method of the CameraPreview class and pass the CameraPreviewRect object to it. You must also, of course, specify the camera you want to use. In this tutorial, we'll use the rear camera only.

The camera preview will be placed beneath our HTML page, and will not be visible unless we make the background of our app transparent. The easiest way to do so is to add a CSS rule inside the src/app/app.scss file.

8. Take Pictures

While defining the layout of our page, we've already added a click handler to the button the user will press to take pictures. Let us now define the handler.

Taking a picture with the CameraPreview Ionic Native wrapper is as simple as calling the takePicture() method and specifying the desired resolution of the picture. For now, let's use 320 x 320 as the maximum dimensions of our picture.

It is worth noting that specifying large resolutions can lead to out-of-memory errors.

9. Apply Image Effects

The CameraPreview wrapper allows you to easily apply several common image effects, also called image filters, to your pictures in real time. We've already added a click handler to the button the user will press to apply the image effects. Therefore, all we need to do now is define it.

To keep our code simple, every time the user presses the button, let us pick a random effect from an array of effects, and apply it. You can use the JavaScript Math.random() function to pick a random effect, and the setColorEffect() method of the CameraPreview class to apply it.

You can run the app now and tap the FAB multiple times to see various image effects being applied to the camera preview window.

Camera preview with the mono effect

10. Move Pictures to External Storage

Our app places all the pictures it takes inside its application storage directory, which is a private data directory. If you prefer storing those pictures on external storage media, thus making them available to third-party photo gallery apps, you must manually move them. To do so, you can use the File Ionic Native wrapper.

As always, import the wrapper before using it. Additionally, declare cordova as an externally initialized global variable. It offers constants that let you easily refer to all the frequently used directories of the Android file system.

We should be moving the pictures to the external storage directory as soon as they are taken. Therefore, subscribe to the setOnPictureTakenHandler() method of the CameraPreview class. The method returns an array containing the absolute paths of the picture and its thumbnail. For now, we'll be moving the picture only.

Accordingly, add the following code towards the end of the initializePreview() method:

Inside the moveFileToExternalStorage() method, we can use the moveFile() method of the File class to actually move the picture. The moveFile() method expects source and destination directories and filenames as its arguments.

To determine the path of your application's external storage directory, use the cordova.file.externalApplicationStorageDirectory constant. Similarly, to determine the path of your application's private storage directory, use the cordova.file.applicationStorageDirectory constant.

Additionally, to extract the filename of the picture from its absolute path, you can simply use JavaScript's split() and pop() methods. I suggest you also display a toast after the move operation is complete.

Our camera app is now complete. You can view its pictures using any photo gallery app you have on your device.

Conclusion

In this tutorial, you learned how to use Ionic 2 and plugin wrappers available in Ionic Native to create a hybrid app that can take pictures, apply image effects to them, and store them on external storage media. Although we focused only on the Android platform today, you can be sure that our app will work, with minimal changes, on iOS devices too.

To learn more about Ionic 2, you can refer to its extensive documentation. Our check out our Ionic 2 course here on Envato Tuts+!

2017-02-16T10:11:10.258Z2017-02-16T10:11:10.258ZAshraff Hathibelagal

Swift From Scratch: Introduction

$
0
0


In 2014, Apple took the developer community by surprise with the introduction of Swift, a brand new programming language. Swift has come a long way, and it is hard to believe that the language is celebrating its third anniversary this year. A few months ago, Apple released Swift 3, a major milestone for the language. In this series, I'll teach you the fundamentals of Swift 3.

Swift feels familiar if you have used Objective-C to develop iOS or macOS applications, but there are a number of important differences. I'll kick this series off by showing you in what ways Swift differs from Objective-C and why those differences are a good thing. Let's get started.

1. Prerequisites

Programming

Throughout this series, I make references to Objective-C and compare the Swift programming language with Objective-C. However, to follow along, there is no need to be familiar with Objective-C.

That said, it is important that you have experience with a programming language. While this series focuses on Swift, it doesn't cover the basics of programming. I expect you to be familiar with variables, constants, functions, control flow, and object-oriented programming.

If you are familiar with Objective-C, Java, Ruby, PHP, or JavaScript, then you won't have problems understanding the concepts explained in this series. As a matter of fact, you will notice that Swift shares similarities with a number of popular programming languages, including Objective-C.

Xcode

Swift 3 is only supported by Xcode 8, and you need to install the latest version of Apple's IDE (Integrated Development Environment) to follow along. You can download Xcode either from the App Store or Apple's Developer Center.

2. Swift

Compared to Objective-C or Java, Swift is an expressive, succinct language that often reminds me of Ruby and JavaScript. Even though the creator of Swift, Chris Lattner, took inspiration from other languages, Swift is very much a language that stands on its own feet.

As you may know, Objective-C is a strict superset of C. Swift, however, is not. While Swift uses curly braces and shares several keywords with the C programming language, it is not compatible with C.

Swift is a modern programming language that feels intuitive, especially if you are used to Java or C-based programming languages like Objective-C. During the development and design of Swift, Chris Lattner focused on a number of key characteristics that ended up defining the language.

Safety

Safety is one of Swift's foundations. In this series, you quickly learn that Swift is very different from Objective-C in terms of safety, and this directly affects the code you write. If you have worked with Objective-C, this takes some getting used to.

LLVM

Chris Lattner also designed the LLVM (Low Level Virtual Machine) compiler, and it shouldn't be a surprise that Swift is built with the LLVM compiler. The result is speed, power, and reliability. Swift is significantly faster than Objective-C in most scenarios. Read this article by Jesse Squires if you are interested in the nitty-gritty details.

Type Inference

Type safety is one of Swift's key features. Swift inspects your code at compile time and warns you about type mismatches. This means that you can catch errors early, avoiding a range of common bugs.

Luckily, Swift helps you with this. Swift is often smart enough to infer the type of variables and constants, which means that you don't have to explicitly declare the type of each variable or constant. In the following code snippet, we declare a variable a and assign it the value "this is a string". Swift is smart enough to infer that a is of type String.

This is a trivial example, but you'll find out that Swift can also handle more complex scenarios.

Variables and Constants

Constants are useful in C and Objective-C, but most developers use them sparingly. In Swift, constants are just as important and common as variables. If the value of a variable doesn't change, then that variable should be a constant. Variables are declared using the var keyword. Constants are declared using the let keyword.

Not only does this improve the intent, it also improves safety by ensuring that the variable's value is not accidentally changed. We take a closer look at variables and constants later in this tutorial.

Semicolons

In Swift, semicolons are not required. You can use semicolons, for example, to write multiple statements on the same line, but they are optional. Take a look at the following example to better understand the use of semicolons in Swift.

We are only scratching the surface. You'll learn about many more features and concepts throughout this series. Instead of overloading you with more theory, I suggest you get your feet wet by writing some code. This brings us to one of the best features of Swift and Xcode: playgrounds.

3. Playgrounds

Apple introduced playgrounds in Xcode 6. Playgrounds are the perfect tool for learning Swift. A playground is an interactive environment in which you can write Swift and immediately see the result. Not only does it make learning Swift more fun, it is much faster and more intuitive than setting up a project in Xcode.

As a matter of fact, it is so easy that you might as well jump in and create your first playground. Open Xcode 8 and select New > Playground... from the File menu. Name the playground and set Platform to iOS.

Create a New Playground

Tell Xcode where you would like to save the playground and click Create. Instead of creating a project with a bunch of files and folders, a playground is nothing more than a file with a .playground extension. A playground is more than a file under the hood, but that isn't something we need to worry about for now.

The user interface you are presented with couldn't be simpler. On the left, you see a code editor with a comment at the top, an import statement for importing the UIKit framework, and one line of code that shouldn't be too difficult to understand. On the right, you see the output or results generated by the code on the left.

The User Interface of a Playground in Xcode

Let's take a moment to understand the code in your new playground. The first line should look familiar if you have worked with Objective-C, PHP, or JavaScript. Comments in Swift start with two forward slashes or, in the case of multiline comments, start with /* and end with */.

Because we selected iOS as the platform when we created the playground, Xcode added an import statement for the UIKit framework. This gives us access to every symbol defined in the UIKit framework.

The third line looks familiar, but there are a few details that need clarifying. We declare a variable str and assign it a string. This line of code is easy to understand, but note that the variable's name is preceded by the var keyword instead of the variable's type as you would expect in Objective-C. The same statement in Objective-C would look something like this.

In Objective-C, we would replace the var keyword with the variable's type, prefix the string with an @ symbol, and end the statement with a semicolon. It is important to understand that the var keyword doesn't replace the type specifier in Objective-C. It is nothing more than a keyword to indicate that str is a variable, not a constant. 

Let me explain this in more detail. Add the following line of code to the playground.

The let keyword tells the compiler that hello is a constant, not a variable. Both str and hello are of type String, but str is a variable and hello is a constant. The difference is simple to understand if we add two more lines of code.

Assigning a new value to str doesn't pose a problem. Assigning a new value to hello, however, results in an error. Xcode tells us that it cannot assign a new value to hello, because hello is a constant, not a variable. This is another key feature of Swift, which will take some getting used to.

The value of a constant cannot be changed

The idea is simple. If the value of a variable is not going to change, then it should be a constant instead of a variable. While this may seem like a semantic detail, I guarantee that it makes your code safer and less prone to errors. Be prepared, because you are going to see the let keyword a lot in this series.

We use playgrounds extensively throughout this series because it is a great way to learn the language. There are a few other powerful playground features that we haven't covered yet, but we first need to understand the basics of the Swift language before we can benefit from those.

Conclusion

I still have to meet a developer who doesn't like Swift, and that's saying something. Swift has a number of concepts that require some getting used to, but I am confident that you too will end up enjoying Swift and appreciating its power, elegance, and concision. In the next installment of this series, we'll start exploring the basics of Swift.

If you want to get up and running with the Swift language quickly, check out our course on creating iOS apps with Swift.

Or check out some of our other tutorials and courses on Swift and iOS development!

2017-02-17T17:35:50.326Z2017-02-17T17:35:50.326ZBart Jacobs

Swift From Scratch: Introduction

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


In 2014, Apple took the developer community by surprise with the introduction of Swift, a brand new programming language. Swift has come a long way, and it is hard to believe that the language is celebrating its third anniversary this year. A few months ago, Apple released Swift 3, a major milestone for the language. In this series, I'll teach you the fundamentals of Swift 3.

Swift feels familiar if you have used Objective-C to develop iOS or macOS applications, but there are a number of important differences. I'll kick this series off by showing you in what ways Swift differs from Objective-C and why those differences are a good thing. Let's get started.

1. Prerequisites

Programming

Throughout this series, I make references to Objective-C and compare the Swift programming language with Objective-C. However, to follow along, there is no need to be familiar with Objective-C.

That said, it is important that you have experience with a programming language. While this series focuses on Swift, it doesn't cover the basics of programming. I expect you to be familiar with variables, constants, functions, control flow, and object-oriented programming.

If you are familiar with Objective-C, Java, Ruby, PHP, or JavaScript, then you won't have problems understanding the concepts explained in this series. As a matter of fact, you will notice that Swift shares similarities with a number of popular programming languages, including Objective-C.

Xcode

Swift 3 is only supported by Xcode 8, and you need to install the latest version of Apple's IDE (Integrated Development Environment) to follow along. You can download Xcode either from the App Store or Apple's Developer Center.

2. Swift

Compared to Objective-C or Java, Swift is an expressive, succinct language that often reminds me of Ruby and JavaScript. Even though the creator of Swift, Chris Lattner, took inspiration from other languages, Swift is very much a language that stands on its own feet.

As you may know, Objective-C is a strict superset of C. Swift, however, is not. While Swift uses curly braces and shares several keywords with the C programming language, it is not compatible with C.

Swift is a modern programming language that feels intuitive, especially if you are used to Java or C-based programming languages like Objective-C. During the development and design of Swift, Chris Lattner focused on a number of key characteristics that ended up defining the language.

Safety

Safety is one of Swift's foundations. In this series, you quickly learn that Swift is very different from Objective-C in terms of safety, and this directly affects the code you write. If you have worked with Objective-C, this takes some getting used to.

LLVM

Chris Lattner also designed the LLVM (Low Level Virtual Machine) compiler, and it shouldn't be a surprise that Swift is built with the LLVM compiler. The result is speed, power, and reliability. Swift is significantly faster than Objective-C in most scenarios. Read this article by Jesse Squires if you are interested in the nitty-gritty details.

Type Inference

Type safety is one of Swift's key features. Swift inspects your code at compile time and warns you about type mismatches. This means that you can catch errors early, avoiding a range of common bugs.

Luckily, Swift helps you with this. Swift is often smart enough to infer the type of variables and constants, which means that you don't have to explicitly declare the type of each variable or constant. In the following code snippet, we declare a variable a and assign it the value "this is a string". Swift is smart enough to infer that a is of type String.

This is a trivial example, but you'll find out that Swift can also handle more complex scenarios.

Variables and Constants

Constants are useful in C and Objective-C, but most developers use them sparingly. In Swift, constants are just as important and common as variables. If the value of a variable doesn't change, then that variable should be a constant. Variables are declared using the var keyword. Constants are declared using the let keyword.

Not only does this improve the intent, it also improves safety by ensuring that the variable's value is not accidentally changed. We take a closer look at variables and constants later in this tutorial.

Semicolons

In Swift, semicolons are not required. You can use semicolons, for example, to write multiple statements on the same line, but they are optional. Take a look at the following example to better understand the use of semicolons in Swift.

We are only scratching the surface. You'll learn about many more features and concepts throughout this series. Instead of overloading you with more theory, I suggest you get your feet wet by writing some code. This brings us to one of the best features of Swift and Xcode: playgrounds.

3. Playgrounds

Apple introduced playgrounds in Xcode 6. Playgrounds are the perfect tool for learning Swift. A playground is an interactive environment in which you can write Swift and immediately see the result. Not only does it make learning Swift more fun, it is much faster and more intuitive than setting up a project in Xcode.

As a matter of fact, it is so easy that you might as well jump in and create your first playground. Open Xcode 8 and select New > Playground... from the File menu. Name the playground and set Platform to iOS.

Create a New Playground

Tell Xcode where you would like to save the playground and click Create. Instead of creating a project with a bunch of files and folders, a playground is nothing more than a file with a .playground extension. A playground is more than a file under the hood, but that isn't something we need to worry about for now.

The user interface you are presented with couldn't be simpler. On the left, you see a code editor with a comment at the top, an import statement for importing the UIKit framework, and one line of code that shouldn't be too difficult to understand. On the right, you see the output or results generated by the code on the left.

The User Interface of a Playground in Xcode

Let's take a moment to understand the code in your new playground. The first line should look familiar if you have worked with Objective-C, PHP, or JavaScript. Comments in Swift start with two forward slashes or, in the case of multiline comments, start with /* and end with */.

Because we selected iOS as the platform when we created the playground, Xcode added an import statement for the UIKit framework. This gives us access to every symbol defined in the UIKit framework.

The third line looks familiar, but there are a few details that need clarifying. We declare a variable str and assign it a string. This line of code is easy to understand, but note that the variable's name is preceded by the var keyword instead of the variable's type as you would expect in Objective-C. The same statement in Objective-C would look something like this.

In Objective-C, we would replace the var keyword with the variable's type, prefix the string with an @ symbol, and end the statement with a semicolon. It is important to understand that the var keyword doesn't replace the type specifier in Objective-C. It is nothing more than a keyword to indicate that str is a variable, not a constant. 

Let me explain this in more detail. Add the following line of code to the playground.

The let keyword tells the compiler that hello is a constant, not a variable. Both str and hello are of type String, but str is a variable and hello is a constant. The difference is simple to understand if we add two more lines of code.

Assigning a new value to str doesn't pose a problem. Assigning a new value to hello, however, results in an error. Xcode tells us that it cannot assign a new value to hello, because hello is a constant, not a variable. This is another key feature of Swift, which will take some getting used to.

The value of a constant cannot be changed

The idea is simple. If the value of a variable is not going to change, then it should be a constant instead of a variable. While this may seem like a semantic detail, I guarantee that it makes your code safer and less prone to errors. Be prepared, because you are going to see the let keyword a lot in this series.

We use playgrounds extensively throughout this series because it is a great way to learn the language. There are a few other powerful playground features that we haven't covered yet, but we first need to understand the basics of the Swift language before we can benefit from those.

Conclusion

I still have to meet a developer who doesn't like Swift, and that's saying something. Swift has a number of concepts that require some getting used to, but I am confident that you too will end up enjoying Swift and appreciating its power, elegance, and concision. In the next installment of this series, we'll start exploring the basics of Swift.

If you want to get up and running with the Swift language quickly, check out our course on creating iOS apps with Swift.

Or check out some of our other tutorials and courses on Swift and iOS development!

2017-01-20T15:26:04.000Z2017-01-20T15:26:04.000ZBart Jacobs

Swift From Scratch: Collections and Tuples

$
0
0

In the previous article, you learned about variables, constants, and some of the common data types, such as integers, floats, and strings. In this article, we zoom in on collections. Swift's standard library defines three collection types: sets, arrays, and dictionaries. Let's start with arrays.

1. Arrays

If you're familiar with Objective-C, JavaScript, or PHP, then it won't be difficult to understand arrays. An array is an ordered, zero-indexed collection of values. But there are a few important differences between arrays for Swift and other programming languages.

Type

The first important difference compared to arrays in Objective-C is that the values stored in an array are always of the same type. At first, this may seem like a significant limitation, but it actually isn't. In fact, this limitation has an important advantage. We know exactly what type we get back when we ask the array for one of its values.

Another key difference is the type of values an array can store. In Objective-C, an array can only store values of a class type. Swift doesn't have this limitation. An array in Swift can store strings, integers, floats, and class instances. How this works and why this is possible in Swift will become clear later in this series when we cover classes and structures.

Declaration

While there are several ways to create an array, you need to keep in mind that Swift needs to know what type of values you plan to store in the array. Create a new playground in Xcode, like we did in the previous article, and add the following lines to your playground.

The first and second lines mean the same thing. The second line is just shorthand. The square brackets wrapping the String keyword tell Swift that we're declaring an array that can only contain String objects.

You could read the first line of code as: "We declare a variable named array1of type Array that can only contain String objects." The colon signifies of type.

The third line shows us how to initialize an array using an array literal. Array literals look very similar to array literals in Objective-C. The main difference is the absence of the @ symbol preceding the square brackets and the string literals.

There's also a fancy way to initialize an array with a predefined number of default values. The syntax may be confusing at first, but take a moment to let it sink in.

The resulting array contains five strings, with each string being equal to "Test". To better understand the above initialization, take a look at the following two lines of code in which we initialize an empty array of strings.

Don't worry if you're still confused. We'll explore the syntax in more detail once we start dealing with classes and functions. In this article, we're only focusing on collections.

Mutability

One aspect of Swift that you'll quickly come to appreciate is how to declare mutable collections. The above code snippet, for example, declares three mutable arrays. A mutable array is defined by using the var keyword. It's that simple.

If you don't want an array to be mutable, then use the let keyword instead. Swift aims to be intuitive and easy to use, and its implementation of mutability is a perfect example of that goal.

Getting and Setting Values

To access the values stored in an array, we use the same subscript syntax as in Objective-C. In the following example, we ask array3 for its second element, the string "Pear".

Replacing the value stored at index 1 is as simple as assigning a new value using the same subscript syntax. In the following example, we replace "Pear" at index 1 with "Peach".

This is only possible because the array is mutable, that is, we used the var keyword to declare the array. Mutating a constant array isn't possible. There are more advanced techniques for manipulating the contents of an array, but the underlying concept is the same.

Merging two arrays is as simple as adding them together. In the following example, we declare and merge two immutable arrays. Note that the resulting array, c, doesn't need to be mutable for this to work.

However, it is key that the values stored in a and b are of the same type. The reason should be obvious by now. As I mentioned earlier, the values stored in an array need to be of the same type. The following example results in an error.

To append an array to a mutable array, we use the += operator. Note that the operand on the right is an array. This operation wouldn't work if we removed the square brackets surrounding 4.

Operations

Arrays are objects on which you can perform a wide range of operations. Arrays expose a number of functions or methods. To invoke a method on an object, you use the dot notation. Add the following line to your playground to add an item to array3.

Let's see how many items array3 contains by inspecting the value of its count property. This outputs 4 to the results pane.

It's also possible to insert an item at a specific index by invoking the array's insert(_:at:) method as shown below. The insert(_:at:) method accepts more than one parameter, and the syntax may look a bit odd at first.

Like Objective-C, Swift supports named parameters to improve readability. The result is that code is easier to read and understand, and functions or methods don't need much explaining in terms of what they do. It is clear, for example, that the insert(_:at:) method inserts an element at index 2.

While Swift is more concise and less verbose than Objective-C, it supports named parameters. If you're coming from PHP, Ruby, or JavaScript, then this is certainly something that takes some getting used to.

Convenience Methods

What I really enjoy about Swift are the Ruby-like convenience properties and methods of Swift's standard library. An array, for example, has an isEmpty property that tells you if the array contains any elements. This is nothing more than shorthand for checking the array's count property. The result, however, is code that is more concise and easier to read.

2. Dictionaries

Dictionaries behave very similarly to dictionaries in Objective-C. A dictionary stores an unordered collection of values. Each value in the dictionary is associated with a key. In other words, a dictionary stores a number of key/value pairs.

Type

As with arrays, the keys and values stored in a dictionary need to be of the same type. This means that if you ask a dictionary for the value of a particular key, you know what type the dictionary will return.

Declaration

Declaring a dictionary is similar to declaring an array. The difference is that you need to specify the type for both keys and values. The following example shows three ways to declare a dictionary.

The second line is shorthand for the first line. The keys of these dictionaries need to be of type String while the values are expected to be of type Int. The var keyword indicates that the dictionaries are mutable.

You could read the first line of code as: "We declare a variable named dictionary1 of typeDictionary that can only contain keys of type String and values of type Int."

The third line illustrates how we can initialize a dictionary using a dictionary literal. This is similar to the syntax we use in Objective-C, but note that the curly braces are replaced by square brackets and the literal isn't prefixed with an @ symbol.

Getting and Setting Values

Accessing values is similar to accessing values of an array. The only difference is that you use the key instead of the index of the value you need to access. The following example illustrates this.

You'll notice that Xcode tells us that the value of value isn't 3, but Optional(3). What does this mean? Swift uses optionals to wrap values that can be one of two things, a value or nil. Don't worry about optionals at this point. We're going to focus on optionals in the next article of this series. Let me just tell you that optionals are another key concept of the Swift programming language.

It's interesting to point out that the syntax to access a value of a dictionary is identical to that of arrays if the keys of the dictionary are of type Int. Take a look at the following example to see what I mean.

Operations

As with arrays, the Swift standard library defines a wide range of operations you can perform on dictionaries. You can ask a dictionary for its number of key/value pairs through its count property. Removing a key/value pair is easy and intuitive, as the next example illustrates. Of course, this is only possible if the dictionary is mutable.

When you start learning Swift, you'll might run into code snippets that look odd or confusing. Take a look at the following line, in which we first declare a dictionary and then remove its key/value pairs.

You have to admit that the last line looks a bit odd. Because Swift knows the types of the keys and values that can be stored in dictionary, emptying the dictionary is as simple as assigning an empty dictionary to it.

There's no need to specify the types for the keys and values in this case, because we already did when we declared the dictionary in the first line. This points out another important detail, that is, the type of values you can store in arrays and dictionaries cannot change once the collection is declared.

3. Sets

Sets are very similar to arrays in that they store a collection of values of the same type. But there are several important differences. The elements stored in a set are unordered, and each item can only appear once in a set.

Declaration

Working with sets is a bit different from working with arrays. Take a look at the next examples in which we declare three sets. The set1 variable is of type Set<String>, a set that can only contain values of type String.

The set2 variable is an empty set, and we use an array literal in the third example to create and populate a mutable set that contains three values. Thanks to Swift's type inference, we can omit the type of the set.

Manipulating Sets

Working with sets is similar to working with arrays. We can ask for the number of elements stored in a set by inspecting the set's count property.

Inserting an element is easy. Because the elements of a set are unordered, we don't need to specify the location of the new element.

And the same applies to removing an element from a set.

You can also ask a set if it contains a particular element.

Arrays or Sets

I often refer to sets as lightweight versions of arrays. If the order of the elements is not important or you want to make sure each element can only appear once in a collection, then sets are the way to go.

4. Tuples

You are going to love tuples. Tuples aren't collections, but like collections, they also group multiple values. Similar to arrays and dictionaries, tuples can contain values of any type. The key difference, however, is that the values stored in a tuple don't need to be of the same type. Let's look at an example to explain this in more detail.

The first example declares a tuple named currency that is of type (String, Int). The second tuple, time, contains a Date instance and a string literal. The values stored in email are both of type String, which means email is of type (String, String).

Accessing Values

Indexes

To access a value stored in a tuple, you use the index that corresponds with the value you're interested in.

Xcode shows us the indexes of each value stored in a tuple in the results pane of the playground on the right.

Tuples in a Playground

Names

To improve readability, you can name the values stored in a tuple. The result is that you can access the values of the tuple through their names instead of their indexes. Declaring a tuple is slightly different in that case.

Decomposition

There's a second, more elegant way to work with the values stored in a tuple. Take a look at the following example in which we decompose the contents of currency.

The value of currency at index 0 is stored in currencyName, and the value at index 1 is stored in currencyRate. There's no need to specify the type for currencyName and currencyRate since Swift infers the type from the values stored in currency. In other words, currencyName is of type String, and currencyRate is of type Float.

If you're only interested in specific values of a tuple, you can use an underscore to tell Swift which values you're not interested in.

Conclusion

Arrays and dictionaries are fundamental components of almost every programming language, and Swift is no different. While collections behave a little differently in Swift, it doesn't take long to become familiar with Swift's collection types if you've worked with arrays and dictionaries in other programming languages. In the next tutorial, we explore optionals and control flow.

If you want to get up and running with the Swift language quickly, check out our course on creating iOS apps with Swift.

Or check out some of our other tutorials and courses on Swift and iOS development!

2017-02-20T15:24:51.588Z2017-02-20T15:24:51.588ZBart Jacobs

Swift From Scratch: Collections and Tuples

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

In the previous article, you learned about variables, constants, and some of the common data types, such as integers, floats, and strings. In this article, we zoom in on collections. Swift's standard library defines three collection types: sets, arrays, and dictionaries. Let's start with arrays.

1. Arrays

If you're familiar with Objective-C, JavaScript, or PHP, then it won't be difficult to understand arrays. An array is an ordered, zero-indexed collection of values. But there are a few important differences between arrays for Swift and other programming languages.

Type

The first important difference compared to arrays in Objective-C is that the values stored in an array are always of the same type. At first, this may seem like a significant limitation, but it actually isn't. In fact, this limitation has an important advantage. We know exactly what type we get back when we ask the array for one of its values.

Another key difference is the type of values an array can store. In Objective-C, an array can only store values of a class type. Swift doesn't have this limitation. An array in Swift can store strings, integers, floats, and class instances. How this works and why this is possible in Swift will become clear later in this series when we cover classes and structures.

Declaration

While there are several ways to create an array, you need to keep in mind that Swift needs to know what type of values you plan to store in the array. Create a new playground in Xcode, like we did in the previous article, and add the following lines to your playground.

The first and second lines mean the same thing. The second line is just shorthand. The square brackets wrapping the String keyword tell Swift that we're declaring an array that can only contain String objects.

You could read the first line of code as: "We declare a variable named array1of type Array that can only contain String objects." The colon signifies of type.

The third line shows us how to initialize an array using an array literal. Array literals look very similar to array literals in Objective-C. The main difference is the absence of the @ symbol preceding the square brackets and the string literals.

There's also a fancy way to initialize an array with a predefined number of default values. The syntax may be confusing at first, but take a moment to let it sink in.

The resulting array contains five strings, with each string being equal to "Test". To better understand the above initialization, take a look at the following two lines of code in which we initialize an empty array of strings.

Don't worry if you're still confused. We'll explore the syntax in more detail once we start dealing with classes and functions. In this article, we're only focusing on collections.

Mutability

One aspect of Swift that you'll quickly come to appreciate is how to declare mutable collections. The above code snippet, for example, declares three mutable arrays. A mutable array is defined by using the var keyword. It's that simple.

If you don't want an array to be mutable, then use the let keyword instead. Swift aims to be intuitive and easy to use, and its implementation of mutability is a perfect example of that goal.

Getting and Setting Values

To access the values stored in an array, we use the same subscript syntax as in Objective-C. In the following example, we ask array3 for its second element, the string "Pear".

Replacing the value stored at index 1 is as simple as assigning a new value using the same subscript syntax. In the following example, we replace "Pear" at index 1 with "Peach".

This is only possible because the array is mutable, that is, we used the var keyword to declare the array. Mutating a constant array isn't possible. There are more advanced techniques for manipulating the contents of an array, but the underlying concept is the same.

Merging two arrays is as simple as adding them together. In the following example, we declare and merge two immutable arrays. Note that the resulting array, c, doesn't need to be mutable for this to work.

However, it is key that the values stored in a and b are of the same type. The reason should be obvious by now. As I mentioned earlier, the values stored in an array need to be of the same type. The following example results in an error.

To append an array to a mutable array, we use the += operator. Note that the operand on the right is an array. This operation wouldn't work if we removed the square brackets surrounding 4.

Operations

Arrays are objects on which you can perform a wide range of operations. Arrays expose a number of functions or methods. To invoke a method on an object, you use the dot notation. Add the following line to your playground to add an item to array3.

Let's see how many items array3 contains by inspecting the value of its count property. This outputs 4 to the results pane.

It's also possible to insert an item at a specific index by invoking the array's insert(_:at:) method as shown below. The insert(_:at:) method accepts more than one parameter, and the syntax may look a bit odd at first.

Like Objective-C, Swift supports named parameters to improve readability. The result is that code is easier to read and understand, and functions or methods don't need much explaining in terms of what they do. It is clear, for example, that the insert(_:at:) method inserts an element at index 2.

While Swift is more concise and less verbose than Objective-C, it supports named parameters. If you're coming from PHP, Ruby, or JavaScript, then this is certainly something that takes some getting used to.

Convenience Methods

What I really enjoy about Swift are the Ruby-like convenience properties and methods of Swift's standard library. An array, for example, has an isEmpty property that tells you if the array contains any elements. This is nothing more than shorthand for checking the array's count property. The result, however, is code that is more concise and easier to read.

2. Dictionaries

Dictionaries behave very similarly to dictionaries in Objective-C. A dictionary stores an unordered collection of values. Each value in the dictionary is associated with a key. In other words, a dictionary stores a number of key/value pairs.

Type

As with arrays, the keys and values stored in a dictionary need to be of the same type. This means that if you ask a dictionary for the value of a particular key, you know what type the dictionary will return.

Declaration

Declaring a dictionary is similar to declaring an array. The difference is that you need to specify the type for both keys and values. The following example shows three ways to declare a dictionary.

The second line is shorthand for the first line. The keys of these dictionaries need to be of type String while the values are expected to be of type Int. The var keyword indicates that the dictionaries are mutable.

You could read the first line of code as: "We declare a variable named dictionary1 of typeDictionary that can only contain keys of type String and values of type Int."

The third line illustrates how we can initialize a dictionary using a dictionary literal. This is similar to the syntax we use in Objective-C, but note that the curly braces are replaced by square brackets and the literal isn't prefixed with an @ symbol.

Getting and Setting Values

Accessing values is similar to accessing values of an array. The only difference is that you use the key instead of the index of the value you need to access. The following example illustrates this.

You'll notice that Xcode tells us that the value of value isn't 3, but Optional(3). What does this mean? Swift uses optionals to wrap values that can be one of two things, a value or nil. Don't worry about optionals at this point. We're going to focus on optionals in the next article of this series. Let me just tell you that optionals are another key concept of the Swift programming language.

It's interesting to point out that the syntax to access a value of a dictionary is identical to that of arrays if the keys of the dictionary are of type Int. Take a look at the following example to see what I mean.

Operations

As with arrays, the Swift standard library defines a wide range of operations you can perform on dictionaries. You can ask a dictionary for its number of key/value pairs through its count property. Removing a key/value pair is easy and intuitive, as the next example illustrates. Of course, this is only possible if the dictionary is mutable.

When you start learning Swift, you'll might run into code snippets that look odd or confusing. Take a look at the following line, in which we first declare a dictionary and then remove its key/value pairs.

You have to admit that the last line looks a bit odd. Because Swift knows the types of the keys and values that can be stored in dictionary, emptying the dictionary is as simple as assigning an empty dictionary to it.

There's no need to specify the types for the keys and values in this case, because we already did when we declared the dictionary in the first line. This points out another important detail, that is, the type of values you can store in arrays and dictionaries cannot change once the collection is declared.

3. Sets

Sets are very similar to arrays in that they store a collection of values of the same type. But there are several important differences. The elements stored in a set are unordered, and each item can only appear once in a set.

Declaration

Working with sets is a bit different from working with arrays. Take a look at the next examples in which we declare three sets. The set1 variable is of type Set<String>, a set that can only contain values of type String.

The set2 variable is an empty set, and we use an array literal in the third example to create and populate a mutable set that contains three values. Thanks to Swift's type inference, we can omit the type of the set.

Manipulating Sets

Working with sets is similar to working with arrays. We can ask for the number of elements stored in a set by inspecting the set's count property.

Inserting an element is easy. Because the elements of a set are unordered, we don't need to specify the location of the new element.

And the same applies to removing an element from a set.

You can also ask a set if it contains a particular element.

Arrays or Sets

I often refer to sets as lightweight versions of arrays. If the order of the elements is not important or you want to make sure each element can only appear once in a collection, then sets are the way to go.

4. Tuples

You are going to love tuples. Tuples aren't collections, but like collections, they also group multiple values. Similar to arrays and dictionaries, tuples can contain values of any type. The key difference, however, is that the values stored in a tuple don't need to be of the same type. Let's look at an example to explain this in more detail.

The first example declares a tuple named currency that is of type (String, Int). The second tuple, time, contains a Date instance and a string literal. The values stored in email are both of type String, which means email is of type (String, String).

Accessing Values

Indexes

To access a value stored in a tuple, you use the index that corresponds with the value you're interested in.

Xcode shows us the indexes of each value stored in a tuple in the results pane of the playground on the right.

Tuples in a Playground

Names

To improve readability, you can name the values stored in a tuple. The result is that you can access the values of the tuple through their names instead of their indexes. Declaring a tuple is slightly different in that case.

Decomposition

There's a second, more elegant way to work with the values stored in a tuple. Take a look at the following example in which we decompose the contents of currency.

The value of currency at index 0 is stored in currencyName, and the value at index 1 is stored in currencyRate. There's no need to specify the type for currencyName and currencyRate since Swift infers the type from the values stored in currency. In other words, currencyName is of type String, and currencyRate is of type Float.

If you're only interested in specific values of a tuple, you can use an underscore to tell Swift which values you're not interested in.

Conclusion

Arrays and dictionaries are fundamental components of almost every programming language, and Swift is no different. While collections behave a little differently in Swift, it doesn't take long to become familiar with Swift's collection types if you've worked with arrays and dictionaries in other programming languages. In the next tutorial, we explore optionals and control flow.

If you want to get up and running with the Swift language quickly, check out our course on creating iOS apps with Swift.

Or check out some of our other tutorials and courses on Swift and iOS development!

2017-02-20T15:24:51.588Z2017-02-20T15:24:51.588ZBart Jacobs

Introduction to Ionic 2

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

In this article, we're going to take look at Ionic 2, the newest version of the Ionic cross-platform mobile app framework. For starters, we'll recap what Ionic is and what it's used for. Then we're going to dive into Ionic 2. I'll tell you what's new and how it differs from Ionic 1, and I'll help you decide whether you should use it on your next project or not. 

What Is Ionic?

Ionic is a framework for building hybrid apps using HTML, CSS, and JavaScript. It comes with a set of UI components and functions that you can use to create fully functional and attractive mobile apps. 

Ionic is built on the Cordova stack. You cannot create mobile apps with Ionic alone because it only handles the UI part. It needs to work with Angular, which handles the application logic, and Cordova, the cross-platform app framework which allows you to compile your app into an installable file and run it inside the web view of the mobile device. 

Apps built with Cordova and Ionic can run on both Android and iOS devices. You can also install Cordova plugins to provide native functionality such as accessing the camera and working with Bluetooth Low Energy devices.

For more on Cordova, check out some of our courses and tutorials here on Envato Tuts+.

Ionic is more than just a UI framework, though. The Ionic company also offers services that support the Ionic UI Framework, including the Ionic Creator, Ionic View, and Ionic Cloud

What's New in Ionic 2?

In this section, we'll be taking a look at some of the significant changes to Ionic in version 2, and also the new features and tools that were introduced in Ionic 2.

Browser Support

Ionic 1 was built with only hybrid mobile apps in mind. But Ionic 2 is built to support progressive web apps and Electron apps as well. This means that you can now build not only Ionic apps that run inside the Cordova environment but also progressive web apps, which use modern web features to deliver an app-like experience to users. 

You can also target Electron, a platform for building cross-platform desktop apps using HTML, CSS, and JavaScript. Electron is pretty much like Cordova but for desktop operating systems like Windows, Ubuntu, or macOS.

Angular 2 and TypeScript

Ionic 2 now uses Angular 2 for templating and application logic. This means that developers will have to learn the new Angular 2 syntax before they can become productive at creating Ionic 2 apps. Don't worry, though, because the concepts are still the same as they were in Angular 1. There are also resources such as ngMigrate which will help you convert your Angular 1 skills to Angular 2.

Aside from Angular 2, Ionic 2 also uses TypeScript. For those unfamiliar with it, TypeScript is a superset of JavaScript. This means that you can still use vanilla JavaScript syntax to write your apps. If you want to use the features that come with TypeScript, such as ES6 and ES7 syntax, static-typing, and intelligent code completion, then you can use the TypeScript-specific syntax. There are plugins that you can install on your favorite text-editor or IDE to reap the benefits of TypeScript's advanced code-completion features.

Syntax

As I mentioned, the template syntax in Ionic 2 has significantly changed, largely because of its transition to using Angular 2. You may even come to find that the new syntax is more simple and concise. Here are a few examples of Ionic 1 and Ionic 2 syntax side by side:

Listening to events:

Using a model:

Looping through an array and displaying each item:

Folder Structure

If you compare the folder structure of an Ionic 1 project and an Ionic 2 project, you'll notice that most of the folders that you're used to seeing in an Ionic 1 project are still there in Ionic 2. This is because the underlying platform hasn't really changed—Ionic 2 still uses Cordova. The only things that have changed are the parts that have to do with your source files. Here's a screenshot of the folder structure of an Ionic 1 app:

ionic 1 folder structure

And here's an app built with Ionic 2:

ionic 2 folder structure

If you look closer, you'll notice that there is now a src folder. That's where all your project's source files are, and every time you make changes to a file in that directory, the changed file gets compiled and copied over to the www/build directory. Previously, the source files were all in the www directory, and you didn't require an extra compilation step.

The directory structure is also more organized. If you check the src/pages directory, you can see that every page has its own folder, and inside each one are the HTML, CSS and JavaScript files for that specific page. 

Previously, in Ionic 1, you were just given an empty directory and had the freedom to structure your project however you wanted. But this came with the downside of not forcing you to do things the best way. You could get lazy and stick with a structure that lumped all the files together, which could make things difficult for larger teams working on complex apps.

Theming

Unlike the previous version of Ionic, which only had a single look and feel for all platforms, Ionic 2 now supports three modes: Material Design, iOS, and Windows. Now Ionic matches the look and feel of the platform it's deployed on. So if your app is installed on Android, for example, it will use a styling and behavior similar to that of native Android apps. 

There is support for theming in Ionic, though at the time of writing of this article, it only ships with the default Light theme. If you want to tweak the theme, you can edit the src/theme/variables.scss file. 

Tooling

Ionic 2 also comes with new tools that will make it a joy to create mobile apps. I'll show you a few in this section.

Generators

Ionic 2 now provides a generator that allows you to create pages and services for your app:

This will create the following files in your app/pages folder:

Each file also has some boilerplate code in it:

This also serves as a guide for new developers so that they know the best practice for structuring their code. Here's the generated TypeScript code which handles the logic for the page above:

Error Reporting

Ionic 2 now comes with an error reporting tool for the front-end. This means that any time there's an error with your code, Ionic will open a modal window right in the app preview itself. This makes it really easy for developers to find out about errors as they happen within the app. 

Ionic App Scripts

Ionic App Scripts are a collection of build scripts for Ionic projects. Previously, Ionic used Gulp for handling its build process. 

Ionic 2 comes with a few of these scripts to make it easier to complete common development tasks. This includes things like transpiling the TypeScript code to ES5, serving the app for testing in the browser, or running it on a specific device.

You can find the default scripts in the project's package.json file:

New Components

Components are the UI building blocks in Ionic. Examples include buttons, cards, lists, and input fields. Lots of new components have been added to Ionic 2, and in this section we'll take a look at some of those. 

Slides

If you want your app to have a walk-through for first-time users, the Slides component makes it easy to create one. This component allows you to create page-based layouts which the user can swipe through to read all about your app. 

 

Action Sheet

Action sheets are menus that slide up from the bottom of the screen. An action sheet is shown on the top layer of the screen, so you either have to dismiss it by tapping on whitespace or to select an option from the menu. This is commonly used for confirmations such as when you delete a file on your iOS device. 

 

Segments

Segments are like tabs. They're used for grouping related content together in such a way that the user can only see the contents of the currently selected segment. Segments are commonly used with lists to filter for related items.

 

Toast

Toasts are the subtle version of alerts. They're commonly used to inform the user that something has happened which doesn't require any user action. They're often shown at the top or bottom of the page so as not to interfere with the content currently being shown. They also disappear after a specified number of seconds.

 

Toolbar

A Toolbar is used as a container for information and actions that are located in the header or footer of the app. For example, the title of the current screen, buttons, search fields and segments are often contained in a toolbar.

 

DateTime

The DateTime component is used to display a UI for picking dates and times. The UI is similar to the one generated when using the datetime-local element, the only difference being that this component comes with an easy-to-use JavaScript API. Previously, Ionic didn't have a component for working with dates and times. You either had to use the browser's native date picker or to install a plugin

 

Floating Action Buttons

Floating Action Buttons (FABs) are buttons that are fixed in a specific area of the screen. If you've ever used the Gmail app, the button for composing a new message is a floating action button. They're not limited to a single action because they can expand to show other floating buttons when tapped.

 

For more info regarding the new components, check out the documentation on components.

New Features and Improvements

Ionic 2 is also packed with new features and improvements. These are mostly due to its transition to Angular 2 and TypeScript.  

Web Animations API

One benefit from switching to Angular 2 is Angular's new animation system, built on top of the Web Animations API. Note that the Web Animations API isn't supported in all browsers—that's why you need to use Crosswalk to install a supported browser along with your app. The only downside of this is that it will make the install size bigger. Another option is to use a polyfill.

Performance

Apps created with Ionic 2 are snappier than those created with Ionic 1. Here's why:

  • Angular 2: DOM manipulation and JavaScript performance have improved a lot in Angular 2. You can check this table if you want to learn about the specifics. Another benefit that comes with Angular 2 is ahead-of-time compilation—templates are pre-compiled using a build tool instead of being compiled as the app runs in the browser. This makes the app initialize faster because there's no more need to compile the templates on the fly.
  • Native Scrolling: Ionic no longer uses JavaScript scrolling. Instead, it now uses native scrolling for supported WebViews. It is also now enabled on all platforms (as opposed to it being only supported on Android in Ionic 1). Aside from native scrolling, there's also the Virtual Scroll, which allows scrolling on a very large list of items with very little performance hit. These two changes add up to smoother scrolling performance.
  • Web Workers: Web Workers allow you to run scripts in the background, isolated from the thread that runs the web page. Ionic 2 implements web workers through their ion-img component. Using this component instead of the standard img element allows you to delegate the HTTP requests for fetching the images to a Web Worker. This makes the loading of images snappier, especially inside large lists. The ion-img component also handles lazy loading, which will only request and render the image as it becomes visible in the user's viewport.

Ionic Native

Ionic Native is the equivalent of ngCordova for Ionic 2. They both act as wrappers for the Cordova plugins to implement native functionality (e.g. Camera, GeoLocation). You can even use Ionic Native in your Ionic 1 app if you want. The main difference is that Ionic Native allows you to write your code using ES6 features and TypeScript syntax. This makes it easier to work with in Ionic 2 since it already uses TypeScript by default. Here's an example of how to implement the Cordova Camera plugin in ngCordova:

And here's how it's done using Ionic Native:

Documentation

The documentation has improved a lot. I especially like the fact that there are now different previews for each component on each platform. This gives developers a really good idea of how their app would look. All this without the developer writing a single line of code! 

Should You Use Ionic 2?

As of the time of writing of this article, Ionic 2 has been released. This means that it's ready to be used for production apps. Considering all the new features, tools and benefits that come with Angular 2 and TypeScript, the only thing that will stop you from using Ionic 2 is the status of your project.

If you're only just starting a new project, you can still use Ionic 1 if you and your teammates are only familiar with Angular 1 and your project needs to be completed as soon as possible. But if you've been given ample time for the project, you should consider using Ionic 2. There will be a bit of a learning curve, and you will also encounter some issues because it's not as battle-tested as Ionic 1, but it's all worth the effort because of Ionic 2's cool new features and improvements.

If you've already started out your current project with Ionic 1, you'll probably want to stick with Ionic 1 and avoid a major rewrite. Don't worry too much about support, improvements, and bug fixes for Ionic 1—Ionic developers have committed to supporting Ionic 1 for a long time. How long exactly isn't clear. At the very least, it's going to be supported for a couple of years after Ionic 2 stable version is released. But we also need to keep in mind that Ionic is an open-source project with over 200 contributors. So as long as people continue using it, we can always expect some form of support from the community.

Conclusion

That's it! In this article you've learned all about Ionic 2. Specifically, you've learned about the significant differences between Ionic 2 and its predecessor. We've also taken a look at the new features added to Ionic 2, and whether you should use it for your future projects or not. In a future tutorial, we're going to put this knowledge into practice by creating an Ionic 2 app. Stay tuned!

If you want to learn more about Ionic 2, be sure to check out the following resources:

And of course, we've got an in-depth Ionic 2 course that you can follow, right here on Envato Tuts+!

2017-02-22T21:08:21.093Z2017-02-22T21:08:21.093ZWernher-Bel Ancheta

Swift From Scratch: Optionals and Control Flow

$
0
0

In the previous articles, you learned some of the basic concepts of the Swift programming language. If you've programmed before, I'm sure you saw a few similarities with other programming languages, such as Ruby, JavaScript, and Objective-C.

In this article, we zoom in on control flow in Swift. Before we can discuss control flow in more detail, we need to take a look at a concept that is new to most of you, optionals. Optionals are another safety feature of Swift. At first, it may look like a hassle to use optionals, but you'll quickly learn that optionals will make your code much safer.

1. Optionals

We've already seen that a variable must be initialized before it can be used. Take a look at the following example to better understand what this means.

If you're used to working with strings in Objective-C, then you may be surprised that Swift shows you an error. Let's see what that error tells us.

An error

In many languages, variables have an initial default value. In Objective-C, for example, the string in the following code snippet is equal to nil.

However, the concept of nil differs in Swift and Objective-C. We'll discuss nil in more detail a bit later.

What Is an Optional?

Swift uses optionals to encapsulate an important concept, that is, a variable or constant has a value or it hasn't. It's that simple in Swift. To declare a variable or constant as optional, we append a question mark to the type of the variable or constant.

The variable str is no longer of type String. It is now of type optionalString. This is important to understand. The result or side effect is that we can no longer directly interact with the value of the str variable. The value is safely stored in the optional, and we need to ask the optional for the value it encapsulates.

Forced Unwrapping

One way to access the value of an optional is through forced unwrapping. We can access the value of the variable str by appending an ! to the variable's name.

It's important that you are sure that the optional contains a value when you force unwrap it. If the optional doesn't have a value and you force unwrap it, Swift will throw an error at you.

Forced unwrapping of an optional

Optional Binding

There is a safer way to access the value of an optional. We'll take a closer look at if statements in a few minutes, but the following example shows how we can safely access the value stored in the variable str, which is of type optional String.

We first check if the variable str is equal to nil before we print its contents. In this example, str doesn't have a value, which means it won't be forced unwrapped by accident.

There's a more elegant approach called optional binding. In the following example, we assign the value stored in the optional to a temporary constant, which is used in the if statement. The value of the optional str is bound to the constant strConst and used in the if statement. This approach also works for while statements.

What Is nil?

If you're coming from Objective-C, then you most certainly know what nil is. In Objective-C, nil is a pointer to an object that doesn't exist. Swift defines nil a bit differently, and it's important that you understand the difference.

In Swift, nil means the absence of a value, any value. While nil is only applicable to objects in Objective-C, in Swift nil can be used for any type. It's therefore important to understand that an optional isn't the equivalent of nil in Objective-C. These concepts are very different.

2. Control Flow

Swift offers a number of common constructs to control the flow of the code you write. If you have any experience programming, then you'll have no problems getting up to speed with Swift's control flow constructs, conditional if and switch statements, and for and while loops.

However, Swift wouldn't be Swift if its control flow didn't slightly differ from, for example, Objective-C's control flow constructs. While the details are important, I'm sure they won't hinder you from getting up to speed with Swift. Let's start with the most common conditional construct, the if statement.

if

Swift's if statements are very similar to those found in Objective-C. The main difference is that there's no need to wrap the condition in parentheses. Curly braces, however, are mandatory. The latter prevents developers from introducing common bugs that are related to writing if statements without curly braces. This is what an if statement looks like in Swift.

It should come as no surprise that Swift also defines an else clause. The code in the else clause is executed if the condition is equal to false. It's also possible to chain if statements as shown in the next example.

There is one important note to make, that is, the condition of an if statement needs to return true or false. This isn't true for if statements in Objective-C. Take a look at the following if statement in Objective-C.

If we were to port the above code snippet to Swift, we would run into an error. The error isn't very informative, but Swift does tell us that we need to ensure the result of the condition evaluates to true or false.

Control flow error

The correct way to translate the above Objective-C snippet to Swift is by making sure the condition of the if statement evaluates to true or false, as in the following snippet.

switch

Swift's switch statement is more powerful than its Objective-C equivalent. It's also safer, as you'll learn in a moment. While there are some differences, switch statements in Swift adhere to the same concept as those in other programming languages; a value is passed to the switch statement, and it is compared against possible matching patterns.

That's right, patterns. As I said, a switch statement in Swift has a few tricks up its sleeve. We'll take a look at those tricks in a moment. Let's talk about safety first.

Exhaustive

A switch statement in Swift needs to be exhaustive, meaning that every possible value of the type that's handed to the switch statement needs to be handled by the switch statement. As in Objective-C, this is easily solved by adding a default case, as shown in the following example.

Fallthrough

An important difference with Objective-C's implementation of switch statements is the lack of implicit fallthrough. The following example doesn't work in Swift for a few reasons.

The first case in which a is compared against 0 doesn't implicitly fall through to the second case in which a is compared against 1. If you add the above example to your playground, you'll notice that Swift throws an error at you. The error says that every case needs to include at least one executable statement.

Notice that the cases of the switch statement don't include break statements to break out of the switch statement. This isn't required in Swift since implicit fallthrough doesn't exist in Swift. This will eliminate a range of common bugs caused by unintentional fallthrough.

Patterns

The power of a switch statement in Swift lies in pattern matching. Take a look at the following example in which I've used ranges to compare the considered value against.

The ..< operator or half-open range operator defines a range from the first value to the second value, excluding the second value. The ... operator or closed range operator defines a range from the first value to the second value, including the second value. These operators are very useful in a wide range of situations.

You can also compare the considered value of a switch statement to tuples. Take a look at the following example to see how this works.

As you can see in the above example, it is possible that the value matches more than one case. When this happens, the first matching case is chosen. The above example also illustrates the use of the underscore. As we saw in the previous article, we can use an underscore, _, to tell Swift which values we're not interested in.

Value Binding

Value binding is also possible with switch statements, as the following example demonstrates. The second value of the tuple is temporarily bound to the constant description for use in the first and second case.

for

The for loop is the first loop construct we'll take a look at. It behaves very similarly to for loops in other languages. There used to be two flavors, the for loop and the for-in loop. As of Swift 3, however, C-style for loops are no longer available. The following snippet is not possible in Swift 3.

If you paste this snippet in a playground, you'll also notice that the ++ and -- operators are no longer available in Swift 3.

The for-in loop is ideal for looping over the contents of a range or collection. In the following example, we loop over the elements of an array.

We can also use for-in loops to loop over the key-value pairs of a dictionary. In the following example, we declare a dictionary and print its contents to the console. As we saw earlier in this series, the sequence of the key-value pairs is undefined since a dictionary is an unordered set of key-value pairs.

Each key-value pair of the dictionary is available in the for-in loop as a tuple of named constants. The for-in loop is also great in combination with ranges. I'm sure you agree that the below snippet is easy to read and understand thanks to the use of a closed range.

while

The while loop comes in two flavors, while and repeat-while. The main difference is that the set of statements of a repeat-while loop is always executed at least once, because the condition of the repeat-while is evaluated at the end of each iteration. The following example illustrates this difference.

The print statement of the while loop is never executed, while that of the repeat-while loop is executed once.

In many cases, for loops can be rewritten as while loops, and it's often up to the developer to determine which type of loop to use in a particular situation. The following for and while loops result in the same output.

Conclusion

There's much more to control flow in Swift than what we've covered in this article, but you now have a basic understanding to continue your journey into Swift. I hope this tutorial has shown you how Swift's control flow implementation is very similar to that of other programming languages—but with a twist.

In the rest of this series, we'll make more use of Swift's control flow constructs, and you'll gradually get a better understanding of the subtle differences between Swift and languages like Objective-C. In the next installment of this series, we'll start exploring functions.

If you want a quick way to get started building apps with the Swift language, we've got a course for that!

Or check out some of our other tutorials and courses on Swift and iOS development!

2017-02-23T19:18:19.000Z2017-02-23T19:18:19.000ZBart Jacobs

Swift From Scratch: Optionals and Control Flow

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

In the previous articles, you learned some of the basic concepts of the Swift programming language. If you've programmed before, I'm sure you saw a few similarities with other programming languages, such as Ruby, JavaScript, and Objective-C.

In this article, we zoom in on control flow in Swift. Before we can discuss control flow in more detail, we need to take a look at a concept that is new to most of you, optionals. Optionals are another safety feature of Swift. At first, it may look like a hassle to use optionals, but you'll quickly learn that optionals will make your code much safer.

1. Optionals

We've already seen that a variable must be initialized before it can be used. Take a look at the following example to better understand what this means.

If you're used to working with strings in Objective-C, then you may be surprised that Swift shows you an error. Let's see what that error tells us.

An error

In many languages, variables have an initial default value. In Objective-C, for example, the string in the following code snippet is equal to nil.

However, the concept of nil differs in Swift and Objective-C. We'll discuss nil in more detail a bit later.

What Is an Optional?

Swift uses optionals to encapsulate an important concept, that is, a variable or constant has a value or it hasn't. It's that simple in Swift. To declare a variable or constant as optional, we append a question mark to the type of the variable or constant.

The variable str is no longer of type String. It is now of type optionalString. This is important to understand. The result or side effect is that we can no longer directly interact with the value of the str variable. The value is safely stored in the optional, and we need to ask the optional for the value it encapsulates.

Forced Unwrapping

One way to access the value of an optional is through forced unwrapping. We can access the value of the variable str by appending an ! to the variable's name.

It's important that you are sure that the optional contains a value when you force unwrap it. If the optional doesn't have a value and you force unwrap it, Swift will throw an error at you.

Forced unwrapping of an optional

Optional Binding

There is a safer way to access the value of an optional. We'll take a closer look at if statements in a few minutes, but the following example shows how we can safely access the value stored in the variable str, which is of type optional String.

We first check if the variable str is equal to nil before we print its contents. In this example, str doesn't have a value, which means it won't be forced unwrapped by accident.

There's a more elegant approach called optional binding. In the following example, we assign the value stored in the optional to a temporary constant, which is used in the if statement. The value of the optional str is bound to the constant strConst and used in the if statement. This approach also works for while statements.

What Is nil?

If you're coming from Objective-C, then you most certainly know what nil is. In Objective-C, nil is a pointer to an object that doesn't exist. Swift defines nil a bit differently, and it's important that you understand the difference.

In Swift, nil means the absence of a value, any value. While nil is only applicable to objects in Objective-C, in Swift nil can be used for any type. It's therefore important to understand that an optional isn't the equivalent of nil in Objective-C. These concepts are very different.

2. Control Flow

Swift offers a number of common constructs to control the flow of the code you write. If you have any experience programming, then you'll have no problems getting up to speed with Swift's control flow constructs, conditional if and switch statements, and for and while loops.

However, Swift wouldn't be Swift if its control flow didn't slightly differ from, for example, Objective-C's control flow constructs. While the details are important, I'm sure they won't hinder you from getting up to speed with Swift. Let's start with the most common conditional construct, the if statement.

if

Swift's if statements are very similar to those found in Objective-C. The main difference is that there's no need to wrap the condition in parentheses. Curly braces, however, are mandatory. The latter prevents developers from introducing common bugs that are related to writing if statements without curly braces. This is what an if statement looks like in Swift.

It should come as no surprise that Swift also defines an else clause. The code in the else clause is executed if the condition is equal to false. It's also possible to chain if statements as shown in the next example.

There is one important note to make, that is, the condition of an if statement needs to return true or false. This isn't true for if statements in Objective-C. Take a look at the following if statement in Objective-C.

If we were to port the above code snippet to Swift, we would run into an error. The error isn't very informative, but Swift does tell us that we need to ensure the result of the condition evaluates to true or false.

Control flow error

The correct way to translate the above Objective-C snippet to Swift is by making sure the condition of the if statement evaluates to true or false, as in the following snippet.

switch

Swift's switch statement is more powerful than its Objective-C equivalent. It's also safer, as you'll learn in a moment. While there are some differences, switch statements in Swift adhere to the same concept as those in other programming languages; a value is passed to the switch statement, and it is compared against possible matching patterns.

That's right, patterns. As I said, a switch statement in Swift has a few tricks up its sleeve. We'll take a look at those tricks in a moment. Let's talk about safety first.

Exhaustive

A switch statement in Swift needs to be exhaustive, meaning that every possible value of the type that's handed to the switch statement needs to be handled by the switch statement. As in Objective-C, this is easily solved by adding a default case, as shown in the following example.

Fallthrough

An important difference with Objective-C's implementation of switch statements is the lack of implicit fallthrough. The following example doesn't work in Swift for a few reasons.

The first case in which a is compared against 0 doesn't implicitly fall through to the second case in which a is compared against 1. If you add the above example to your playground, you'll notice that Swift throws an error at you. The error says that every case needs to include at least one executable statement.

Notice that the cases of the switch statement don't include break statements to break out of the switch statement. This isn't required in Swift since implicit fallthrough doesn't exist in Swift. This will eliminate a range of common bugs caused by unintentional fallthrough.

Patterns

The power of a switch statement in Swift lies in pattern matching. Take a look at the following example in which I've used ranges to compare the considered value against.

The ..< operator or half-open range operator defines a range from the first value to the second value, excluding the second value. The ... operator or closed range operator defines a range from the first value to the second value, including the second value. These operators are very useful in a wide range of situations.

You can also compare the considered value of a switch statement to tuples. Take a look at the following example to see how this works.

As you can see in the above example, it is possible that the value matches more than one case. When this happens, the first matching case is chosen. The above example also illustrates the use of the underscore. As we saw in the previous article, we can use an underscore, _, to tell Swift which values we're not interested in.

Value Binding

Value binding is also possible with switch statements, as the following example demonstrates. The second value of the tuple is temporarily bound to the constant description for use in the first and second case.

for

The for loop is the first loop construct we'll take a look at. It behaves very similarly to for loops in other languages. There used to be two flavors, the for loop and the for-in loop. As of Swift 3, however, C-style for loops are no longer available. The following snippet is not possible in Swift 3.

If you paste this snippet in a playground, you'll also notice that the ++ and -- operators are no longer available in Swift 3.

The for-in loop is ideal for looping over the contents of a range or collection. In the following example, we loop over the elements of an array.

We can also use for-in loops to loop over the key-value pairs of a dictionary. In the following example, we declare a dictionary and print its contents to the console. As we saw earlier in this series, the sequence of the key-value pairs is undefined since a dictionary is an unordered set of key-value pairs.

Each key-value pair of the dictionary is available in the for-in loop as a tuple of named constants. The for-in loop is also great in combination with ranges. I'm sure you agree that the below snippet is easy to read and understand thanks to the use of a closed range.

while

The while loop comes in two flavors, while and repeat-while. The main difference is that the set of statements of a repeat-while loop is always executed at least once, because the condition of the repeat-while is evaluated at the end of each iteration. The following example illustrates this difference.

The print statement of the while loop is never executed, while that of the repeat-while loop is executed once.

In many cases, for loops can be rewritten as while loops, and it's often up to the developer to determine which type of loop to use in a particular situation. The following for and while loops result in the same output.

Conclusion

There's much more to control flow in Swift than what we've covered in this article, but you now have a basic understanding to continue your journey into Swift. I hope this tutorial has shown you how Swift's control flow implementation is very similar to that of other programming languages—but with a twist.

In the rest of this series, we'll make more use of Swift's control flow constructs, and you'll gradually get a better understanding of the subtle differences between Swift and languages like Objective-C. In the next installment of this series, we'll start exploring functions.

If you want a quick way to get started building apps with the Swift language, we've got a course for that!

Or check out some of our other tutorials and courses on Swift and iOS development!

2017-02-23T19:18:19.000Z2017-02-23T19:18:19.000ZBart Jacobs

Code an Image Gallery Android App With Glide

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

1. What Is Glide?

Glide is a popular open-source Android library for loading images, videos, and animated GIFs. With Glide, you can load and display media from many different sources, such as remote servers or the local file system.  

By default, Glide uses a custom implementation of HttpURLConnection to load images over the internet. However, Glide also provides plugins to other popular networking libraries such as Volley or OkHttp

2. So Why Use Glide?

Developing your own media loading and display functionality in Java can be a real pain: you have to take care of caching, decoding, managing network connections, threading, exception handling, and more. Glide is an easy to use, well planned, well documented, and thoroughly tested library that can save you a lot of precious time—and save you some headaches. 

In this tutorial, we'll learn about Glide 3 by building a simple image gallery app. It will load the images via the internet and display them as thumbnails in a RecyclerView, and when a user clicks on any image, it will open a detail activity containing the larger image. 

3. Create an Android Studio Project

Fire up your Android Studio and create a new project with an empty activity called MainActivity

Android Studio new project screenshot

4. Declare Dependencies

After creating a new project, specify the following dependencies in your build.gradle.

Or with Maven:

Make sure you sync your project after adding the Glide dependency.

Integration Libraries

If you want to use a networking library such as OkHttp or Volley in your project for network operations, it is recommended you include the specific Glide integration for the library you are using (instead of the default one which bundles HttpURLConnection). 

Volley 

OkHttp 

You can visit the official Glide integration libraries guide for more information. 

5. Add Internet Permission

Since Glide is going to perform a network request to load images via the internet, we need to include the permission INTERNET in our AndroidManifest.xml

6. Create the Layout

We'll start by creating our RecyclerView

Creating the Custom Item Layout

Next, let's create the XML layout that will be used for each item (ImageView) within the RecyclerView

Now that we have created the layout, the next step is to create the RecyclerView adapter for populating data. Before we do that, though, let's create our simple data model. 

7. Create a Data Model

We are going to define a simple data model for our RecyclerView. This model implements Parcelable for high-performance transport of data from one component to another. In our case, data will be transported from SpaceGalleryActivity to SpacePhotoActivity

8. Create the Adapter

We'll create an adapter to populate the RecyclerView with data. We'll also implement a click listener to open the detail activity—SpacePhotoActivity—passing it an instance of SpacePhoto as an extra. The detail activity will show a close-up of the image. We'll create it in a later section.

9. Loading Images From a URL

This is where we need Glide to do its job—to fetch images from the internet and display them in the individual ImageViews, using our RecyclerView onBindViewHolder() method as the user scrolls the app. 

Step by step, here are what the calls to Glide are doing:

  • with(Context context): we begin the load process by first passing our context into the with() method. 
  • load(String string): the image source is specified as either a directory path, a URI, or a URL.
  • placeholder(int resourceId): a local application resource id, preferably a drawable, that will be a placeholder until the image is loaded and displayed.
  • into(ImageView imageView): the target image view into which the image will be placed.

Be aware that Glide can also load local images. Just pass either the Android resource id, the file path, or a URI as an argument to the load() method. 

Image Resizing and Transformation

You can resize the image before it is displayed in the ImageView with Glide's .override(int width, int height) method. This is useful for creating thumbnails in your app when loading a different image size from the server. Note that the dimensions are in pixels not dp. 

The following image transformations are also available:

  • fitCenter(): scales the image uniformly (maintaining the image's aspect ratio) so that the image will fit in the given area. The entire image will be visible, but there might be vertical or horizontal padding.
  • centerCrop(): scales the image uniformly (maintaining the image's aspect ratio) so that the image fills up the given area, with as much of the image showing as possible. If needed, the image will be cropped horizontally or vertically to fit.

10. Initializing the Adapter

Here we create our RecyclerView with GridLayoutManager as the layout manager, initialize our adapter, and bind it to the RecyclerView

11. Creating the Detail Activity

Create a new activity and name it SpacePhotoActivity. We get the SpacePhoto extra and load the image with Glide as we did before. Here we are expecting the file or URL to be a Bitmap, so we'll use asBitmap() to makes that Glide receives a Bitmap. Otherwise the load will fail and the .error() callback will be triggered—causing the drawable resource returned from the error callback to be shown. 

You could also use asGif() if you wanted to ensure that your loaded image was a GIF. (I'll explain how GIFs work in Glide shortly.)

Note that we also initialized a unique cache for the loaded images: DiskCacheStrategy.SOURCE. I'll explain more about caching in a later section.

The Detail Layout

Here's a layout to display the detail activity. It just displays a scrollable ImageView that will show the full-resolution version of the loaded image.

12. Caching in Glide

If you watch closely, you'll see that when you revisit an image that was previously loaded, it loads even faster than before. What made it faster? Glide's caching system, that's what.

After an image has been loaded once from the internet, Glide will cache it in memory and on disk, saving repeated network requests and permitting faster retrieval of the image. So, Glide will first check if an image is available in either memory or on the disk before loading it from the network. 

Depending on your application, though, you might want to avoid caching—for example if the images being displayed are likely to change often and not to be reloaded.

So How Do You Disable Caching? 

You can avoid memory caching by calling .skipMemoryCache(true). But be aware that the image will still be cached on the disk—to prevent that also, you use the .diskCacheStrategy(DiskCacheStrategy strategy) method, which takes one of the following enum values:

  • DiskCacheStrategy.NONE: no data is saved to cache.
  • DiskCacheStrategy.SOURCE: original data saved to cache.
  • DiskCacheStrategy.RESULT: saves the result of the data after transformations to cache.
  • DiskCacheStrategy.ALL: caches both original data and transformed data. 

To avoid both memory and disk caching altogether, just call both methods one after the other:

13. Request Listeners

In Glide, you can implement a RequestListener to monitor the status of the request you made as the image loads. Only one of these methods will be called. 

  • onException(): triggered whenever an exception occurs so you can handle exceptions in this method.
  • onResourceReady(): fired when the image is loaded successfully. 

Going back to our image gallery app, let's modify the display a little by using a RequestListener object that will set the bitmap to the ImageView and also change the background colour of the layout by extracting the dark and vibrate colour of our image using the Android Palette API

Here you could also hide a progress dialog if you had one. With this last change, make sure to include the Palette dependency in your build.gradle:

14. Testing the App

Finally, you can run the app! Click on a thumbnail to get a full-sized version of the image.

Emulator running the application screenshots

15. Animations

If you run the app, you will notice a crossfade animation that happens while the image is being displayed. Glide has this enabled by default, but you can disable it by calling dontAnimate(), which will just cause the image to be displayed without any animation. 

You can also customize the crossfade animation by calling crossFade(int duration), passing the duration in milliseconds to either speed it up or slow it down—300 milliseconds is the default. 

Animated GIFs

It's very simple to display an animated GIF in your app using Glide. It works the same as displaying an ordinary image.

If you are expecting the image to be a GIF, call asGif()—this makes sure that Glide receives a GIF, otherwise the load will fail and the Drawable passed to the .error() method will be shown instead.

Playing Video

Unfortunately, Glide does not support video loading and display via URL. Instead it can only load and display videos already stored on the phone. Show a video by passing its URI to the load() method. 

Conclusion

Great job! In this tutorial, you've built a complete image gallery app with Glide, and along the way learned how the library works and how you can integrate it in your own project. You've also learned how to display both local and remote images, how to show animated GIFs and videos, and how to apply image transformations like resizing. Not only that, but you've seen how easy it is to enable caching, error handling, and custom request listeners. 

To learn more about Glide, you can refer to its official documentation. To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

2017-02-28T12:25:21.000Z2017-02-28T12:25:21.000ZChike Mgbemena

Code an Image Gallery Android App With Glide

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

1. What Is Glide?

Glide is a popular open-source Android library for loading images, videos, and animated GIFs. With Glide, you can load and display media from many different sources, such as remote servers or the local file system.  

By default, Glide uses a custom implementation of HttpURLConnection to load images over the internet. However, Glide also provides plugins to other popular networking libraries such as Volley or OkHttp

2. So Why Use Glide?

Developing your own media loading and display functionality in Java can be a real pain: you have to take care of caching, decoding, managing network connections, threading, exception handling, and more. Glide is an easy to use, well planned, well documented, and thoroughly tested library that can save you a lot of precious time—and save you some headaches. 

In this tutorial, we'll learn about Glide 3 by building a simple image gallery app. It will load the images via the internet and display them as thumbnails in a RecyclerView, and when a user clicks on any image, it will open a detail activity containing the larger image. 

3. Create an Android Studio Project

Fire up your Android Studio and create a new project with an empty activity called MainActivity

Android Studio new project screenshot

4. Declare Dependencies

After creating a new project, specify the following dependencies in your build.gradle.

Or with Maven:

Make sure you sync your project after adding the Glide dependency.

Integration Libraries

If you want to use a networking library such as OkHttp or Volley in your project for network operations, it is recommended you include the specific Glide integration for the library you are using (instead of the default one which bundles HttpURLConnection). 

Volley 

OkHttp 

You can visit the official Glide integration libraries guide for more information. 

5. Add Internet Permission

Since Glide is going to perform a network request to load images via the internet, we need to include the permission INTERNET in our AndroidManifest.xml

6. Create the Layout

We'll start by creating our RecyclerView

Creating the Custom Item Layout

Next, let's create the XML layout that will be used for each item (ImageView) within the RecyclerView

Now that we have created the layout, the next step is to create the RecyclerView adapter for populating data. Before we do that, though, let's create our simple data model. 

7. Create a Data Model

We are going to define a simple data model for our RecyclerView. This model implements Parcelable for high-performance transport of data from one component to another. In our case, data will be transported from SpaceGalleryActivity to SpacePhotoActivity

8. Create the Adapter

We'll create an adapter to populate the RecyclerView with data. We'll also implement a click listener to open the detail activity—SpacePhotoActivity—passing it an instance of SpacePhoto as an extra. The detail activity will show a close-up of the image. We'll create it in a later section.

9. Loading Images From a URL

This is where we need Glide to do its job—to fetch images from the internet and display them in the individual ImageViews, using our RecyclerView onBindViewHolder() method as the user scrolls the app. 

Step by step, here are what the calls to Glide are doing:

  • with(Context context): we begin the load process by first passing our context into the with() method. 
  • load(String string): the image source is specified as either a directory path, a URI, or a URL.
  • placeholder(int resourceId): a local application resource id, preferably a drawable, that will be a placeholder until the image is loaded and displayed.
  • into(ImageView imageView): the target image view into which the image will be placed.

Be aware that Glide can also load local images. Just pass either the Android resource id, the file path, or a URI as an argument to the load() method. 

Image Resizing and Transformation

You can resize the image before it is displayed in the ImageView with Glide's .override(int width, int height) method. This is useful for creating thumbnails in your app when loading a different image size from the server. Note that the dimensions are in pixels not dp. 

The following image transformations are also available:

  • fitCenter(): scales the image uniformly (maintaining the image's aspect ratio) so that the image will fit in the given area. The entire image will be visible, but there might be vertical or horizontal padding.
  • centerCrop(): scales the image uniformly (maintaining the image's aspect ratio) so that the image fills up the given area, with as much of the image showing as possible. If needed, the image will be cropped horizontally or vertically to fit.

10. Initializing the Adapter

Here we create our RecyclerView with GridLayoutManager as the layout manager, initialize our adapter, and bind it to the RecyclerView

11. Creating the Detail Activity

Create a new activity and name it SpacePhotoActivity. We get the SpacePhoto extra and load the image with Glide as we did before. Here we are expecting the file or URL to be a Bitmap, so we'll use asBitmap() to makes that Glide receives a Bitmap. Otherwise the load will fail and the .error() callback will be triggered—causing the drawable resource returned from the error callback to be shown. 

You could also use asGif() if you wanted to ensure that your loaded image was a GIF. (I'll explain how GIFs work in Glide shortly.)

Note that we also initialized a unique cache for the loaded images: DiskCacheStrategy.SOURCE. I'll explain more about caching in a later section.

The Detail Layout

Here's a layout to display the detail activity. It just displays a scrollable ImageView that will show the full-resolution version of the loaded image.

12. Caching in Glide

If you watch closely, you'll see that when you revisit an image that was previously loaded, it loads even faster than before. What made it faster? Glide's caching system, that's what.

After an image has been loaded once from the internet, Glide will cache it in memory and on disk, saving repeated network requests and permitting faster retrieval of the image. So, Glide will first check if an image is available in either memory or on the disk before loading it from the network. 

Depending on your application, though, you might want to avoid caching—for example if the images being displayed are likely to change often and not to be reloaded.

So How Do You Disable Caching? 

You can avoid memory caching by calling .skipMemoryCache(true). But be aware that the image will still be cached on the disk—to prevent that also, you use the .diskCacheStrategy(DiskCacheStrategy strategy) method, which takes one of the following enum values:

  • DiskCacheStrategy.NONE: no data is saved to cache.
  • DiskCacheStrategy.SOURCE: original data saved to cache.
  • DiskCacheStrategy.RESULT: saves the result of the data after transformations to cache.
  • DiskCacheStrategy.ALL: caches both original data and transformed data. 

To avoid both memory and disk caching altogether, just call both methods one after the other:

13. Request Listeners

In Glide, you can implement a RequestListener to monitor the status of the request you made as the image loads. Only one of these methods will be called. 

  • onException(): triggered whenever an exception occurs so you can handle exceptions in this method.
  • onResourceReady(): fired when the image is loaded successfully. 

Going back to our image gallery app, let's modify the display a little by using a RequestListener object that will set the bitmap to the ImageView and also change the background colour of the layout by extracting the dark and vibrate colour of our image using the Android Palette API

Here you could also hide a progress dialog if you had one. With this last change, make sure to include the Palette dependency in your build.gradle:

14. Testing the App

Finally, you can run the app! Click on a thumbnail to get a full-sized version of the image.

Emulator running the application screenshots

15. Animations

If you run the app, you will notice a crossfade animation that happens while the image is being displayed. Glide has this enabled by default, but you can disable it by calling dontAnimate(), which will just cause the image to be displayed without any animation. 

You can also customize the crossfade animation by calling crossFade(int duration), passing the duration in milliseconds to either speed it up or slow it down—300 milliseconds is the default. 

Animated GIFs

It's very simple to display an animated GIF in your app using Glide. It works the same as displaying an ordinary image.

If you are expecting the image to be a GIF, call asGif()—this makes sure that Glide receives a GIF, otherwise the load will fail and the Drawable passed to the .error() method will be shown instead.

Playing Video

Unfortunately, Glide does not support video loading and display via URL. Instead it can only load and display videos already stored on the phone. Show a video by passing its URI to the load() method. 

Conclusion

Great job! In this tutorial, you've built a complete image gallery app with Glide, and along the way learned how the library works and how you can integrate it in your own project. You've also learned how to display both local and remote images, how to show animated GIFs and videos, and how to apply image transformations like resizing. Not only that, but you've seen how easy it is to enable caching, error handling, and custom request listeners. 

To learn more about Glide, you can refer to its official documentation. To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

2017-02-28T12:25:21.000Z2017-02-28T12:25:21.000ZChike Mgbemena

Back-End as a Service for Mobile Apps

$
0
0

If you're a mobile developer, you may be wondering how to manage user data in your next app. Should you use a database, a dedicated server, or maybe you can manage only with a front-end? This article will help you make a better decision.

1. What Is Back-End?

Before we dive into the details of available service, let's get some terminology out of the way.

For mobile and web apps, we often talk about the front- and back-ends. While the front-end defines the user interface, user interaction, and presentation of information, the back-end handles the business logic, data storage, and security. The front-end is the users' web browser or mobile device, and the back-end is the server or servers where data is stored and shared.

A growing number of modern mobile apps rely on at least a few features that require a back-end. User and usage analytics, push notifications, extended security, user-to-user communication (in multiplayer games or messaging apps, for example) and monetizing the app through advertisements are the most common examples.

2. Who Develops It?

From a mobile developer's point of view, the back-end seems to be a whole other world, populated with databases and servers. So not only are developers expected to create beautiful and performant mobile interfaces, they must also be knowledgeable about network infrastructure such as web servers, database management software, server-side-scripting languages and a lot more. 

Furthermore, they're expected to be experts on modern cryptography and computer security, big data and data mining, mobile telecommunication networks (mobile apps mostly run on smart phones connected to a mobile telephone network) and an ever growing list of additional technologies.

Naturally, it follows that, even to develop a simple mobile app with a back-end, the developer needs to master many tools and languages that are outside the scope of ordinary app development. Surely, this situation discourages a lot of developers from integrating a back-end into their apps. 

3. Back-End as a Service (BaaS) to the Rescue

With cloud computing absorbed into the mainstream, XaaS (meaning BaaS, SaaS, PaaS, etc.—Back-End as a Service, Software as a Service or Platform as a Service) has already started to redefine the way software is developed, published, and consumed.

The basic idea is similar to having your back-end development, maintenance and management outsourced to another party. In other words, the back-end is made available to developers as a web service. 

While different BaaS providers offer diverse features through a large variety of pricing models, most of them use some kind of "freemium" model. This means core features such as data storage, user/usage analytics, push notifications, and authentication are provided free of charge up to a certain usage limit. Once the usage exceeds that limit or additional features are requested, a fee is charged. This makes it easy to create and launch an app at the free usage tier, and then to scale up to a paid tier as you add customers.

Normally the developer needs to use the SDKs and APIs of the BaaS provider to connect their app to the back-end.

4. Pros & Cons of BaaS

The biggest advantage of BaaS is that it frees developers from the burden of building and managing back-ends themselves. That allows the developer to concentrate on more important stuff, such as designing a compelling user experience, which will be the actual success factors of the app. Also, it helps the developer avoid steep learning curves typically associated with most back-end technologies. So it cuts the cost and the development time. It also provides a cheap way of experimenting with app ideas and seeing how they perform in the real world.

As with anything else, BaaS has some tradeoffs. The biggest downside is the danger that your BaaS provider might suddenly go out of business and close down the service. In such a scenario, even if you switch to another provider, you may need to substantially redesign and recode your app, because the new service might have a completely different API. Actually, one of the most popular BaaS providers, Parse, recently closed, which has affected a lot of developers (though the Parse infrastructure was released under an open-source licence, and new vendors have sprung up to provide a Parse-compatible BaaS). 

Another downside is that customization of back-end infrastructure in a BaaS is often limited. That might mean that some functionality you want for your app is not available.

5. How to Choose a BaaS Provider?

There are several questions you need to ask yourself about each BaaS provider, before selecting one for your mobile app. 

The first question is whether the provider can fulfill your app's needs. It's worth mentioning that sometimes, redefining the scope of your app to match the features offered by a BaaS provider can give you really amazing results. But don't give up the features that give your app its uniqueness and appeal!

Most BaaS providers offer their services, free of charge, only up to a certain point. This limiting point is usually defined by something like the number of API calls, number of active users, or a similar parameter. Sometimes, it can be very difficult for the developer to forecast the amount of usage or the number of users of the app. So it's quite possible to end up with a platform which is not profitable for the developer. 

Check this in advance by projecting the cost and revenue for a range of possible values that correspond to the usage or the number of users. Then, you can see how much of the app's revenue would go to BaaS fees and adjust your revenue model if need be. Alternatively, the developer can look for a BaaS provider whose pricing model best matches the app's revenue model.

Because there are limits to customization, some apps might be hard or impossible to develop with some of the off-the-shelf BaaS offerings. Interestingly, some BaaS providers offer more specialized features targeting a specific app category, such as games. If your app falls into such a category, there's a bigger chance that the required feature is supported by such a provider. You need to do a bit of research about BaaS providers who target your specific app category.

The developer also needs to consider the lifecycle of the app. The longer the life of the app, the higher the cost of sticking with the BaaS provider. For an app that will be around for a long time, it might be worth investing in creating your own back-end.

6. Popular BaaS Providers

Now that we have some insights into BaaS from both a developer's and an app startup founder's point of view, let's look at some of the popular BaaS packages and their features. While the industry is dominated by the commercial providers, a set of aspiring open-source providers also seem to be on the rise.

Firebase

Google's BaaS platform, Firebase, offers an extensive list of features categorized under three stages, namely Develop, Earn, and Grow. The Develop stage consists of real-time databases, authentication, cloud messaging, storage, hosting, test lab (for testing apps on a device), and crash reporting. Being a commercial provider, it has also integrated its AdMob platform for monetizing your app. Further on the path to growth, you'll find the features such as App Indexing, AdWords, Notifications and a lot more.

Because it is from Google, the creator of Android, Firebase is usually seen as an Android platform. However, the Firebase SDK is also available for iOS

Here on Envato Tuts+, we have a number of tutorials and courses to help you get started with Firebase. Check them out!

AWS

Another commercial provider, Amazon Web Services (AWS), was one of the first PaaS providers. It boasts a rich set of cloud services and accompanying tools, with control, if you want it, over every aspect of your virtual servers. In fact, many other cloud service providers use AWS behind the scenes. 

All this power comes with a cost, though—AWS has a much steeper learning curve than other BaaS providers. Features include mobile SDKs, email and SMS notifications, app analytics, and the Device Farm for testing your app on various mobile devices.

Back4App (Parse SDK)

Parse was a popular BaaS platform, but unfortunately Facebook has decided to shut it down. But don't worry that the Parse SDK will die! Facebook retired the parse.com hosting service in January 2017, but the Parse SDK has been made open source. Parse SDK has lots of great developers working on it, and there are a number of brand new websites that offer back-end hosting as a service.

One of the best is Back4App. It has a free tier with a generous storage and requests budget, as well as APIs for Android and iOS.

Mesosfer

Introducing its highly elastic BaaS, Mesosfer is a commercial provider with interesting features that supports mobile, web and even IoT embedded apps. 

BaasBox

Unlike the previous members on this list, BaasBox is an open-source BaaS provider. The developer and API usage statistics displayed on their website suggest a competitive and capable provider, comparable with the commercial providers.

Apache Usergrid

Another open-source BaaS is Apache Usergrid (from the creator of the popular web server). Usergrid supports running on traditional server infrastructure, enabling you to deploy your own BaaS platform. Features include user management, file and data storage plus retrieval.

Apple CloudKit

Apple introduced their CloudKit framework alongside iOS 8 in 2014. While its main purpose was to act as an online database for iOS applications, CloudKit also offers many other features, including push notifications. One of the best things about CloudKit for some developers is how much you get for free. For example, with CloudKit, there is no limit on the number of push notifications you can send to your users. 

However, a disadvantage you should be aware of when using CloudKit is that it is not currently available on any non-Apple platforms. That means that if you want to create an Android version of your app, CloudKit won't work!

7. Conclusion

BaaS is a practical and timely solution to the problem of adding a back-end to your mobile apps. It also helps the developer direct their own limited time in the best possible way. There are a growing number of BaaS providers out there, and now you know how to make use of them!

2017-03-05T15:00:44.095Z2017-03-05T15:00:44.095ZBala Durage Sandamal Siripathi

Back-End as a Service for Mobile Apps

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

If you're a mobile developer, you may be wondering how to manage user data in your next app. Should you use a database, a dedicated server, or maybe you can manage only with a front-end? This article will help you make a better decision.

1. What Is Back-End?

Before we dive into the details of available service, let's get some terminology out of the way.

For mobile and web apps, we often talk about the front- and back-ends. While the front-end defines the user interface, user interaction, and presentation of information, the back-end handles the business logic, data storage, and security. The front-end is the users' web browser or mobile device, and the back-end is the server or servers where data is stored and shared.

A growing number of modern mobile apps rely on at least a few features that require a back-end. User and usage analytics, push notifications, extended security, user-to-user communication (in multiplayer games or messaging apps, for example) and monetizing the app through advertisements are the most common examples.

2. Who Develops It?

From a mobile developer's point of view, the back-end seems to be a whole other world, populated with databases and servers. So not only are developers expected to create beautiful and performant mobile interfaces, they must also be knowledgeable about network infrastructure such as web servers, database management software, server-side-scripting languages and a lot more. 

Furthermore, they're expected to be experts on modern cryptography and computer security, big data and data mining, mobile telecommunication networks (mobile apps mostly run on smart phones connected to a mobile telephone network) and an ever growing list of additional technologies.

Naturally, it follows that, even to develop a simple mobile app with a back-end, the developer needs to master many tools and languages that are outside the scope of ordinary app development. Surely, this situation discourages a lot of developers from integrating a back-end into their apps. 

3. Back-End as a Service (BaaS) to the Rescue

With cloud computing absorbed into the mainstream, XaaS (meaning BaaS, SaaS, PaaS, etc.—Back-End as a Service, Software as a Service or Platform as a Service) has already started to redefine the way software is developed, published, and consumed.

The basic idea is similar to having your back-end development, maintenance and management outsourced to another party. In other words, the back-end is made available to developers as a web service. 

While different BaaS providers offer diverse features through a large variety of pricing models, most of them use some kind of "freemium" model. This means core features such as data storage, user/usage analytics, push notifications, and authentication are provided free of charge up to a certain usage limit. Once the usage exceeds that limit or additional features are requested, a fee is charged. This makes it easy to create and launch an app at the free usage tier, and then to scale up to a paid tier as you add customers.

Normally the developer needs to use the SDKs and APIs of the BaaS provider to connect their app to the back-end.

4. Pros & Cons of BaaS

The biggest advantage of BaaS is that it frees developers from the burden of building and managing back-ends themselves. That allows the developer to concentrate on more important stuff, such as designing a compelling user experience, which will be the actual success factors of the app. Also, it helps the developer avoid steep learning curves typically associated with most back-end technologies. So it cuts the cost and the development time. It also provides a cheap way of experimenting with app ideas and seeing how they perform in the real world.

As with anything else, BaaS has some tradeoffs. The biggest downside is the danger that your BaaS provider might suddenly go out of business and close down the service. In such a scenario, even if you switch to another provider, you may need to substantially redesign and recode your app, because the new service might have a completely different API. Actually, one of the most popular BaaS providers, Parse, recently closed, which has affected a lot of developers (though the Parse infrastructure was released under an open-source licence, and new vendors have sprung up to provide a Parse-compatible BaaS). 

Another downside is that customization of back-end infrastructure in a BaaS is often limited. That might mean that some functionality you want for your app is not available.

5. How to Choose a BaaS Provider?

There are several questions you need to ask yourself about each BaaS provider, before selecting one for your mobile app. 

The first question is whether the provider can fulfill your app's needs. It's worth mentioning that sometimes, redefining the scope of your app to match the features offered by a BaaS provider can give you really amazing results. But don't give up the features that give your app its uniqueness and appeal!

Most BaaS providers offer their services, free of charge, only up to a certain point. This limiting point is usually defined by something like the number of API calls, number of active users, or a similar parameter. Sometimes, it can be very difficult for the developer to forecast the amount of usage or the number of users of the app. So it's quite possible to end up with a platform which is not profitable for the developer. 

Check this in advance by projecting the cost and revenue for a range of possible values that correspond to the usage or the number of users. Then, you can see how much of the app's revenue would go to BaaS fees and adjust your revenue model if need be. Alternatively, the developer can look for a BaaS provider whose pricing model best matches the app's revenue model.

Because there are limits to customization, some apps might be hard or impossible to develop with some of the off-the-shelf BaaS offerings. Interestingly, some BaaS providers offer more specialized features targeting a specific app category, such as games. If your app falls into such a category, there's a bigger chance that the required feature is supported by such a provider. You need to do a bit of research about BaaS providers who target your specific app category.

The developer also needs to consider the lifecycle of the app. The longer the life of the app, the higher the cost of sticking with the BaaS provider. For an app that will be around for a long time, it might be worth investing in creating your own back-end.

6. Popular BaaS Providers

Now that we have some insights into BaaS from both a developer's and an app startup founder's point of view, let's look at some of the popular BaaS packages and their features. While the industry is dominated by the commercial providers, a set of aspiring open-source providers also seem to be on the rise.

Firebase

Google's BaaS platform, Firebase, offers an extensive list of features categorized under three stages, namely Develop, Earn, and Grow. The Develop stage consists of real-time databases, authentication, cloud messaging, storage, hosting, test lab (for testing apps on a device), and crash reporting. Being a commercial provider, it has also integrated its AdMob platform for monetizing your app. Further on the path to growth, you'll find the features such as App Indexing, AdWords, Notifications and a lot more.

Because it is from Google, the creator of Android, Firebase is usually seen as an Android platform. However, the Firebase SDK is also available for iOS

Here on Envato Tuts+, we have a number of tutorials and courses to help you get started with Firebase. Check them out!

AWS

Another commercial provider, Amazon Web Services (AWS), was one of the first PaaS providers. It boasts a rich set of cloud services and accompanying tools, with control, if you want it, over every aspect of your virtual servers. In fact, many other cloud service providers use AWS behind the scenes. 

All this power comes with a cost, though—AWS has a much steeper learning curve than other BaaS providers. Features include mobile SDKs, email and SMS notifications, app analytics, and the Device Farm for testing your app on various mobile devices.

Back4App (Parse SDK)

Parse was a popular BaaS platform, but unfortunately Facebook has decided to shut it down. But don't worry that the Parse SDK will die! Facebook retired the parse.com hosting service in January 2017, but the Parse SDK has been made open source. Parse SDK has lots of great developers working on it, and there are a number of brand new websites that offer back-end hosting as a service.

One of the best is Back4App. It has a free tier with a generous storage and requests budget, as well as APIs for Android and iOS.

Mesosfer

Introducing its highly elastic BaaS, Mesosfer is a commercial provider with interesting features that supports mobile, web and even IoT embedded apps. 

BaasBox

Unlike the previous members on this list, BaasBox is an open-source BaaS provider. The developer and API usage statistics displayed on their website suggest a competitive and capable provider, comparable with the commercial providers.

Apache Usergrid

Another open-source BaaS is Apache Usergrid (from the creator of the popular web server). Usergrid supports running on traditional server infrastructure, enabling you to deploy your own BaaS platform. Features include user management, file and data storage plus retrieval.

Azure Mobile Services

Microsoft has added a BaaS platform to Azure, their popular suite of cloud services. Azure Mobile Services has support for push notifications, data syncing, and authentication. For developers working in the enterprise domain, Azure Mobile Services also has robust support for connectivity to corporate networks using technologies like Active Directory and VPN. Reflecting Microsoft's recent embrace of cross-platform development, Azure Mobile Services works on Android, iOS, and of course Windows Phone.

Apple CloudKit

Apple introduced their CloudKit framework alongside iOS 8 in 2014. While its main purpose was to act as an online database for iOS applications, CloudKit also offers many other features, including push notifications. One of the best things about CloudKit for some developers is how much you get for free. For example, with CloudKit, there is no limit on the number of push notifications you can send to your users. 

However, a disadvantage you should be aware of when using CloudKit is that it is not currently available on any non-Apple platforms. That means that if you want to create an Android version of your app, CloudKit won't work!

7. Conclusion

BaaS is a practical and timely solution to the problem of adding a back-end to your mobile apps. It also helps the developer direct their own limited time in the best possible way. There are a growing number of BaaS providers out there, and now you know how to make use of them!

2017-03-05T15:00:44.095Z2017-03-05T15:00:44.095ZBala Durage Sandamal Siripathi

10 Best Restaurant App Templates

$
0
0

CodeCanyon offers a wide range of application templates to kickstart your mobile app project. In this article, I'll show you the top ten restaurant templates that you should consider for your next restaurant app.

Android App Templates

Your Restaurant App

Want a restaurant app template that fulfils both users' and administrators' needs? Then this template is for you. 

Your Restaurant App is a Material Design template that can get your intended restaurant app running almost immediately. This template has cool features needed in any restaurant app such as menus, images gallery, news, location, social, reservations and push notifications powered by Firebase for user engagement. It also has an admin back-end for general management of the app. 

You should try it out by downloading the app from the Google Play Store and see for yourself! 

Your Restaurant App template

Restaurant Finder 

Restaurant Finder is an Android app template for finding nearby restaurants. App features include food and price ratings by users and a restaurant gallery. Users can also track their favourite restaurants. Users can easily find their way to a restaurant with the help of a built-in map, powered by Google Maps. 

This template also ships with a PHP Admin back-end and AdMob integration. You can also give a restaurant a call right from the app. You are free to try out the app by downloading the apk and see if it works for you!

Restaurant Finder app template

iOS App Templates

Restaurant Finder

This template is for apps on the iOS platform. Users can easily find a restaurant and can make reservations by call, email, or SMS. Not only that, the template is also packed with features such as restaurant search functionality with querying by zip code, restaurant name, or food being served. Map integration is included for easy directions, as well as a customer profile and review feature. You even have the ability to filter restaurants by food cuisines. 

Restaurant Finder

The app is also supported by an admin web dashboard which is shipped together with the template, where an administrator can add new restaurants, new food categories, special offers, and more. 

Restaurateur iOS 

This iOS app is packed with lots of useful features and flexibility for either a single restaurant or multiple restaurants. What also makes this template really unique is the shopping cart and checkout functionality, allowing users to purchase meals online for takeout or home delivery. 

This app template also has features such as searching for nearby restaurants, item inquiries, reservations, user profiles, and support for Apple Push Notification Service. 

Restaurateur screenshots

This app template also includes a back-end for general management of the system. It has a really nice UI and an easy navigation system. You should check it out!

Food Delivery System for Restaurant

This app template is useful for a single restaurant. Its features include the ability to search and order specific items as well as cart management, reservations, reservation reminders, and Admob integration. This template also comes with a PHP admin back-end, for configuring details of the restaurant. 

One thing I really like about this template is the cool UI animation! Compatible with all iOS versions through iOS 9. An Android version of the Food Delivery System template is also available on CodeCanyon.

Food Delivery System template

Restaurant IOS Template

This app template is compatible with iOS 8 and 9 development environments out of the box, but an up-to-date iOS 10 and Swift 3 version is available on request. Features include a menu, with descriptions and photos for each item, as well as a restaurant gallery, social media integration, and contact details. 

There is no back-end to manage with this template—it works offline and is configured via XML. It also has Google Analytics integration. This simple iOS template is simple to set up and easy to navigate. 

Restaurant IOS template

Cross-Platform App Templates

Restaurant App Template - React Native

This app template is a React Native mobile app that works for both the Android and IOS platforms. The template has a unique and attractive user interface and some notable features: multi-language support, order management, push notifications for user engagement, PayPal payment integration, and a Firebase-powered admin dashboard for general management. You can download the app from the Google Play Store and try it out today. 

Restaurant App Template  - React Native

Restaurant Ionic

This app template is a cross-platform Ionic app template for a single restaurant. Some of the more interesting features include colour themes to choose from for app branding, Firebase back-end integration, categorized menus, restaurant finder with built-in map, special offers, and a shopping cart. 

For engagement, you can send push notifications, and the app includes social network integration so that users can view the restaurant's social media profile. You can download the Android apk file to check it out for yourself!

Restaurant Ionic App template

Crunchy - Restaurant Booking

This app template is packed with functionality that is needed for any restaurant app built on PhoneGap and the Ionic framework. This cross-platform app template features easy payment integration with PayPal and Stripe, social media login with Facebook or Google+, and a back-end platform built on the CodeIgniter PHP framework

An Android apk is available, so you can download an example app made with this template. Try it out, see how it feels, and then make your decision!

Crunchy Restaurant app

Caetano 

This is a very clean and easy-to-use Ionic 2 restaurant app template. Features include a splash screen, food menu, shopping cart, and user profile. This template does not come with any ready-made back-end, but you can easily implement your own service with the back-end provider of your choice. It's also easily customizable. Why don't you give it a shot by downloading the apk and see if it fits your needs? 

Caetano app template

Conclusion

App templates are a great way to jumpstart your next development project, or to learn from other people's work. This article lists just a few of the popular mobile app templates available on Envato Market. If you are looking for inspiration or you're building an application and need help with a particular feature, then you may find your answer in some of these templates.

Put one of these templates to use right now, or check out some of the other templates for complete apps available on CodeCanyon. Learn more about them right here on Envato Tuts+!

2017-03-09T13:49:05.000Z2017-03-09T13:49:05.000ZChike Mgbemena

10 Best Restaurant App Templates

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

CodeCanyon offers a wide range of application templates to kickstart your mobile app project. In this article, I'll show you the top ten restaurant templates that you should consider for your next restaurant app.

Android App Templates

Your Restaurant App

Want a restaurant app template that fulfils both users' and administrators' needs? Then this template is for you. 

Your Restaurant App is a Material Design template that can get your intended restaurant app running almost immediately. This template has cool features needed in any restaurant app such as menus, images gallery, news, location, social, reservations and push notifications powered by Firebase for user engagement. It also has an admin back-end for general management of the app. 

You should try it out by downloading the app from the Google Play Store and see for yourself! 

Your Restaurant App template

Restaurant Finder 

Restaurant Finder is an Android app template for finding nearby restaurants. App features include food and price ratings by users and a restaurant gallery. Users can also track their favourite restaurants. Users can easily find their way to a restaurant with the help of a built-in map, powered by Google Maps. 

This template also ships with a PHP Admin back-end and AdMob integration. You can also give a restaurant a call right from the app. You are free to try out the app by downloading the apk and see if it works for you!

Restaurant Finder app template

iOS App Templates

Restaurant Finder

This template is for apps on the iOS platform. Users can easily find a restaurant and can make reservations by call, email, or SMS. Not only that, the template is also packed with features such as restaurant search functionality with querying by zip code, restaurant name, or food being served. Map integration is included for easy directions, as well as a customer profile and review feature. You even have the ability to filter restaurants by food cuisines. 

Restaurant Finder

The app is also supported by an admin web dashboard which is shipped together with the template, where an administrator can add new restaurants, new food categories, special offers, and more. 

Restaurateur iOS 

This iOS app is packed with lots of useful features and flexibility for either a single restaurant or multiple restaurants. What also makes this template really unique is the shopping cart and checkout functionality, allowing users to purchase meals online for takeout or home delivery. 

This app template also has features such as searching for nearby restaurants, item inquiries, reservations, user profiles, and support for Apple Push Notification Service. 

Restaurateur screenshots

This app template also includes a back-end for general management of the system. It has a really nice UI and an easy navigation system. You should check it out!

Food Delivery System for Restaurant

This app template is useful for a single restaurant. Its features include the ability to search and order specific items as well as cart management, reservations, reservation reminders, and Admob integration. This template also comes with a PHP admin back-end, for configuring details of the restaurant. 

One thing I really like about this template is the cool UI animation! Compatible with all iOS versions through iOS 9. An Android version of the Food Delivery System template is also available on CodeCanyon.

Food Delivery System template

Restaurant IOS Template

This app template is compatible with iOS 8 and 9 development environments out of the box, but an up-to-date iOS 10 and Swift 3 version is available on request. Features include a menu, with descriptions and photos for each item, as well as a restaurant gallery, social media integration, and contact details. 

There is no back-end to manage with this template—it works offline and is configured via XML. It also has Google Analytics integration. This simple iOS template is simple to set up and easy to navigate. 

Restaurant IOS template

Cross-Platform App Templates

Restaurant App Template - React Native

This app template is a React Native mobile app that works for both the Android and IOS platforms. The template has a unique and attractive user interface and some notable features: multi-language support, order management, push notifications for user engagement, PayPal payment integration, and a Firebase-powered admin dashboard for general management. You can download the app from the Google Play Store and try it out today. 

Restaurant App Template  - React Native

Restaurant Ionic

This app template is a cross-platform Ionic app template for a single restaurant. Some of the more interesting features include colour themes to choose from for app branding, Firebase back-end integration, categorized menus, restaurant finder with built-in map, special offers, and a shopping cart. 

For engagement, you can send push notifications, and the app includes social network integration so that users can view the restaurant's social media profile. You can download the Android apk file to check it out for yourself!

Restaurant Ionic App template

Crunchy - Restaurant Booking

This app template is packed with functionality that is needed for any restaurant app built on PhoneGap and the Ionic framework. This cross-platform app template features easy payment integration with PayPal and Stripe, social media login with Facebook or Google+, and a back-end platform built on the CodeIgniter PHP framework

An Android apk is available, so you can download an example app made with this template. Try it out, see how it feels, and then make your decision!

Crunchy Restaurant app

Caetano 

This is a very clean and easy-to-use Ionic 2 restaurant app template. Features include a splash screen, food menu, shopping cart, and user profile. This template does not come with any ready-made back-end, but you can easily implement your own service with the back-end provider of your choice. It's also easily customizable. Why don't you give it a shot by downloading the apk and see if it fits your needs? 

Caetano app template

Conclusion

App templates are a great way to jumpstart your next development project, or to learn from other people's work. This article lists just a few of the popular mobile app templates available on Envato Market. If you are looking for inspiration or you're building an application and need help with a particular feature, then you may find your answer in some of these templates.

Put one of these templates to use right now, or check out some of the other templates for complete apps available on CodeCanyon. Learn more about them right here on Envato Tuts+!

2017-03-09T13:49:05.000Z2017-03-09T13:49:05.000ZChike Mgbemena

Swift From Scratch: An Introduction to Functions

$
0
0

To get anything done in Swift, you need to learn the ins and outs of functions. Functions are exceptionally powerful and flexible in Swift. The basics are simple, especially if you've worked with other programming languages before. But because of Swift's flexible syntax, functions can become confusing if you're not familiar with the basics. 

In this article, we focus on the basics first. Then we'll go on to explore the more complex syntax and use cases in the next article. It's important that you don't skim the basics as they are essential to understand where a function's power comes from. Let's start by dissecting the anatomy of a function in Swift with an example.

1. Learn by Example

A function is nothing more than a block of code that can be executed whenever it's needed. Let's look at an example of the basic anatomy of a Swift function. Fire up Xcode and create a new playground. Add the following function definition to the playground.

A function begins with the func keyword and is followed by the name of the function, printHelloWorld in our example. As in many other languages, the name of the function is followed by a pair of parentheses that contain the function's parameters—the input to the function.

The body of the function is wrapped in a pair of curly braces. The printHelloWorld() function contains a single statement that prints the string Hello World! to the standard output. This is what a basic function looks like in Swift. The syntax is simple, clean, and minimalist.

You can invoke the function by typing the name of the function, followed by a pair of parentheses.

2. Parameters

Let's make the above example a bit more complex by adding parameters to the function definition. This simply means that we provide the function with input values it can use in the function's body. In the following example, we define the printMessage(message:) function, which accepts one parameter, message, of type String.

A function can accept multiple parameters or input values. The parameters are wrapped by the parentheses that follow the function's name. The name of the parameter is followed by a colon and the parameter's type. As you remember, this is very similar to declaring a variable or constant. It simply says that the message parameter is of typeString.

Instead of printing a hard-coded string as we did in the printHelloWorld() function, we print the message parameter's value. This makes the function flexible and more useful.

Invoking the function is very similar to what we saw earlier. The only difference is that we pass in an argument when invoking the function.

Note that the terms parameters and arguments are often used interchangeably, but there is a subtle, semantic difference in Swift. In Swift, parameters are the values specified in the function definition, while arguments are the values passed to the function when it is invoked.

Multiple Parameters

As I mentioned earlier, the syntax of functions is very flexible, and it shouldn't surprise you that it's perfectly possible to pass multiple arguments to a function. In the next example, we create a variation on the printMessage(message:times:) function that allows us to print the message multiple times.

While the name of the function is identical to that of the original printMessage(message:) function, the function's type is different. 

It's important you understand the previous sentence. Read it again.

Each function has a type, consisting of the parameter types and the return type. We'll explore return types in a moment. Functions can have the same name as long as their type is different, as shown by the previous two function definitions.

The type of the first function is (String) -> (), while the type of the second function is(String, Int) -> (). The name of both functions is the same. Don't worry about the -> symbol. Its meaning will become clear in a few moments when we discuss return types.

The second printMessage(message:times:) function defines two parameters, message of type String and times of type Int. This definition illustrates one of the features Swift has adopted from Objective-C, readable function and method names. While the name of the function is printMessage, it's easy to understand what the function is supposed to do by reading the names of the function's parameters.

In the second printMessage(message:times:) function, we create a for-in loop to print the message string times times. We use the half-open range operator, ..<, as we saw earlier in this series.

Invoking a Function

When we start typing printMessage in the playground, Xcode displays both functions in the autocompletion menu. Thanks to the function's type, it's easy to choose the function we're interested in. Calling the second printMessage(message:times:) function is as simple as:

Default Values

One of my favorite features is the ability to define default values for parameters. This may sound silly if you're coming from a language that has had this feature for ages, but this is pretty great if you've been working with C and Objective-C for many years.

In short, Swift allows developers to define default values for the parameters of a function. Let's define a new function that prints the current date in a specific format. Make sure you add the following import statement at the top of your playground to import the UIKit framework.

Let's first define the printDate(date:format:) function without making use of default values for any of the parameters.

If you're not familiar with the Foundation framework and you don't understand what's happening in the function body, then that's fine. The focus of this example isn't on the implementation of formatting a date. In printDate(date:format:), we use the value of the format parameter to format the value of date. If we don't pass in a value for the format parameter, the compiler throws an error.

A Function Argument Is Missing

We can remedy this by defining a default value for the function's second parameter, as shown in the updated function definition below.

Defining a default value is as simple as specifying a value in the list of parameters in the function's definition. The result is that the compiler no longer complains and the error disappears.

Even though we have specified a default value for the format parameter, we can still pass in a value if we want to.

Note that Apple recommends positioning parameters with a default value at the end of the list of parameters. This is certainly a good idea and common in most other programming languages that support optional parameters.

3. Return Type

The functions we've seen so far don't return anything to us when we invoke them. Let's make the printDate(date:format:) function more useful by returning the formatted date as a string, instead of printing the formatted date in the function's body. This requires two changes, as you can see below.

The first thing we change is the function's definition. After the list of parameters, we specify the return type, String. The return type is preceded by the -> symbol. If you've worked with CoffeeScript, then this will look familiar.

Instead of printing the formatted date using the print(_:separator:terminator:) function, we use the return keyword to return the value from the function. That's all we need to do. Let's try it out.

We invoke the printDate(date:format:) function, store the returned value in the constant formattedDate, and print the value of formattedDate in the standard output. Note that the name of the printDate(date:format:) function no longer reflects what it does, so you may want to change it to formatDate instead.

No Return Type

The other functions we've defined in this tutorial didn't have a return type. When a function doesn't have a return type, it isn't necessary to include the -> symbol in the function definition.

A few paragraphs earlier, I told you that none of the functions we had defined returned a value to us. That's actually not entirely true. Let me explain the nitty-gritty details with an experiment. Add the following line to your playground and see what happens.

The Compiler Shows a Warning

This is interesting. Swift doesn't have a problem that we store the return value of the printHelloWorld() function in a constant, but it does warn us that the type of the returned value is not what we might think it is.

What's happening here? Every function in Swift returns a value, even if we don't define a return type in the function definition. When a function doesn't explicitly specify a return type, the function implicitly returns Void, which is equivalent to an empty tuple, or () for short. You can see this in the playground's output pane and it is also mentioned in the warning the compiler outputs.

We can get rid of the above warning by explicitly declaring the type of value, an empty tuple. I agree that it's not very useful to store an empty tuple in a constant, but it illustrates to you that every function has a return value.

Tuples

Another great feature of Swift is the ability to return multiple values from a function by returning a tuple. The following example illustrates how this works. Let me repeat that it's not important that you understand how the timeComponentsForDate(date:) function does its job. The focus is the return value of the function, a tuple with three elements.

The function accepts one argument, a Date instance, and returns a tuple with three labeled values. Labeling the tuple's values is only for convenience; it is possible to omit the labels.

However, as the following example illustrates, labeling the values of the tuple returned from the function is very convenient and makes your code easier to understand.

It's also possible to return an optional value from a function if there are scenarios in which the function has no value to return. This is as simple as defining the return type of the function as optional, as shown below.

Conclusion

In this tutorial, we explored the basics of functions in Swift. It's important that you understand the syntax of functions, because in the next article we'll explore more advanced functions that build on what we covered in this tutorial.

I encourage you to read the article again if necessary and, more importantly, write a few functions in a playground to become familiar with the syntax. The basics are easy to understand, but you only get the hang of them by practicing.

If you want to learn how to use Swift 3 to code real-world apps, check out our course Create iOS Apps With Swift 3. Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. 

 


2017-03-10T19:15:24.948Z2017-03-10T19:15:24.948ZBart Jacobs
Viewing all 1836 articles
Browse latest View live