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

Tools for React Native Development

$
0
0

Tools, libraries, and services are an important part of every developer’s life, no matter which environment you’re developing for. And React Native is no exception. In this article, I’ll walk you through some of the best UI frameworks, libraries, components, development tools, and web services which will make you a happier and more productive React Native developer. 

Text Editors and IDEs

Visual Studio Code is a text editor which has built-in IntelliSense, debugging, and Git integration capabilities. What makes it really good for React Native development is its React Native tools extension. This allows you to execute React Native commands from the command palette, add IntelliSense for React Native APIs, and debug code within the editor itself. 

For more information regarding how to set up Visual Studio Code for React Native, check out this blog post: VSCode for React Native.

If you’re using Atom, you can install the Nuclide plugin. This plugin was specifically created for working with React Native, Flow, and Hack projects. It has a built-in debugger and element inspector with all the features you’re used to in Chrome Developer Tools. Flow support means that you get autocomplete, type-hinting, and code diagnostics out of the box. 

If you want to explore more IDE and editor options, check out this blog post on the Top 10 Editors for React Native.

Development Tools

Development tools have a wide scope, so I’ll be grouping each tool based on its focus:

  • SDK
  • code quality
  • testing
  • debugging

SDK

When it comes to SDKs for React Native, nothing beats Expo. Expo allows you to easily prototype an app without the need for Android Studio or Xcode. It includes a set of components and libraries to help you speed up your development. 

The Expo workflow consists of the following:

  1. Create a new project using create-react-native-app.
  2. Write the code in your favorite text editor.
  3. Run the app using the Expo client app. 

There’s no need to connect your phone to your computer. Simply scan the QR code on your terminal using the Expo client app, and it will automatically run your app. If you’re using Genymotion, Expo supports that too

The only disadvantage when using Expo is that you cannot include any custom package which uses the device’s native functionality. Expo already includes a number of commonly used native packages such as the Camera, Facebook, and Map. But if you need to use a package that they don’t already support, then you’ll have to "eject" your app. At that point your app will be as if it was created with react-native init, and you’ll also lose the ability to run it using the Expo client app.

Code Quality

Checking the quality of your code is important, and that is why tools like ESLint exist. In a nutshell, a linting tool allows you to be more consistent with your code by checking it against a style guide. An example of such a style guide is Airbnb’s JavaScript Style Guide which specifies rules on how JavaScript code should be written. The linting tool then checks your code against those rules to ensure that they've been followed. There’s also a style guide for React projects.

If you’re using Sublime Text, here’s a good tutorial on how you can configure it so that you can have real-time feedback on the quality of your code while you’re coding: Sublime Linting for React and ES6. If you’re using another editor or IDE, be sure to look for a corresponding plugin which uses ESLint.

If you want to add static typing to your project, you can use Flow. Flow adds static-typing on top of JavaScript without you having to make any changes to your existing codebase. This is because Flow tries to infer the type whenever possible. For new projects, though, it's recommended that you explicitly specify the type to reap the full benefits of using Flow.

To get started using Flow, here’s a tutorial on how you can set up Flow for your React Native projects.

Testing

Enzyme is a testing utility for React which allows you to assert, manipulate, and traverse your component’s output. It provides methods such as shallow() to "shallowly" render your components, find() to traverse the rendered component, and expect() to assert the props or the content rendered within the component.

You can follow this guide to Using enzyme to Test Components in React Native to make your React Native app testable with enzyme. If you’re new to enzyme, you can read this tutorial on Testing React Components with Enzyme and Mocha.

Debugging

Reactotron is a desktop app that allows you to debug React and React Native apps. Some of its key features include inspecting, modifying, and subscribing to the app state, tracking HTTP requests made through the app, benchmarking the app performance, and tracking errors. If you’re using Redux, you can even dispatch actions and track sagas from within Reactotron.

Boilerplates and UI Frameworks

Snowflake is a boilerplate for full-stack React Native development. It includes everything from the front-end to the back-end of the app. So if you just want a tool that can help you quickly get started then you might find Snowflake useful. You can read the notes for more information on what packages and tools are used to put it up.

Alternatively, you can use Ignite. It's a command-line tool which also includes a boilerplate, generators, style guide for UI components, API Testing Tool, and more. 

React Native already comes with UI components which you can use for user interaction. The problem is that they only have the most basic styling in order for each component to be distinguished for what it is (e.g. button, checkbox). If you want to add custom styles, you have to write your own CSS code. 

This is where NativeBase comes in. It allows your app to have a truly native look and feel by implementing the same design used in native Android (Material Design) and iOS (Human Interface Guidelines) apps. Out of the box, you get custom components such as Floating Action Buttons, Spinners, and best of all, form components.

Libraries and Components

React Native has a huge community behind it, so there are lots of libraries and components that you can use. We could spend all day talking about these, so to keep things brief, I’ll focus on the following areas:

  • navigation
  • state management
  • animations
  • commonly used components and libraries

Navigation

React Navigation allows you to easily implement navigation in your React Native apps through the use of its built-in navigators such as the Stack Navigator, Tab Navigator, and Drawer Navigator. That's not all, though: in addition to in-app navigation, it also includes deep linking, Redux integration, and web integration. This makes it a really robust library for implementing navigation.

State Management

MobX provides the functionality to update and manage the app state used by React. What makes it a good candidate for state management in React is its simplicity and testability. It also has a short learning curve, so things like async functions and computed values are already handled behind the scenes. 

For bigger and more complex applications, Redux is still recommended. This is because MobX is very liberal, not unlike Redux, which provides strict guidelines on how the state should be managed. So it's a wiser choice for bigger projects with more people working on them.

Animations

React Native already has an animation API built into it. In fact, there’s not just one, but two APIs for working with animation: Animated API and LayoutAnimation. Those two are very powerful but can be cumbersome, especially if all you want to do is apply basic animations such as moving an object up and down or making it bounce. In such cases, components like Animatable come in handy.

Commonly Used Components and Libraries

Here’s a list of components and libraries that are commonly used in React Native projects. These are compatible with both Android and iOS devices:

Web Services

You can build serverless apps and ease the deployment of your React Native apps by using web services. There are a plethora of web services out there, but I’ll focus on the following areas:

  • database
  • analytics
  • push notifications
  • code updates
  • continuous integration

Database

Realm is a real-time database with a focus on mobile apps. It includes features such as two-way data sync, offline-first capabilities, and data push. The Realm Mobile Database is open-source and cross-platform, which means that you can host the Realm Object Server on your own server and then use the Realm JavaScript library for free. 

Not all features are available in the developer edition, but in most use cases you should be fine with just the developer edition because it includes the core features such as the Object Database, Realtime Synchronization, and Authentication. Here's a comparison of what you get for each edition: Realm Products and Pricing.

If Realm is too much for your needs, you can always stick with the AsyncStorage API that comes with React Native.

Analytics

Fabric is an all-in-one service that allows you, among other things, to add analytics in your app. There’s Answers, which gives you real-time statistics on how your app is being used. This includes the number of active users, the session length, and retention rate. There’s also Crashlytics, which gives you powerful crash reporting capabilities. All of it happens in real time, and you can view it in Fabric’s real-time dashboard. You can use the Fabric library to easily set up Fabric for your React Native app.

If you’d rather stick with a tried and tested solution like Google Analytics, there’s also a library that allows you to do that.

Push Notifications

There’s really no competition when it comes to implementing push notifications in apps. Firebase Cloud Messaging (previously known as Google Cloud Messaging) allows you to send push notifications to both Android and iOS apps. You can use the react-native-fcm package to communicate with FCM from your app.

Code Updates

CodePush allows you to deploy code updates to mobile apps directly to the users’ devices. CodePush acts as a central repository where you can deploy changes to HTML, CSS, JavaScript, and assets such as images. The corresponding CodePush code in the app would then pull these changes. This is great for pushing bug fixes to the app without the need for uploading it in the app store and waiting for users to update the app. You can use this package to pull updates from CodePush within your React Native app.

Continuous Integration

Bitrise is a Continuous Delivery Service for mobile app development. It allows you to run your tests, build the app, and automatically push it to your users’ devices every time you deploy your code. 

Bitrise integrates with a bunch of services in every step of your development workflow. For example, when you push to your release branches on GitHub, Bitrise is notified of that push through webhooks. It will then begin running the tests. Once the tests pass, the build process begins. If it’s just a "soft release" (e.g. changes to the JavaScript code) then the changes can be deployed to the users through CodePush. But if there are changes to the native code (e.g. you added a Camera plugin), then Bitrise can also build an APK or IPA file and deploy it to Google Play or iTunes Connect.

Fastlane is a collection of tools that automate the build and release process for Android and iOS apps. For iOS, it handles tasks such as running your tests, generating screenshots, code signing, and releasing the app to the app store. It also includes beta testing tools such as Pilot and Boarding. Pilot allows you to upload your app to iTunes Connect and manage your TestFlight beta testers right from the command line. Boarding creates a signup page for TestFlight beta testers.

The tools are more geared towards iOS deployment, but you can also benefit if you’re deploying Android apps. Currently, there are only two tools available for Android deployment: Supply and Screengrab. 

Supply allows you to automate the uploading of assets such as the app icon, promo graphics, and screenshots of your app. It also allows you to update your existing apps on the Google Play Store. 

Screengrab, on the other hand, automates the generation of screenshots for multiple devices. Each screenshot can also be localized if your app supports multiple languages.

Conclusion

That’s it! In this article, you’ve learned about some of the tools, libraries, and services that you can use when developing React Native apps. What about you? What are your go-to tools when it comes to developing apps in React Native?

And while you're here, check out some of our other posts on React Native app development!

2017-10-25T08:00:00.000Z2017-10-25T08:00:00.000ZWernher-Bel Ancheta

Tools for React Native Development

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

Tools, libraries, and services are an important part of every developer’s life, no matter which environment you’re developing for. And React Native is no exception. In this article, I’ll walk you through some of the best UI frameworks, libraries, components, development tools, and web services which will make you a happier and more productive React Native developer. 

Text Editors and IDEs

Visual Studio Code is a text editor which has built-in IntelliSense, debugging, and Git integration capabilities. What makes it really good for React Native development is its React Native tools extension. This allows you to execute React Native commands from the command palette, add IntelliSense for React Native APIs, and debug code within the editor itself. 

For more information regarding how to set up Visual Studio Code for React Native, check out this blog post: VSCode for React Native.

If you’re using Atom, you can install the Nuclide plugin. This plugin was specifically created for working with React Native, Flow, and Hack projects. It has a built-in debugger and element inspector with all the features you’re used to in Chrome Developer Tools. Flow support means that you get autocomplete, type-hinting, and code diagnostics out of the box. 

If you want to explore more IDE and editor options, check out this blog post on the Top 10 Editors for React Native.

Development Tools

Development tools have a wide scope, so I’ll be grouping each tool based on its focus:

  • SDK
  • code quality
  • testing
  • debugging

SDK

When it comes to SDKs for React Native, nothing beats Expo. Expo allows you to easily prototype an app without the need for Android Studio or Xcode. It includes a set of components and libraries to help you speed up your development. 

The Expo workflow consists of the following:

  1. Create a new project using create-react-native-app.
  2. Write the code in your favorite text editor.
  3. Run the app using the Expo client app. 

There’s no need to connect your phone to your computer. Simply scan the QR code on your terminal using the Expo client app, and it will automatically run your app. If you’re using Genymotion, Expo supports that too

The only disadvantage when using Expo is that you cannot include any custom package which uses the device’s native functionality. Expo already includes a number of commonly used native packages such as the Camera, Facebook, and Map. But if you need to use a package that they don’t already support, then you’ll have to "eject" your app. At that point your app will be as if it was created with react-native init, and you’ll also lose the ability to run it using the Expo client app.

Code Quality

Checking the quality of your code is important, and that is why tools like ESLint exist. In a nutshell, a linting tool allows you to be more consistent with your code by checking it against a style guide. An example of such a style guide is Airbnb’s JavaScript Style Guide which specifies rules on how JavaScript code should be written. The linting tool then checks your code against those rules to ensure that they've been followed. There’s also a style guide for React projects.

If you’re using Sublime Text, here’s a good tutorial on how you can configure it so that you can have real-time feedback on the quality of your code while you’re coding: Sublime Linting for React and ES6. If you’re using another editor or IDE, be sure to look for a corresponding plugin which uses ESLint.

If you want to add static typing to your project, you can use Flow. Flow adds static-typing on top of JavaScript without you having to make any changes to your existing codebase. This is because Flow tries to infer the type whenever possible. For new projects, though, it's recommended that you explicitly specify the type to reap the full benefits of using Flow.

To get started using Flow, here’s a tutorial on how you can set up Flow for your React Native projects.

Testing

Enzyme is a testing utility for React which allows you to assert, manipulate, and traverse your component’s output. It provides methods such as shallow() to "shallowly" render your components, find() to traverse the rendered component, and expect() to assert the props or the content rendered within the component.

You can follow this guide to Using enzyme to Test Components in React Native to make your React Native app testable with enzyme. If you’re new to enzyme, you can read this tutorial on Testing React Components with Enzyme and Mocha.

Debugging

Reactotron is a desktop app that allows you to debug React and React Native apps. Some of its key features include inspecting, modifying, and subscribing to the app state, tracking HTTP requests made through the app, benchmarking the app performance, and tracking errors. If you’re using Redux, you can even dispatch actions and track sagas from within Reactotron.

Boilerplates and UI Frameworks

Snowflake is a boilerplate for full-stack React Native development. It includes everything from the front-end to the back-end of the app. So if you just want a tool that can help you quickly get started then you might find Snowflake useful. You can read the notes for more information on what packages and tools are used to put it up.

Alternatively, you can use Ignite. It's a command-line tool which also includes a boilerplate, generators, style guide for UI components, API Testing Tool, and more. 

React Native already comes with UI components which you can use for user interaction. The problem is that they only have the most basic styling in order for each component to be distinguished for what it is (e.g. button, checkbox). If you want to add custom styles, you have to write your own CSS code. 

This is where NativeBase comes in. It allows your app to have a truly native look and feel by implementing the same design used in native Android (Material Design) and iOS (Human Interface Guidelines) apps. Out of the box, you get custom components such as Floating Action Buttons, Spinners, and best of all, form components.

Libraries and Components

React Native has a huge community behind it, so there are lots of libraries and components that you can use. We could spend all day talking about these, so to keep things brief, I’ll focus on the following areas:

  • navigation
  • state management
  • animations
  • commonly used components and libraries

Navigation

React Navigation allows you to easily implement navigation in your React Native apps through the use of its built-in navigators such as the Stack Navigator, Tab Navigator, and Drawer Navigator. That's not all, though: in addition to in-app navigation, it also includes deep linking, Redux integration, and web integration. This makes it a really robust library for implementing navigation.

State Management

MobX provides the functionality to update and manage the app state used by React. What makes it a good candidate for state management in React is its simplicity and testability. It also has a short learning curve, so things like async functions and computed values are already handled behind the scenes. 

For bigger and more complex applications, Redux is still recommended. This is because MobX is very liberal, not unlike Redux, which provides strict guidelines on how the state should be managed. So it's a wiser choice for bigger projects with more people working on them.

Animations

React Native already has an animation API built into it. In fact, there’s not just one, but two APIs for working with animation: Animated API and LayoutAnimation. Those two are very powerful but can be cumbersome, especially if all you want to do is apply basic animations such as moving an object up and down or making it bounce. In such cases, components like Animatable come in handy.

Commonly Used Components and Libraries

Here’s a list of components and libraries that are commonly used in React Native projects. These are compatible with both Android and iOS devices:

Web Services

You can build serverless apps and ease the deployment of your React Native apps by using web services. There are a plethora of web services out there, but I’ll focus on the following areas:

  • database
  • analytics
  • push notifications
  • code updates
  • continuous integration

Database

Realm is a real-time database with a focus on mobile apps. It includes features such as two-way data sync, offline-first capabilities, and data push. The Realm Mobile Database is open-source and cross-platform, which means that you can host the Realm Object Server on your own server and then use the Realm JavaScript library for free. 

Not all features are available in the developer edition, but in most use cases you should be fine with just the developer edition because it includes the core features such as the Object Database, Realtime Synchronization, and Authentication. Here's a comparison of what you get for each edition: Realm Products and Pricing.

If Realm is too much for your needs, you can always stick with the AsyncStorage API that comes with React Native.

Analytics

Fabric is an all-in-one service that allows you, among other things, to add analytics in your app. There’s Answers, which gives you real-time statistics on how your app is being used. This includes the number of active users, the session length, and retention rate. There’s also Crashlytics, which gives you powerful crash reporting capabilities. All of it happens in real time, and you can view it in Fabric’s real-time dashboard. You can use the Fabric library to easily set up Fabric for your React Native app.

If you’d rather stick with a tried and tested solution like Google Analytics, there’s also a library that allows you to do that.

Push Notifications

There’s really no competition when it comes to implementing push notifications in apps. Firebase Cloud Messaging (previously known as Google Cloud Messaging) allows you to send push notifications to both Android and iOS apps. You can use the react-native-fcm package to communicate with FCM from your app.

Code Updates

CodePush allows you to deploy code updates to mobile apps directly to the users’ devices. CodePush acts as a central repository where you can deploy changes to HTML, CSS, JavaScript, and assets such as images. The corresponding CodePush code in the app would then pull these changes. This is great for pushing bug fixes to the app without the need for uploading it in the app store and waiting for users to update the app. You can use this package to pull updates from CodePush within your React Native app.

Continuous Integration

Bitrise is a Continuous Delivery Service for mobile app development. It allows you to run your tests, build the app, and automatically push it to your users’ devices every time you deploy your code. 

Bitrise integrates with a bunch of services in every step of your development workflow. For example, when you push to your release branches on GitHub, Bitrise is notified of that push through webhooks. It will then begin running the tests. Once the tests pass, the build process begins. If it’s just a "soft release" (e.g. changes to the JavaScript code) then the changes can be deployed to the users through CodePush. But if there are changes to the native code (e.g. you added a Camera plugin), then Bitrise can also build an APK or IPA file and deploy it to Google Play or iTunes Connect.

Fastlane is a collection of tools that automate the build and release process for Android and iOS apps. For iOS, it handles tasks such as running your tests, generating screenshots, code signing, and releasing the app to the app store. It also includes beta testing tools such as Pilot and Boarding. Pilot allows you to upload your app to iTunes Connect and manage your TestFlight beta testers right from the command line. Boarding creates a signup page for TestFlight beta testers.

The tools are more geared towards iOS deployment, but you can also benefit if you’re deploying Android apps. Currently, there are only two tools available for Android deployment: Supply and Screengrab. 

Supply allows you to automate the uploading of assets such as the app icon, promo graphics, and screenshots of your app. It also allows you to update your existing apps on the Google Play Store. 

Screengrab, on the other hand, automates the generation of screenshots for multiple devices. Each screenshot can also be localized if your app supports multiple languages.

Conclusion

That’s it! In this article, you’ve learned about some of the tools, libraries, and services that you can use when developing React Native apps. What about you? What are your go-to tools when it comes to developing apps in React Native?

And while you're here, check out some of our other posts on React Native app development!

2017-10-25T08:00:00.000Z2017-10-25T08:00:00.000ZWernher-Bel Ancheta

Mobile Development Tools

$
0
0

Traditional desktop app development is dominated by large-scale software companies with huge workforces, sometimes scattered around the globe. However, the mobile app development industry is quite different. Its ecosystem has created a new breed of small-scale and highly efficient developers. Its dominant players are powered by innovation and efficiency, rather than by the number of heads on the payroll. Even an individual developer can produce a killer app that has millions of downloads in the app stores.

So how do these individuals or small teams of developers achieve such great results, without a large human workforce? It's because the mobile app ecosystem has a broad range of software tools that simplify the workflow and improve efficiency. There are tools that even guarantee certain types of functionality, up to certain standards.

In this post, you'll be exposed to various mobile development tools that enable you to make your app unique and stand out from the rest. With these tools, you can achieve success even without a large team of programmers.

1. General-Purpose Tools

These include Software Development Kits (SDKs) that make it possible to develop for a specific platform such as Android, iOS, and Windows. In addition, Integrated Development Environments (IDEs) that help streamline the workflow also fall into this category.

1.1 Native Platform SDKs

An SDK usually consists of compiled core sources, supporting software libraries and various other components such as documentation, sample apps, etc., that are designed to facilitate app development. Platform SDKs can be defined as the immediately usable form of the platform's source code.

Android SDK & NDK

You can download Android SDK from the Android Developer website's Downloads section, free of charge. You just need to download the SDK command-line tools package that matches your OS and use the SDK Manager included there to download the other packages. Then, you can use this SDK to develop apps with or without the help of an Integrated Development Environment (IDE).

Unlike the SDK, which facilitates Java-based development, Android Native Development Kit (NDK) enables developers to implement their apps in the C or C++ languages. This comes in handy, especially when external libraries written in C or C++ are used within your app. Also, this ensures the fastest performance and maximum utilization of the device's hardware features. Therefore, if performance is the main criterion, you'd be better off using Android NDK.

You can find a large collection of Android tutorials on Envato Tuts+ that can help you get up and running in a flash.

iOS SDK

Similar to the Android SDK, you can download the iOS SDK, free of charge, once you register for an Apple Developer Center Account. However, you can't run the apps developed using that on an Apple device, unless you join the paid iOS Developer Program. However, you can still run your app on an emulator and test if it works correctly. 

When you are ready to run your app on a real device, you can join the Developer Program and eventually publish the app on the App Store. If you need more help on iOS development, check out our iOS From Scratch series.

Windows 10 SDK

Microsoft has unified the app development process for different devices including PC, Mobile, Xbox One, and HoloLens, with its Universal Windows Platform (UWP). You can download the Windows 10 SDK (also supports UWP) from Microsoft Windows Dev Center and use it for developing mobile apps with other tools, such as mobile emulators, to test your app. 

When used together with UWP, the Windows 10 SDK allows you to port your existing Android, iOS and older Windows apps to the latest Windows 10 platform. This is really great because it enables developers to expand their reach and target the broadest possible range of devices. Windows Phone SDK tutorials on Envato Tuts+ could be a great place to look for expert help.

1.2 Complete IDEs

IDEs help streamline your workflow and get the maximum out of the SDKs. They also save developers a great deal of time with clever features such as code completion, interactive debugging, and automated building.

Android Studio

Android Studio is the IDE officially supported by Google for building Android apps. It's an all-in-one IDE featuring intelligent code completion, fast and realistic device emulation, and robust build systems. You can share the same code base across many devices, ranging from wearables, through phones, to smart TVs. 

The latest Android SDK is also bundled with Android Studio so that developers can start coding from day one. The older versions of the SDK can be downloaded via the SDK Manager included in the IDE. It's also full of sample apps, code templates, and project wizards that make life really easy for developers.

Xcode

If you are an iOS developer, you must get yourself familiar with Xcode, which includes the iOS SDK and a number of other useful tools. Similar to Android Studio, it's a productive environment for building apps for Mac, iPhone, iPad, and Apple Watch. Xcode's features include a powerful source-code editor, built-in interface builder, advanced device emulator, and complete, up-to-date documentation. 

Anyway, you don't have much choice, because it's mandatory to use the Xcode IDE if you plan to publish your iOS apps to Apple's App Store. Xcode handles all the app signing and developer-key management, plus the verification process for app submission, so that developers can focus more on their core business rather than worrying about their apps' administrative overheads.

Visual Studio

Visual Studio is the IDE of choice for Windows developers. It's from Microsoft, and therefore, you'll get the full support that you'd expect from the official vendor. With Visual Studio, you can use the same code base for desktop apps, mobile apps, and other Microsoft device-based apps. 

Naturally, the Windows 10 SDK is bundled with the IDE, as in the case of Android Studio and Xcode. Visual Studio makes it easy for developers to find their way around a large code base with features such as Peek To Definition, improved GoTo, and more. Depending on your capacity and budget, you can select from three versions, namely Community, Professional, and Enterprise. Also, Visual Studio comes with two OS flavors, Windows and Mac. So it doesn't matter whether you own a PC or a Mac; you can use Visual Studio to code your next mobile app.

Not only that, but Visual Studio Code is a great IDE for coding cross-platform apps in JavaScript—for React Native, for example. Visual Studio Code is especially good for React Native development with the React Native tools extension. With that, you can run React Native commands from the GUI, view smart code completion prompts for React Native APIs, and even debug your apps from within the editor.

2. Special-Purpose Tools

These are the tools that enable your app to have a competitive advantage. That's really what it takes to build a killer app or a niche market. Here, you'll read about the most popular ones.

2.1 Game Engines

Mobile games are the most popular app category, in terms of download volume, on almost all the app stores. So, if you're planning to develop a mobile game, why not try one of these game engines?

Unity

Unity is a popular game development tool that can be used for creating a compelling user experience. Its features include an all-in-one editor, 2D and 3D workflow support, realistic physics engine, built-in UI creation components, and a lot more. Based on the size of your game development studio, you can choose a suitable version from Personal, Plus, or Pro. 

Unity allows you to maintain a single code base and publish to multiple platforms such as Android, iOS, and Windows Phone. Unity is essentially packed with tons of features such as 360 panoramic video support, cinematic VR, and photo- or video-based asset creation. It even has its own mobile app monetization platform with Unity Ads.

Godot

Released under the MIT license, Godot is a free and open-source game creation tool that enables you to publish 2D and 3D games to all the popular mobile platforms. You can write your programs either with its default scripting language called GDScript or in the C++ language. It also has a nice visual editor with an uncluttered UI. What's really interesting is that it supports live editing on mobile devices too.

libGDX

libGDX is a game engine with multiple publishing targets including Android and iOS. It's released under the Apache 2.0 license and maintained by an active community of talented developers. It also comes with a large collection of books and tutorials, so that it's really easy for you to get started and continue.

2.2 Computer Vision SDKs

Computer vision has made remarkable progress since its early days of conception. Now it's become such a commodity that there are thousands of apps that use some form of computer vision. The availability of the built-in camera has made computer vision-based mobile apps a widespread type of software.

IBM Watson

IBM Watson is a cloud-based suite of machine-learning tools. With its Visual Recognition service, detecting and analyzing images from a smartphone app is actually quite easy. Check out some of our Watson tutorials here on Envato Tuts+. You can even use it to guess a person's age and gender from a photograph.

Google Cloud Vision

Google Cloud Vision is another cloud-based machine learning platform that makes computer vision easier. Through the Cloud Vision REST API, Google shares its deep learning AI technology with app developers everywhere. With this API, you can easily add features such as face detection, emotion detection, and optical character recognition to your Android apps. In this tutorial, you'll learn how.

OpenCV

OpenCV was one of the early adopters of computer vision technology, and today it's one of the leaders in the field. There are several other projects, some open source, and other commercial ones, based on OpenCV. It's available for Android, iOS, and Windows platforms. In Android, you'll need Android NDK to use it. 

OpenCV itself is written in C++, and you'll need to brush up your C++ skills if you intend to write programs using the SDK. You'll be able to add a wide range of computer vision based features to your app using OpenCV. They include face recognition, eye tracking and gaze estimation, object recognition, and a lot more related to both still images and videos. OpenCV is released under the BSD license and is completely free to use.

Qualcomm FastCV

Released by Qualcomm Technologies Inc., FastCV is another popular computer vision based SDK. It supports features like gesture recognition, face detection, tracking, and text recognition. Although FastCV can perform reasonably well on most ARM-based processors, it's specifically designed for Qualcomm Snapdragon processors. A high-end processor is needed to fully utilize FastCV's capabilities.

2.3 Augmented Reality (AR) SDKs

AR is slowly gaining traction and becoming more of a day-to-day mobile experience, thanks to some state-of-the-art SDKs and enthusiastic developer communities. Here are some of the leaders and trendsetters in the industry.

Vuforia

Vuforia is a widely used mobile AR platform that can support a broad range of Android, iOS, and Windows smartphones and tablets. It helps you create memorable AR experiences in mobile apps, so that those apps can stand out from the rest. 

Vuforia can cater to a variety of AR use cases such as print media and magazines, toys and consumer products, boxes and product packaging, and even bottles and cans. It also supports object recognition and object tracking and enables developers to create AR and VR apps by using its Mixed Reality API. You can choose from four available pricing plans depending on your requirements.

Wikitude

Another serious player in the field, Wikitude combines mobile geo-location with other standard AR features. So it must be another essential tool for any aspiring developer who wants to produce really cool mobile AR apps. The SDK comes with different options for licensing, such as a one-time fee and yearly subscription-based models. 

Wikitude can currently deploy to Android and iOS mobile targets. Its community is also full of seasoned developers who are ready to share their knowledge, and hence you could take a shortcut to accelerate your development efforts to full speed.

Tango

Tango is an AR SDK developed by Google. It currently supports only two specific device models, namely Asus ZenFone AR and Lenovo Phab 2 Pro. So, if you are interested in specifically developing for any of those devices, Tango is worth considering.

ARKit

ARKit is the AR platform of Apple. You'll need to get Xcode 9, in which ARKit is included as part of the iOS 11 SDK. So, if you don't want to mess up with third-party tools and prefer to focus only on official Apple tools, ARKit is ideal for you.

Stay tuned to Envato Tuts+ for courses and tutorials about ARKit!

3. Hybrid Development Tools

Some novice developers are intimidated by the steep learning curve normally associated with native mobile development platforms. They might have to learn new programming languages and acquire platform-specific development skills, such as mastering the testing tools. 

Hybrid development tools address this issue in a clever manner. They enable developers with web development skills to develop mobile apps—without needing platform-specific knowledge. There are many such platforms available, but we'll focus only on a few popular ones.

React Native

React Native is a mobile development platform released by Facebook. It allows developers to publish native mobile apps using HTML, CSS, and JavaScript. You can maintain a single code base and publish your app on the Android or iOS platforms. 

It's wonderful since you don't have to install Android Studio or Xcode on your development machine. And the real fun begins when you switch to native code within the React Native code editor itself. You can mix code snippets from several native platforms in the same code editor, and that makes you really powerful and versatile.

Ionic

Ionic is another framework that lets you build mobile apps with HTML, CSS, and JavaScript. It comes out of the gate with a library of UI components and lots of handy utilities that let you code beautiful mobile apps. Ionic is built on top of the very popular Angular framework, so if you have experience with Angular, you'll find Ionic a snap.

NativeScript

NativeScript is another framework for building cross-platform mobile apps. Like Ionic and React Native, it allows you to use CSS and JavaScript to build mobile apps, but instead of HTML you code your app layouts in XML. 

NativeScript can target Android, iOS, and even the Windows Universal Platform. Unlike Ionic, which uses Cordova's WebView for rendering the UI of the app, NativeScript uses the native platform's rendering engine, which means that it provides a truly native user experience. 

Adobe PhoneGap

PhoneGap was one of the pioneers of HTML-based hybrid mobile development frameworks. Since being acquired by Adobe in 2011, it's just gotten better and better. 

The quickest way to get started is to download the PhoneGap desktop app and dive into coding. You can emulate apps in your browser, and you can also perform live testing on connected devices, using the PhoneGap Developer Mobile App. It can serve all the three popular platforms: Android, iOS, and Windows Phone. 

If you encounter a problem while writing your app, there are thousands of posts and articles on the web that will help you fix the issues. PhoneGap has a thriving community of developers who are really knowledgeable and helpful.

Xamarin

Xamarin is another hybrid mobile development tool, but it's based on C#, instead of HTML. So, if you are coming from a Microsoft development background and want to develop cross-platform mobile apps, it's an ideal choice. You'll also need Visual Studio IDE when you develop mobile apps with Xamarin.

Conclusion

The availability of the right tools and the ability to use them correctly are the key success factors of mobile app development. So, when you plan to develop your next app, give these tools a try. 

2017-10-26T12:00:00.000Z2017-10-26T12:00:00.000ZBala Durage Sandamal Siripathi

Mobile Development Tools

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

Traditional desktop app development is dominated by large-scale software companies with huge workforces, sometimes scattered around the globe. However, the mobile app development industry is quite different. Its ecosystem has created a new breed of small-scale and highly efficient developers. Its dominant players are powered by innovation and efficiency, rather than by the number of heads on the payroll. Even an individual developer can produce a killer app that has millions of downloads in the app stores.

So how do these individuals or small teams of developers achieve such great results, without a large human workforce? It's because the mobile app ecosystem has a broad range of software tools that simplify the workflow and improve efficiency. There are tools that even guarantee certain types of functionality, up to certain standards.

In this post, you'll be exposed to various mobile development tools that enable you to make your app unique and stand out from the rest. With these tools, you can achieve success even without a large team of programmers.

1. General-Purpose Tools

These include Software Development Kits (SDKs) that make it possible to develop for a specific platform such as Android, iOS, and Windows. In addition, Integrated Development Environments (IDEs) that help streamline the workflow also fall into this category.

1.1 Native Platform SDKs

An SDK usually consists of compiled core sources, supporting software libraries and various other components such as documentation, sample apps, etc., that are designed to facilitate app development. Platform SDKs can be defined as the immediately usable form of the platform's source code.

Android SDK & NDK

You can download Android SDK from the Android Developer website's Downloads section, free of charge. You just need to download the SDK command-line tools package that matches your OS and use the SDK Manager included there to download the other packages. Then, you can use this SDK to develop apps with or without the help of an Integrated Development Environment (IDE).

Unlike the SDK, which facilitates Java-based development, Android Native Development Kit (NDK) enables developers to implement their apps in the C or C++ languages. This comes in handy, especially when external libraries written in C or C++ are used within your app. Also, this ensures the fastest performance and maximum utilization of the device's hardware features. Therefore, if performance is the main criterion, you'd be better off using Android NDK.

You can find a large collection of Android tutorials on Envato Tuts+ that can help you get up and running in a flash.

iOS SDK

Similar to the Android SDK, you can download the iOS SDK, free of charge, once you register for an Apple Developer Center Account. However, you can't run the apps developed using that on an Apple device, unless you join the paid iOS Developer Program. However, you can still run your app on an emulator and test if it works correctly. 

When you are ready to run your app on a real device, you can join the Developer Program and eventually publish the app on the App Store. If you need more help on iOS development, check out our iOS From Scratch series.

Windows 10 SDK

Microsoft has unified the app development process for different devices including PC, Mobile, Xbox One, and HoloLens, with its Universal Windows Platform (UWP). You can download the Windows 10 SDK (also supports UWP) from Microsoft Windows Dev Center and use it for developing mobile apps with other tools, such as mobile emulators, to test your app. 

When used together with UWP, the Windows 10 SDK allows you to port your existing Android, iOS and older Windows apps to the latest Windows 10 platform. This is really great because it enables developers to expand their reach and target the broadest possible range of devices. Windows Phone SDK tutorials on Envato Tuts+ could be a great place to look for expert help.

1.2 Complete IDEs

IDEs help streamline your workflow and get the maximum out of the SDKs. They also save developers a great deal of time with clever features such as code completion, interactive debugging, and automated building.

Android Studio

Android Studio is the IDE officially supported by Google for building Android apps. It's an all-in-one IDE featuring intelligent code completion, fast and realistic device emulation, and robust build systems. You can share the same code base across many devices, ranging from wearables, through phones, to smart TVs. 

The latest Android SDK is also bundled with Android Studio so that developers can start coding from day one. The older versions of the SDK can be downloaded via the SDK Manager included in the IDE. It's also full of sample apps, code templates, and project wizards that make life really easy for developers.

Xcode

If you are an iOS developer, you must get yourself familiar with Xcode, which includes the iOS SDK and a number of other useful tools. Similar to Android Studio, it's a productive environment for building apps for Mac, iPhone, iPad, and Apple Watch. Xcode's features include a powerful source-code editor, built-in interface builder, advanced device emulator, and complete, up-to-date documentation. 

Anyway, you don't have much choice, because it's mandatory to use the Xcode IDE if you plan to publish your iOS apps to Apple's App Store. Xcode handles all the app signing and developer-key management, plus the verification process for app submission, so that developers can focus more on their core business rather than worrying about their apps' administrative overheads.

Visual Studio

Visual Studio is the IDE of choice for Windows developers. It's from Microsoft, and therefore, you'll get the full support that you'd expect from the official vendor. With Visual Studio, you can use the same code base for desktop apps, mobile apps, and other Microsoft device-based apps. 

Naturally, the Windows 10 SDK is bundled with the IDE, as in the case of Android Studio and Xcode. Visual Studio makes it easy for developers to find their way around a large code base with features such as Peek To Definition, improved GoTo, and more. Depending on your capacity and budget, you can select from three versions, namely Community, Professional, and Enterprise. Also, Visual Studio comes with two OS flavors, Windows and Mac. So it doesn't matter whether you own a PC or a Mac; you can use Visual Studio to code your next mobile app.

Not only that, but Visual Studio Code is a great IDE for coding cross-platform apps in JavaScript—for React Native, for example. Visual Studio Code is especially good for React Native development with the React Native tools extension. With that, you can run React Native commands from the GUI, view smart code completion prompts for React Native APIs, and even debug your apps from within the editor.

2. Special-Purpose Tools

These are the tools that enable your app to have a competitive advantage. That's really what it takes to build a killer app or a niche market. Here, you'll read about the most popular ones.

2.1 Game Engines

Mobile games are the most popular app category, in terms of download volume, on almost all the app stores. So, if you're planning to develop a mobile game, why not try one of these game engines?

Unity

Unity is a popular game development tool that can be used for creating a compelling user experience. Its features include an all-in-one editor, 2D and 3D workflow support, realistic physics engine, built-in UI creation components, and a lot more. Based on the size of your game development studio, you can choose a suitable version from Personal, Plus, or Pro. 

Unity allows you to maintain a single code base and publish to multiple platforms such as Android, iOS, and Windows Phone. Unity is essentially packed with tons of features such as 360 panoramic video support, cinematic VR, and photo- or video-based asset creation. It even has its own mobile app monetization platform with Unity Ads.

Godot

Released under the MIT license, Godot is a free and open-source game creation tool that enables you to publish 2D and 3D games to all the popular mobile platforms. You can write your programs either with its default scripting language called GDScript or in the C++ language. It also has a nice visual editor with an uncluttered UI. What's really interesting is that it supports live editing on mobile devices too.

libGDX

libGDX is a game engine with multiple publishing targets including Android and iOS. It's released under the Apache 2.0 license and maintained by an active community of talented developers. It also comes with a large collection of books and tutorials, so that it's really easy for you to get started and continue.

2.2 Computer Vision SDKs

Computer vision has made remarkable progress since its early days of conception. Now it's become such a commodity that there are thousands of apps that use some form of computer vision. The availability of the built-in camera has made computer vision-based mobile apps a widespread type of software.

IBM Watson

IBM Watson is a cloud-based suite of machine-learning tools. With its Visual Recognition service, detecting and analyzing images from a smartphone app is actually quite easy. Check out some of our Watson tutorials here on Envato Tuts+. You can even use it to guess a person's age and gender from a photograph.

Google Cloud Vision

Google Cloud Vision is another cloud-based machine learning platform that makes computer vision easier. Through the Cloud Vision REST API, Google shares its deep learning AI technology with app developers everywhere. With this API, you can easily add features such as face detection, emotion detection, and optical character recognition to your Android apps. In this tutorial, you'll learn how.

OpenCV

OpenCV was one of the early adopters of computer vision technology, and today it's one of the leaders in the field. There are several other projects, some open source, and other commercial ones, based on OpenCV. It's available for Android, iOS, and Windows platforms. In Android, you'll need Android NDK to use it. 

OpenCV itself is written in C++, and you'll need to brush up your C++ skills if you intend to write programs using the SDK. You'll be able to add a wide range of computer vision based features to your app using OpenCV. They include face recognition, eye tracking and gaze estimation, object recognition, and a lot more related to both still images and videos. OpenCV is released under the BSD license and is completely free to use.

Qualcomm FastCV

Released by Qualcomm Technologies Inc., FastCV is another popular computer vision based SDK. It supports features like gesture recognition, face detection, tracking, and text recognition. Although FastCV can perform reasonably well on most ARM-based processors, it's specifically designed for Qualcomm Snapdragon processors. A high-end processor is needed to fully utilize FastCV's capabilities.

2.3 Augmented Reality (AR) SDKs

AR is slowly gaining traction and becoming more of a day-to-day mobile experience, thanks to some state-of-the-art SDKs and enthusiastic developer communities. Here are some of the leaders and trendsetters in the industry.

Vuforia

Vuforia is a widely used mobile AR platform that can support a broad range of Android, iOS, and Windows smartphones and tablets. It helps you create memorable AR experiences in mobile apps, so that those apps can stand out from the rest. 

Vuforia can cater to a variety of AR use cases such as print media and magazines, toys and consumer products, boxes and product packaging, and even bottles and cans. It also supports object recognition and object tracking and enables developers to create AR and VR apps by using its Mixed Reality API. You can choose from four available pricing plans depending on your requirements.

Wikitude

Another serious player in the field, Wikitude combines mobile geo-location with other standard AR features. So it must be another essential tool for any aspiring developer who wants to produce really cool mobile AR apps. The SDK comes with different options for licensing, such as a one-time fee and yearly subscription-based models. 

Wikitude can currently deploy to Android and iOS mobile targets. Its community is also full of seasoned developers who are ready to share their knowledge, and hence you could take a shortcut to accelerate your development efforts to full speed.

Tango

Tango is an AR SDK developed by Google. It currently supports only two specific device models, namely Asus ZenFone AR and Lenovo Phab 2 Pro. So, if you are interested in specifically developing for any of those devices, Tango is worth considering.

ARKit

ARKit is the AR platform of Apple. You'll need to get Xcode 9, in which ARKit is included as part of the iOS 11 SDK. So, if you don't want to mess up with third-party tools and prefer to focus only on official Apple tools, ARKit is ideal for you.

Stay tuned to Envato Tuts+ for courses and tutorials about ARKit!

3. Hybrid Development Tools

Some novice developers are intimidated by the steep learning curve normally associated with native mobile development platforms. They might have to learn new programming languages and acquire platform-specific development skills, such as mastering the testing tools. 

Hybrid development tools address this issue in a clever manner. They enable developers with web development skills to develop mobile apps—without needing platform-specific knowledge. There are many such platforms available, but we'll focus only on a few popular ones.

React Native

React Native is a mobile development platform released by Facebook. It allows developers to publish native mobile apps using HTML, CSS, and JavaScript. You can maintain a single code base and publish your app on the Android or iOS platforms. 

It's wonderful since you don't have to install Android Studio or Xcode on your development machine. And the real fun begins when you switch to native code within the React Native code editor itself. You can mix code snippets from several native platforms in the same code editor, and that makes you really powerful and versatile.

Ionic

Ionic is another framework that lets you build mobile apps with HTML, CSS, and JavaScript. It comes out of the gate with a library of UI components and lots of handy utilities that let you code beautiful mobile apps. Ionic is built on top of the very popular Angular framework, so if you have experience with Angular, you'll find Ionic a snap.

NativeScript

NativeScript is another framework for building cross-platform mobile apps. Like Ionic and React Native, it allows you to use CSS and JavaScript to build mobile apps, but instead of HTML you code your app layouts in XML. 

NativeScript can target Android, iOS, and even the Windows Universal Platform. Unlike Ionic, which uses Cordova's WebView for rendering the UI of the app, NativeScript uses the native platform's rendering engine, which means that it provides a truly native user experience. 

Adobe PhoneGap

PhoneGap was one of the pioneers of HTML-based hybrid mobile development frameworks. Since being acquired by Adobe in 2011, it's just gotten better and better. 

The quickest way to get started is to download the PhoneGap desktop app and dive into coding. You can emulate apps in your browser, and you can also perform live testing on connected devices, using the PhoneGap Developer Mobile App. It can serve all the three popular platforms: Android, iOS, and Windows Phone. 

If you encounter a problem while writing your app, there are thousands of posts and articles on the web that will help you fix the issues. PhoneGap has a thriving community of developers who are really knowledgeable and helpful.

Xamarin

Xamarin is another hybrid mobile development tool, but it's based on C#, instead of HTML. So, if you are coming from a Microsoft development background and want to develop cross-platform mobile apps, it's an ideal choice. You'll also need Visual Studio IDE when you develop mobile apps with Xamarin.

Conclusion

The availability of the right tools and the ability to use them correctly are the key success factors of mobile app development. So, when you plan to develop your next app, give these tools a try. 

2017-10-26T12:00:00.000Z2017-10-26T12:00:00.000ZBala Durage Sandamal Siripathi

Updating Your App for iOS 11

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

In addition to feature development and bug fixes, iOS developers have to keep tabs on what’s announced yearly at WWDC. Amidst the notable new SDKs announced, there are some changes that iOS devs will need to roll out to keep their apps platform-compliant.

With Swift having evolved to version 4, along with improvements and changes coming to the iOS SDK itself, developers need to sift through the changes and devise a strategy for updating their code bases. All without breaking any of their existing features and functionalities! It all comes down to prioritization for your project: what is the minimum you need to do in order to make your app iOS 11 compliant? What is the easiest case you can make to your project stakeholder or project manager?

Vital features come first, and next come the nice-to-have but not required improvements that iOS 11 brings, from optimizing your application to the visual aesthetics that will further enrich the interaction and functionality of your app. With that in mind, this tutorial will guide you through the steps to take to upgrade your app, taking a pragmatic approach to required and optional improvements. 

Objectives of This Tutorial

This article will provide you with an overview of the changes that will be required in order to update your app for iOS 11, from architectural to visual changes as well as App Store publishing changes. Moreover, this tutorial will organize the sections starting from the required changes needed and the scope and effort required, to the nice but not necessary features that will enhance your app as a result of iOS 11. 

In this tutorial we will be covering the following:

  • preparing your app (and yourself) for iOS 11
  • architectural changes
  • App Store publishing changes
  • UI changes

Assumed Knowledge

This tutorial assumes an intermediate knowledge of Swift or Objective-C and Xcode, as well as familiarity with core iOS SDKs (e.g. UIKit and Core Foundation).

Architectural Changes

As with every iteration of iOS, the most important changes usually are the architectural ones. With iOS 11, this involves migrating to Swift 4, so updating the build settings for Xcode 9 will be the first task we'll look at. 

Incremental Migrating to Swift 4 

Important | Required

For those who had to migrate from Swift 2 to 3 last year, that process was extremely painful, and a lot of the changes broke the existing codebase. Thankfully, this isn’t the case moving from Swift 3.2 to 4, as most of the chances are considered additive, rather than deprecating, and as a result the Xcode 9 migration tool performs an admirable job of transitioning your code to the latest Swift.

Moreover, unlike in previous versions, you are not going to be forced to do the upgrade to 4 in one go. That is, Xcode projects simultaneously support both Swift 4 and Swift 3.2, which means that you can have one target in your project compile under Swift 3.2 and another compile in Swift 4. The migration tool will let you know which classes and functions it successfully migrated, and which ones will require your manual intervention to resolve, in the form of errors or warnings. 

The errors mean you will need to fix something that isn’t backward-compatible, whereas many of the warnings will indicate that there is a new way in Swift 4 of doing something, such as new API changes. Fix the errors, and prioritize the aforementioned warnings as a separate task. 

To access the migration tool, go to Edit > Convert > To Current Swift Syntax in Xcode, and follow the prompts, selecting the target(s) you wish to migrate at this stage. 

The Xcode Migration Tool modal prompt screen

The migration tool will let you know the minimum work that you will need to do in order to recompile your app, and therefore it should come as no surprise that the recommended best practice is to work on migrating your app from 3 to 4 incrementally, especially in large projects, testing and converting target by target. You won’t have to migrate everything at once, and you can plan your migration path in stages, where and when needed. 

We will next take a quick look at what the changes are in Swift 4 that are not mandatory to implement, but good to know. 

32-Bit Architectural Deprecation

Important | Required

Another major change in iOS 11 is that all apps in the App Store now have to be 64-bit, as 32-bit apps are no longer supported, and as a matter of fact don’t even work on devices running iOS 11. This shouldn’t come as a surprise as Apple have been warning developers for quite a while, but in case your app has still not made its transition, you can follow Apple’s guidelines on Converting Your App to a 64-bit Binary.

What’s New in Swift 4

Not Important | Optional

Beyond the mandatory work needed in order to get your target to become Swift 4 compliant, you have the option of refactoring your existing code to leverage the new Swift API changes, which are broken down according to the following API-level improvements:

Strings

String has received a lot of attention in Swift 4, with the most notable change being a reversion back to Swift 1.0 where Strings are once again defined as collections, so you can iterate over a String object character by character (SE-0163) using a for loop. Other notable changes to the Strings class include: 

Collections

Dictionaries and sets, as part of collections, have also been revamped in Swift 4, starting with the filtering of dictionaries, which until now returned an array of tuples consisting of key/value pairs. To access a specific element, you would use the following subscript, as in an array:

In Swift 4, you get back a dictionary instead, providing a more consistent syntax, and subsequently, you access the returned dictionary as you would a normal dictionary. The same now occurs for the map() function, where you also get back a dictionary. New to dictionary-access subscripts, you can provide a default value in case the key doesn’t exist, making your code safer.

The rest of the changes for collections include:

Other Notable Changes

Finally, there are some miscellaneous changes worth noting as part of this release pertaining to the language: 

You can find the exhaustive list of changes and original proposals at Swift.org.

App Store Publishing Changes

iOS 11 users of the App Store would have already noticed that it is sporting a completely new design with whole new sections, providing developers with new ways in which they can promote their apps and communicate with their users.

The new App Store Today Screen source Apple

We will start off by taking a look at the new marketing icon that you will now be required to upload with your app updates.

Marketing Icon

Mandatory | Higher Priority

As of iOS 11, for any new submissions, whether your app is new or an existing one, you will need to include an icon-1024.png—a 1024x1024 sized marketing icon. Conveniently enough, you won’t need to submit the icon via iTunes Connect, but through Xcode, bygoing to Images.xcassets and adding the appropriately sized image, the same way you manage your other icons:

You add the Marketing Icon in Xcode

The marketing icon is used as part of the new App Store design process, to show a larger image icon representing your app in the Today section, or other sections where the app graphic is enlarged. 

Promoting In-App Purchases

Optional | Lower Priority

Apple has made the process of in-app purchases more prominent and transparent, allowing users to view all the in-app purchasing options directly via the same level as the app product display, and in fact, even initiate an in-app purchase for the app whilst downloading the actual app. Think of a subscription app where users who download your app may already want to purchase their subscription. iOS 11 makes this quicker and more convenient. 

As of iOS 11, developers are able to promote up to 20 in-app purchases such as subscriptions on their app’s product page. These purchase options will also appear in search results. 

Promoting in-app purchases can also encourage downloads of your app. When a user doesn’t have your app installed but wants to buy a promoted in-app purchase, they'll receive a prompt to download the app first. Once the app is downloaded, the transaction will continue in the app. (Apple)

Marketing in-app purchases more visibly in the App Store source Apple

To enable greater in-app purchase promotion visibility, in iTunes Connect you will need to include the following metadata: 

  • Image: This is the unique promotional image representing your in-app purchase, appearing on your App Store product page, Today, Games, and Apps tabs, as well as other prominent areas. This should not consist of a screenshot or represent your app’s icon, but rather represent what the in-app purchase does. The image should also be in PNG format, and high quality with dimensions of 1024 x 1024.
  • Name: The display name of the in-app purchase, consisting of a maximum of 30 characters. This should be specific, befitting the function of that specific in-app purchase. If it is a subscription, say so, and ensure the duration of the subscription is included in the title, such as “One Month All-Access Subscription”.
  • Description: 45 characters long, descriptions provide context for the users to understand and appreciate the benefits of your specific in-app offering. 

For more information on promoting your in-app purchase, refer to Apple’s official guidelines as well as Apple’s Product Page guidelines.

Communicating With Your Customers

Optional | Lower Priority

Something that is definitely long overdue, and Android developers have enjoyed for quite some time, is the ability to respond directly to user comments. As of iOS 11, developers can now also directly respond to their users’ reviews and comments. While this doesn’t require any technical changes and participation is optional, developers through iTunes Connect (App > Activity > Ratings) can respond to praise as well as criticism.

Developers can now respond to comments and reviews in the App Store source Apple

Individualized developer responses can be leveraged in order to build stronger and more intimate relationships, fostering deeper engagement, by showing that their feedback is being reviewed and responded to, and issues they raised are actively being listened to. To respond to comments, simply go to iTunes Connect where you can view the feedback and respond individually. 

Besides the new developer comments feature, Apple have also provided a new formalized SDK to prompt users to rate and review apps. The new SKStoreReviewController should be used instead of any third party or manual prompting of users for reviews, because Apple wants the operating system to be able to control the frequency of the prompts as well as their visual appearance. Apple will thus constrain prompts to no more than three times in a 365-day period. 

To implement SKStoreReviewController, simply import StoreKit and call requestReview() as shown below:

While Apple hasn’t outright banned the other methods of prompting users for feedback, expect this to change in the near future, so it's best that you start thinking of implementing Apple’s prompt-to-review engine over the next year.

Refer to Apple’s Ratings, Reviews and Responses guidelines for more information. 

Incremental Rollouts

Optional | Lower Priority

Another very useful feature iOS 11 brings to developers is the ability to release their apps to users incrementally. Apple calls this phased releasing, and it's intended to reduce the risk of overloading the production environment all at once, instead rolling out the release updates over a seven-day period. 

Developers can now roll-out an app in phases over a 7-day period

Under Version Release in iTunes Connect, there is a new section called Phased Release for Automatic Updates, which gives you the option of either releasing immediately or over the seven-day period. Developers are also able to halt the phased roll-out for up to 30 days, which would normally happen if a major issue is discovered and reported.

A chart demonstrating the percentage of users receiving the app split over a 7-day period

The phased roll-out doesn’t prevent users from getting the update manually from the App Store, but rather is targeted at users who use the iOS automatic download setting in the App Store. 

Next, let’s take a look at the visual changes that were introduced as part of iOS 11, as we go through the important as well as the less important topics. 

UI Changes

After looking at the architectural as well as the app store publishing changes for iOS 11, we are now ready to dissect the visual changes and help you prioritize what UI changes should be tackled first. 

Importantly, while we certainly could build our iOS apps without implementing any of the changes in this section, addressing only the architectural and App Store changes, you may first want to ensure that your app visually supports the new iPhone X. This means changes to the navigation bars to address the new physical ‘notch’ at the top. 

With that in mind, we will look at updating your UI for the iPhone X first up, followed by some other quick changes that will ensure your app appears modern and up-to-date.

Updating Your UI for iPhone X

Mandatory | Higher Priority

One of the most important tasks in updating your iOS app is ensuring is ensuring your app looks good and works nicely on the newer devices, whilst not breaking your previous device support. That's why Apple has worked very hard to provide developers with tools such as Auto Layout to design for screen-agnostic layouts, be it the iPhone 4, 5C, or the 6 and 6 Plus. As of this year, we now have a phone that not only has new dimensions, but also has a physical notch at the top. 

The top notch of the iPhone X

Notice that we don’t have a rectangle viewport anymore, and with the new notch at the top for the physical sensors, how does Apple recommend you deal with that? For one thing, Apple don’t want you to place black bars at the top to hide the notch! Instead, they are advocating for developers to embrace it.

Don't mask or call special attention to key display features. Don't attempt to hide the device's rounded corners, sensor housing, or indicator for accessing the Home screen by placing black bars at the top and bottom of the screen. Don't use visual adornments like brackets, bezels, shapes, or instructional text to call special attention to these areas either. (iOS Human Interface Guidelines)

You will need to design for the full-screen experience, leveraging the new device’s bezel-less design while not obscuring parts of your UI with either the device’s rounded corners or sensor housing (notch). 

The layout of the iPhone X along with the safe areas Auto-Layout source iOS Human Interface Guidelines

The good news is, Apple’s system-provided UI elements from UIKit such as the UINavigationBar already conform and adapt to the new design requirements out of the box. However for any custom UI elements, you will need to do the conformance work yourself. 

Comparing the UI elements on the iPhone 47 versus the iPhone X source iOS Human Interface Guidelines

Looking at the images of the iPhone 4.7 compared to the new iPhone X above, you will notice how the status bar is now implemented differently, starting with its height, which has grown from the historical 20 pt to 44 pt on the iPhone X. 

Apple suggests that app developers who have been hiding their status bars should reconsider that decision in light of the iPhone X and only hide it in landscape mode, not portrait mode. 

Finally, make use of the Safe Area Layout Guides by leveraging Auto Layouts as your primary measure to ensure your app fits within its appropriate margins, guaranteeing no visual obstructions, such as underlapping the status bar or navigation bar.

iPhone X Safe Areas source iOS Human Interface Guidelines

Two excellent resources to help get you started with designing for the iPhone X are the following WWDC videos:

Implementing Drag & Drop

Optional | Lower Priority

One of the most talked about new SDKs at this year’s WWDC is drag & drop. This is something desktop users have been accustomed to for a very long time, but its absence in the iOS platform meant the iPad and iPhone have never truly embraced multi-tasking. In iOS 11, this has changed, as the new iOS will support UI elements being dragged not only within the same screen, but from one application to another. 

Drag  Drop on the iPad source Apple - Drag  Drop

Leveraging iOS’s multi-touch engine, users can effortlessly move content in a natural way between apps on the iPad (or just within the same screen on the iPhone) by tapping and holding on an image, file, text, or specific UI element to drag it. This is already integrated system-wide in iOS, allowing users for instance to drag text from Safari into the dock’s Reminders app to create a new reminder item. 

This hasn’t been flagged as mandatory for implementation, but because it will rapidly become an expected behavior due to its prevalence system-wide, it is suggested that you try and prioritize this sooner rather than later, so that you can make your app’s UX conform to the new standard system UX behavior. 

UIKit comes with some level of drag & drop support built-in, for components such as UITables and UICollectionViews, but you will need to bridge and adapt the elements with code so that other components can receive the dragged component. This can be somewhat involved, and it's outside the scope of this article, but I'll cover drag & drop support more fully in a follow-up post next week. 

For now, briefly, you would add and support drag & drop in your ViewController’s viewDidLoad() method, by implementing the two delegates shown below:

Stay tuned for our upcoming article on how to add Drag and Drop support to your iOS 11 app. 

Other UIKit & Auto Layout Changes

Optional | Lower Priority

Finally, let's take a look at the remaining UIKit changes new to iOS 11, starting with the UINavigationBar, which has some notable improvements, including the integration of SearchViewController and large titles. We then take a look at the improvements to UITableView, from the new and improved swipe actions to table view cells automatically self-sizing. 

Navigation 

We already touched on navigation bars earlier on when discussing the iPhone X and how it aligns with the new status bar dimensions. Besides that, the new contemporary design style advocated for in iOS includes new larger titles in navigation bars, first seen in the Apple Music App in iOS 10 and since then an established design pattern across all of the other system apps in iOS. 

Large title bars on the iPhone X Navigation Bar source iOS Human Interface Guidelines

The larger title text provides greater emphasis on the context of the screen in a navigation bar, and helps orient users as to the active tab while navigating through the various tabs. The size of the title text is not static but rather shrinks as the user scrolls down, reverting to the pre-iOS 11 style. Inversely, when you pull down in a scroll view, the title text will increase slightly. 

Use a large title when you need to provide extra emphasis on context. In some apps, the big, bold text of a large title can help orient people as they browse and search. In a tabbed layout, for example, large titles can help clarify the active tab and inform the user when they've scrolled to the top. Phone uses this approach, while Music uses large titles to differentiate content areas like albums, artists, playlists, and radio. A large title transitions to a standard title as the user begins scrolling content. Large titles don't make sense in all apps and should never compete with content. Although the Clock app has a tabbed layout, large titles are unnecessary because each tab has a distinct, recognizable layout. (iOS Human Interface Guidelines))

As a developer, it's up to you to decide if and when to implement the large text style, based on Apple’s Human Interface Guidelines, and Apple recommends you specifically use the large text titles only for top-level navigation screens rather than across all levels. To enable large text, simply add the following property to your UINavigationController:

Hierarchically, both the master and detail view controllers under the navigation bar will have the large text mode enabled by default due to parent inheritance, and as just mentioned, it is advisable to only have the top-level navigation screens implement the large text mode. To suppress the large text inheritance in your detail screen, go to your view controller and add the following to its initializer (it has to be set at initialization time):

The largeTitleDisplayMode above is being set to .never. Without that line, the default is .automatic, which is where the detail view controller inherits the properties of its parent view controller.

Search View Controllers

Search can now be integrated directly into navigation bars without needing to associate the UISearchViewController instance with the subject view controller (and its table header view) separately. As of iOS 11, you can elegantly embed the search bar in the navigation bar:

You will also need to conform to UISearchResultsUpdating to react to search terms, of course. While iOS automatically hides the search bar based on the number of rows in your table view, you can force the search bar to be visible at all times by toggling:

UITableViews

Finally, we take a look at two new and distinguished features introduced to UITableViews as of iOS 11: self-sizing and improved swipe actions. Self-sizing was introduced way back in iOS 8 to alleviate the burden of developers having to manually size table view cells, with the ability to dynamically size the cells to fit the contents of the row using Auto Layout. Until now, you had to explicitly request auto-sizing using:

As of iOS 11, it is on and set by default with no extra code, but you still have the ability to specify your own row height explicitly, as needed. iOS 11 has also brought about new leading and trailing swipe actions, prevalent in many system apps such as Apple’s very own Mail app. 

New Action swipes in iOS 11s UITableView source Cult of Mac

In addition to being able to being able to swipe either left or right, you can also attach images to associate with these actions. You implement two delegate methods as part of the UIContextualAction, for leading and trailing swipe actions:

Using the code above, you can create more than one contextual action and add it to the UISwipeActionsConfiguration grouping instance, for more than one action. This is a simple yet engaging improvement to bring greater elasticity to your table views, with minimal code changes, and while not mandatory, it's worth allocating a few hours to it in your sprint planning board. 

Conclusion

In this post, I've given you an overview of the changes across the architecture, App Store, and visual components of iOS 11, providing you with an idea of what you will need to action immediately, and what can be deferred until a later time. Migration to iOS 11 and Swift 4 will be a lot easier than it was in the previous years' updates.

Beyond the imminent changes that need to be made, we've also gone through the Swift 4 changes that improve strings and collections, as well as the visual improvements to UITableView and Search Controller. This should make it easier for you to plan your work to make updates to your app!

Stay tuned for my upcoming post on implementing drag & drop for your iOS 11 apps, and in the meantime, check out some of our other posts on new changes to iOS and Swift!

2017-10-30T09:00:00.000Z2017-10-30T09:00:00.000ZDoron Katz

Updating Your App for iOS 11

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

In addition to feature development and bug fixes, iOS developers have to keep tabs on what’s announced yearly at WWDC. Amidst the notable new SDKs announced, there are some changes that iOS devs will need to roll out to keep their apps platform-compliant.

With Swift having evolved to version 4, along with improvements and changes coming to the iOS SDK itself, developers need to sift through the changes and devise a strategy for updating their code bases. All without breaking any of their existing features and functionalities! It all comes down to prioritization for your project: what is the minimum you need to do in order to make your app iOS 11 compliant? What is the easiest case you can make to your project stakeholder or project manager?

Vital features come first, and next come the nice-to-have but not required improvements that iOS 11 brings, from optimizing your application to the visual aesthetics that will further enrich the interaction and functionality of your app. With that in mind, this tutorial will guide you through the steps to take to upgrade your app, taking a pragmatic approach to required and optional improvements. 

Objectives of This Tutorial

This article will provide you with an overview of the changes that will be required in order to update your app for iOS 11, from architectural to visual changes as well as App Store publishing changes. Moreover, this tutorial will organize the sections starting from the required changes needed and the scope and effort required, to the nice but not necessary features that will enhance your app as a result of iOS 11. 

In this tutorial we will be covering the following:

  • preparing your app (and yourself) for iOS 11
  • architectural changes
  • App Store publishing changes
  • UI changes

Assumed Knowledge

This tutorial assumes an intermediate knowledge of Swift or Objective-C and Xcode, as well as familiarity with core iOS SDKs (e.g. UIKit and Core Foundation).

Architectural Changes

As with every iteration of iOS, the most important changes usually are the architectural ones. With iOS 11, this involves migrating to Swift 4, so updating the build settings for Xcode 9 will be the first task we'll look at. 

Incremental Migrating to Swift 4 

Important | Required

For those who had to migrate from Swift 2 to 3 last year, that process was extremely painful, and a lot of the changes broke the existing codebase. Thankfully, this isn’t the case moving from Swift 3.2 to 4, as most of the chances are considered additive, rather than deprecating, and as a result the Xcode 9 migration tool performs an admirable job of transitioning your code to the latest Swift.

Moreover, unlike in previous versions, you are not going to be forced to do the upgrade to 4 in one go. That is, Xcode projects simultaneously support both Swift 4 and Swift 3.2, which means that you can have one target in your project compile under Swift 3.2 and another compile in Swift 4. The migration tool will let you know which classes and functions it successfully migrated, and which ones will require your manual intervention to resolve, in the form of errors or warnings. 

The errors mean you will need to fix something that isn’t backward-compatible, whereas many of the warnings will indicate that there is a new way in Swift 4 of doing something, such as new API changes. Fix the errors, and prioritize the aforementioned warnings as a separate task. 

To access the migration tool, go to Edit > Convert > To Current Swift Syntax in Xcode, and follow the prompts, selecting the target(s) you wish to migrate at this stage. 

The Xcode Migration Tool modal prompt screen

The migration tool will let you know the minimum work that you will need to do in order to recompile your app, and therefore it should come as no surprise that the recommended best practice is to work on migrating your app from 3 to 4 incrementally, especially in large projects, testing and converting target by target. You won’t have to migrate everything at once, and you can plan your migration path in stages, where and when needed. 

We will next take a quick look at what the changes are in Swift 4 that are not mandatory to implement, but good to know. 

32-Bit Architectural Deprecation

Important | Required

Another major change in iOS 11 is that all apps in the App Store now have to be 64-bit, as 32-bit apps are no longer supported, and as a matter of fact don’t even work on devices running iOS 11. This shouldn’t come as a surprise as Apple have been warning developers for quite a while, but in case your app has still not made its transition, you can follow Apple’s guidelines on Converting Your App to a 64-bit Binary.

What’s New in Swift 4

Not Important | Optional

Beyond the mandatory work needed in order to get your target to become Swift 4 compliant, you have the option of refactoring your existing code to leverage the new Swift API changes, which are broken down according to the following API-level improvements:

Strings

String has received a lot of attention in Swift 4, with the most notable change being a reversion back to Swift 1.0 where Strings are once again defined as collections, so you can iterate over a String object character by character (SE-0163) using a for loop. Other notable changes to the Strings class include: 

Collections

Dictionaries and sets, as part of collections, have also been revamped in Swift 4, starting with the filtering of dictionaries, which until now returned an array of tuples consisting of key/value pairs. To access a specific element, you would use the following subscript, as in an array:

In Swift 4, you get back a dictionary instead, providing a more consistent syntax, and subsequently, you access the returned dictionary as you would a normal dictionary. The same now occurs for the map() function, where you also get back a dictionary. New to dictionary-access subscripts, you can provide a default value in case the key doesn’t exist, making your code safer.

The rest of the changes for collections include:

Other Notable Changes

Finally, there are some miscellaneous changes worth noting as part of this release pertaining to the language: 

You can find the exhaustive list of changes and original proposals at Swift.org.

App Store Publishing Changes

iOS 11 users of the App Store would have already noticed that it is sporting a completely new design with whole new sections, providing developers with new ways in which they can promote their apps and communicate with their users.

The new App Store Today Screen source Apple

We will start off by taking a look at the new marketing icon that you will now be required to upload with your app updates.

Marketing Icon

Mandatory | Higher Priority

As of iOS 11, for any new submissions, whether your app is new or an existing one, you will need to include an icon-1024.png—a 1024x1024 sized marketing icon. Conveniently enough, you won’t need to submit the icon via iTunes Connect, but through Xcode, bygoing to Images.xcassets and adding the appropriately sized image, the same way you manage your other icons:

You add the Marketing Icon in Xcode

The marketing icon is used as part of the new App Store design process, to show a larger image icon representing your app in the Today section, or other sections where the app graphic is enlarged. 

Promoting In-App Purchases

Optional | Lower Priority

Apple has made the process of in-app purchases more prominent and transparent, allowing users to view all the in-app purchasing options directly via the same level as the app product display, and in fact, even initiate an in-app purchase for the app whilst downloading the actual app. Think of a subscription app where users who download your app may already want to purchase their subscription. iOS 11 makes this quicker and more convenient. 

As of iOS 11, developers are able to promote up to 20 in-app purchases such as subscriptions on their app’s product page. These purchase options will also appear in search results. 

Promoting in-app purchases can also encourage downloads of your app. When a user doesn’t have your app installed but wants to buy a promoted in-app purchase, they'll receive a prompt to download the app first. Once the app is downloaded, the transaction will continue in the app. (Apple)

Marketing in-app purchases more visibly in the App Store source Apple

To enable greater in-app purchase promotion visibility, in iTunes Connect you will need to include the following metadata: 

  • Image: This is the unique promotional image representing your in-app purchase, appearing on your App Store product page, Today, Games, and Apps tabs, as well as other prominent areas. This should not consist of a screenshot or represent your app’s icon, but rather represent what the in-app purchase does. The image should also be in PNG format, and high quality with dimensions of 1024 x 1024.
  • Name: The display name of the in-app purchase, consisting of a maximum of 30 characters. This should be specific, befitting the function of that specific in-app purchase. If it is a subscription, say so, and ensure the duration of the subscription is included in the title, such as “One Month All-Access Subscription”.
  • Description: 45 characters long, descriptions provide context for the users to understand and appreciate the benefits of your specific in-app offering. 

For more information on promoting your in-app purchase, refer to Apple’s official guidelines as well as Apple’s Product Page guidelines.

Communicating With Your Customers

Optional | Lower Priority

Something that is definitely long overdue, and Android developers have enjoyed for quite some time, is the ability to respond directly to user comments. As of iOS 11, developers can now also directly respond to their users’ reviews and comments. While this doesn’t require any technical changes and participation is optional, developers through iTunes Connect (App > Activity > Ratings) can respond to praise as well as criticism.

Developers can now respond to comments and reviews in the App Store source Apple

Individualized developer responses can be leveraged in order to build stronger and more intimate relationships, fostering deeper engagement, by showing that their feedback is being reviewed and responded to, and issues they raised are actively being listened to. To respond to comments, simply go to iTunes Connect where you can view the feedback and respond individually. 

Besides the new developer comments feature, Apple have also provided a new formalized SDK to prompt users to rate and review apps. The new SKStoreReviewController should be used instead of any third party or manual prompting of users for reviews, because Apple wants the operating system to be able to control the frequency of the prompts as well as their visual appearance. Apple will thus constrain prompts to no more than three times in a 365-day period. 

To implement SKStoreReviewController, simply import StoreKit and call requestReview() as shown below:

While Apple hasn’t outright banned the other methods of prompting users for feedback, expect this to change in the near future, so it's best that you start thinking of implementing Apple’s prompt-to-review engine over the next year.

Refer to Apple’s Ratings, Reviews and Responses guidelines for more information. 

Incremental Rollouts

Optional | Lower Priority

Another very useful feature iOS 11 brings to developers is the ability to release their apps to users incrementally. Apple calls this phased releasing, and it's intended to reduce the risk of overloading the production environment all at once, instead rolling out the release updates over a seven-day period. 

Developers can now roll-out an app in phases over a 7-day period

Under Version Release in iTunes Connect, there is a new section called Phased Release for Automatic Updates, which gives you the option of either releasing immediately or over the seven-day period. Developers are also able to halt the phased roll-out for up to 30 days, which would normally happen if a major issue is discovered and reported.

A chart demonstrating the percentage of users receiving the app split over a 7-day period

The phased roll-out doesn’t prevent users from getting the update manually from the App Store, but rather is targeted at users who use the iOS automatic download setting in the App Store. 

Next, let’s take a look at the visual changes that were introduced as part of iOS 11, as we go through the important as well as the less important topics. 

UI Changes

After looking at the architectural as well as the app store publishing changes for iOS 11, we are now ready to dissect the visual changes and help you prioritize what UI changes should be tackled first. 

Importantly, while we certainly could build our iOS apps without implementing any of the changes in this section, addressing only the architectural and App Store changes, you may first want to ensure that your app visually supports the new iPhone X. This means changes to the navigation bars to address the new physical ‘notch’ at the top. 

With that in mind, we will look at updating your UI for the iPhone X first up, followed by some other quick changes that will ensure your app appears modern and up-to-date.

Updating Your UI for iPhone X

Mandatory | Higher Priority

One of the most important tasks in updating your iOS app is ensuring is ensuring your app looks good and works nicely on the newer devices, whilst not breaking your previous device support. That's why Apple has worked very hard to provide developers with tools such as Auto Layout to design for screen-agnostic layouts, be it the iPhone 4, 5C, or the 6 and 6 Plus. As of this year, we now have a phone that not only has new dimensions, but also has a physical notch at the top. 

The top notch of the iPhone X

Notice that we don’t have a rectangle viewport anymore, and with the new notch at the top for the physical sensors, how does Apple recommend you deal with that? For one thing, Apple don’t want you to place black bars at the top to hide the notch! Instead, they are advocating for developers to embrace it.

Don't mask or call special attention to key display features. Don't attempt to hide the device's rounded corners, sensor housing, or indicator for accessing the Home screen by placing black bars at the top and bottom of the screen. Don't use visual adornments like brackets, bezels, shapes, or instructional text to call special attention to these areas either. (iOS Human Interface Guidelines)

You will need to design for the full-screen experience, leveraging the new device’s bezel-less design while not obscuring parts of your UI with either the device’s rounded corners or sensor housing (notch). 

The layout of the iPhone X along with the safe areas Auto-Layout source iOS Human Interface Guidelines

The good news is, Apple’s system-provided UI elements from UIKit such as the UINavigationBar already conform and adapt to the new design requirements out of the box. However for any custom UI elements, you will need to do the conformance work yourself. 

Comparing the UI elements on the iPhone 47 versus the iPhone X source iOS Human Interface Guidelines

Looking at the images of the iPhone 4.7 compared to the new iPhone X above, you will notice how the status bar is now implemented differently, starting with its height, which has grown from the historical 20 pt to 44 pt on the iPhone X. 

Apple suggests that app developers who have been hiding their status bars should reconsider that decision in light of the iPhone X and only hide it in landscape mode, not portrait mode. 

Finally, make use of the Safe Area Layout Guides by leveraging Auto Layouts as your primary measure to ensure your app fits within its appropriate margins, guaranteeing no visual obstructions, such as underlapping the status bar or navigation bar.

iPhone X Safe Areas source iOS Human Interface Guidelines

Two excellent resources to help get you started with designing for the iPhone X are the following WWDC videos:

Implementing Drag & Drop

Optional | Lower Priority

One of the most talked about new SDKs at this year’s WWDC is drag & drop. This is something desktop users have been accustomed to for a very long time, but its absence in the iOS platform meant the iPad and iPhone have never truly embraced multi-tasking. In iOS 11, this has changed, as the new iOS will support UI elements being dragged not only within the same screen, but from one application to another. 

Drag  Drop on the iPad source Apple - Drag  Drop

Leveraging iOS’s multi-touch engine, users can effortlessly move content in a natural way between apps on the iPad (or just within the same screen on the iPhone) by tapping and holding on an image, file, text, or specific UI element to drag it. This is already integrated system-wide in iOS, allowing users for instance to drag text from Safari into the dock’s Reminders app to create a new reminder item. 

This hasn’t been flagged as mandatory for implementation, but because it will rapidly become an expected behavior due to its prevalence system-wide, it is suggested that you try and prioritize this sooner rather than later, so that you can make your app’s UX conform to the new standard system UX behavior. 

UIKit comes with some level of drag & drop support built-in, for components such as UITables and UICollectionViews, but you will need to bridge and adapt the elements with code so that other components can receive the dragged component. This can be somewhat involved, and it's outside the scope of this article, but I'll cover drag & drop support more fully in a follow-up post next week. 

For now, briefly, you would add and support drag & drop in your ViewController’s viewDidLoad() method, by implementing the two delegates shown below:

Stay tuned for our upcoming article on how to add Drag and Drop support to your iOS 11 app. 

Other UIKit & Auto Layout Changes

Optional | Lower Priority

Finally, let's take a look at the remaining UIKit changes new to iOS 11, starting with the UINavigationBar, which has some notable improvements, including the integration of SearchViewController and large titles. We then take a look at the improvements to UITableView, from the new and improved swipe actions to table view cells automatically self-sizing. 

Navigation 

We already touched on navigation bars earlier on when discussing the iPhone X and how it aligns with the new status bar dimensions. Besides that, the new contemporary design style advocated for in iOS includes new larger titles in navigation bars, first seen in the Apple Music App in iOS 10 and since then an established design pattern across all of the other system apps in iOS. 

Large title bars on the iPhone X Navigation Bar source iOS Human Interface Guidelines

The larger title text provides greater emphasis on the context of the screen in a navigation bar, and helps orient users as to the active tab while navigating through the various tabs. The size of the title text is not static but rather shrinks as the user scrolls down, reverting to the pre-iOS 11 style. Inversely, when you pull down in a scroll view, the title text will increase slightly. 

Use a large title when you need to provide extra emphasis on context. In some apps, the big, bold text of a large title can help orient people as they browse and search. In a tabbed layout, for example, large titles can help clarify the active tab and inform the user when they've scrolled to the top. Phone uses this approach, while Music uses large titles to differentiate content areas like albums, artists, playlists, and radio. A large title transitions to a standard title as the user begins scrolling content. Large titles don't make sense in all apps and should never compete with content. Although the Clock app has a tabbed layout, large titles are unnecessary because each tab has a distinct, recognizable layout. (iOS Human Interface Guidelines))

As a developer, it's up to you to decide if and when to implement the large text style, based on Apple’s Human Interface Guidelines, and Apple recommends you specifically use the large text titles only for top-level navigation screens rather than across all levels. To enable large text, simply add the following property to your UINavigationController:

Hierarchically, both the master and detail view controllers under the navigation bar will have the large text mode enabled by default due to parent inheritance, and as just mentioned, it is advisable to only have the top-level navigation screens implement the large text mode. To suppress the large text inheritance in your detail screen, go to your view controller and add the following to its initializer (it has to be set at initialization time):

The largeTitleDisplayMode above is being set to .never. Without that line, the default is .automatic, which is where the detail view controller inherits the properties of its parent view controller.

Search View Controllers

Search can now be integrated directly into navigation bars without needing to associate the UISearchViewController instance with the subject view controller (and its table header view) separately. As of iOS 11, you can elegantly embed the search bar in the navigation bar:

You will also need to conform to UISearchResultsUpdating to react to search terms, of course. While iOS automatically hides the search bar based on the number of rows in your table view, you can force the search bar to be visible at all times by toggling:

UITableViews

Finally, we take a look at two new and distinguished features introduced to UITableViews as of iOS 11: self-sizing and improved swipe actions. Self-sizing was introduced way back in iOS 8 to alleviate the burden of developers having to manually size table view cells, with the ability to dynamically size the cells to fit the contents of the row using Auto Layout. Until now, you had to explicitly request auto-sizing using:

As of iOS 11, it is on and set by default with no extra code, but you still have the ability to specify your own row height explicitly, as needed. iOS 11 has also brought about new leading and trailing swipe actions, prevalent in many system apps such as Apple’s very own Mail app. 

New Action swipes in iOS 11s UITableView source Cult of Mac

In addition to being able to being able to swipe either left or right, you can also attach images to associate with these actions. You implement two delegate methods as part of the UIContextualAction, for leading and trailing swipe actions:

Using the code above, you can create more than one contextual action and add it to the UISwipeActionsConfiguration grouping instance, for more than one action. This is a simple yet engaging improvement to bring greater elasticity to your table views, with minimal code changes, and while not mandatory, it's worth allocating a few hours to it in your sprint planning board. 

Conclusion

In this post, I've given you an overview of the changes across the architecture, App Store, and visual components of iOS 11, providing you with an idea of what you will need to action immediately, and what can be deferred until a later time. Migration to iOS 11 and Swift 4 will be a lot easier than it was in the previous years' updates.

Beyond the imminent changes that need to be made, we've also gone through the Swift 4 changes that improve strings and collections, as well as the visual improvements to UITableView and Search Controller. This should make it easier for you to plan your work to make updates to your app!

Stay tuned for my upcoming post on implementing drag & drop for your iOS 11 apps, and in the meantime, check out some of our other posts on new changes to iOS and Swift!

2017-10-30T09:00:00.000Z2017-10-30T09:00:00.000ZDoron Katz

Kotlin From Scratch: Exception Handling

$
0
0

Kotlin is a modern programming language that compiles to Java bytecode. It's free and open source, and makes coding for Android even more fun.  

In the previous article, you learned more about object-oriented programming by digging into abstract classes, interfaces, inheritance, and type aliases in Kotlin. 

In this post, you'll continue to learn about programming in Kotlin by learning about exceptions and how to handle them. 

1. Exception Handling

Exceptions are used to indicate a problem in our code during a program's execution. Exception handling is the capability to address (or handle) the exception that might occur. If we don't handle any exception that occurs, our program will stop execution abruptly—crashing our app immediately. 

Exception handling allows our program to continue execution even if there was an exception (though it is highly recommended to log your exceptions and report them using a crash reporting tool like Crashlytics).   

In Java, we have two kinds of exceptions: checked and unchecked. I'll briefly explain both of them, but we'll start with unchecked exceptions. 

Unchecked Exceptions

These are exceptions that are thrown because of flaws in your code. They are a direct or indirect subclass of the RuntimeException superclass. 

Examples of unchecked exceptions include:

  • ArithmeticException: thrown when you divide by zero.
  • ArrayIndexOutOfBoundExceptions: thrown when an array has been accessed with an illegal index. 
  • SecurityException: thrown by the security manager to indicate a security violation.
  • NullPointerException: thrown when invoking a method or property on a null object.

A method that might throw an unchecked exception doesn't contain any information about the exception thrown on its method declaration. 

These types of exception can be prevented by coding right. In the code above, we should have checked if the denominator was zero before performing the operation. For these exceptions, the developer doesn't need to catch the exception using the try...catch block. In other words, we aren't forced by the compiler to wrap the code that might trigger the exception in a try...catch block. Instead, we should just make sure the exceptions never occur in the first place.

Also, remember, Kotlin is a null safe language. In other words, it can help us avoid getting NullPointerExceptions in our code. You can read the Nullability, Loops, and Conditions post to get a refresher on null safety in Kotlin. 

Checked Exceptions in Java

A method that might throw a checked exception needs to declare so in its method signature using the throws keyword. If you call a method that throws a checked exception, you either need to throw it again from your function or to catch it and handle it using a try...catch block. 

Checked exceptions are exceptions that are checked at compile time. These kinds of exceptions inherit from the Exception class. An example of this kind of exception is IOException. This can occur when you try to access a file that can't be opened because it doesn't exist. (FileNotFoundException is a subclass of IOException.)

In the preceding code, we used a try...catch block to handle the IOException inside the editFile() method. We can now call the editFile() method as normal, and the compiler won't complain. 

Looking at the code below, we've refactored the method to instead use the throws keyword in the method signature. This indicates to callers that they need to handle the exception IOException that might be thrown when calling the method editFile().

To call the method above, we need to surround it in a try...catch block to handle the exception.

This has been a brief look at exceptions in Java. Let's now see how Kotlin handles exceptions. 

2. Exceptions in Kotlin

The main difference between Kotlin and Java exception mechanisms is that all exceptions are unchecked in Kotlin. In other words, they are not explicitly declared in the function signatures, as they are in Java.

Here, we have converted the editFile() method to a Kotlin function. You can see that the function doesn't have the throws IOException statement in its function signature. throws isn't even a keyword in Kotlin. 

Also, we can call this function without surrounding it with the try...catch block—and the compiler won't complain. In other words, there's no such thing as checked exceptions in Kotlin. All exceptions are unchecked. (Note that if there is an exception thrown, program execution will stop as normal.) 

If we think this exception might arise, we should still handle it by surrounding the method with a try...catch block—but this is not enforced by the Kotlin compiler. 

If the exception thrown inside the editFile() function is an instance of the IOException class, our catch block will be executed, and we simply print the stack trace for debugging purposes.

The try...catch Block

The try construct with catch and finally clauses in Kotlin is similar to that of Java. 

Here, we are throwing an Exception object inside the try block. Notice we didn't include the new keyword as we do in Java to create a new instance. Also notice that we didn't specify the exception that will be thrown in the function signature as we would have to in Java. 

We handle all subclasses and classes of type Exception in the catch block. The optional finally block is always executed—this is where we typically close any resources or connections that were previously opened so as to prevent resource leaks. For example, if you open a file or create a database or network connection in a try block, you should close or free it in a finally block. 

Note that in Kotlin the throw construct is an expression and can combine with other expressions.

Also, the try construct can be used as an expression.

Here, we assigned the value returned from the try...catch block to the result variable. If the number is not 1, it throws an IllegalArgumentException and the catch block is executed. The false expression in the catch block value will be assigned to the result variable. If the number is 1 instead, then the true expression value will be assigned to the result variable.

Java Interop

Exceptions in Kotlin behave as normal in Java—but I want to make you aware of a useful annotation called @Throws in Kotlin that might come in handy. Because all exceptions in Kotlin are unchecked, developers who consume your Kotlin code from Java might not be aware that your functions throw exceptions. However, you can still add the possible exceptions that might be thrown to a method signature with the @Throw annotation. This will alert Java callers that they need to handle the exception. 

Let's see a practical example of this annotation.

Here, we defined a Kotlin function that can throw an exception IllegalArgumentException only if the type passed to the function is not of type Int

We call this top-level function addNumberToTwo() directly from Java in the following way:

This works fine; the compiler isn't complaining. However, if we want to communicate with Java callers that the addNumberToTwo() top-level function throws an exception, we simply add the @Throws annotation to the function signature. 

This @Throws annotation can accept a comma-separated list of arguments of exception classes. In the code above, we just included one exception class—IllegalArgumentException

Now we have to update our Java code to handle the exception.

If we decompile the Kotlin addNumberToTwo() function, using the Show Kotlin Bytecode feature (if you're in IntelliJ IDEA or Android Studio, use Tools > Kotlin Show Kotlin Bytecode), we'll see the following Java code:

In the generated Java code above (some elements of the generated code were removed for brevity's sake), you can see that the compiler added the throws keyword to the method signature—because we included the @Throws annotation. 

Conclusion

In this tutorial, you learned more about programming in Kotlin by looking into exceptions. We saw that Kotlin doesn't have checked exceptions but that instead, all exceptions are unchecked. We also looked at how to handle exceptions using the try...catch block and saw the usefulness of the @Throws annotation in Kotlin for Java callers. 

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts!


2017-11-01T12:00:00.000Z2017-11-01T12:00:00.000ZChike Mgbemena

Kotlin From Scratch: Exception Handling

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

Kotlin is a modern programming language that compiles to Java bytecode. It's free and open source, and makes coding for Android even more fun.  

In the previous article, you learned more about object-oriented programming by digging into abstract classes, interfaces, inheritance, and type aliases in Kotlin. 

In this post, you'll continue to learn about programming in Kotlin by learning about exceptions and how to handle them. 

1. Exception Handling

Exceptions are used to indicate a problem in our code during a program's execution. Exception handling is the capability to address (or handle) the exception that might occur. If we don't handle any exception that occurs, our program will stop execution abruptly—crashing our app immediately. 

Exception handling allows our program to continue execution even if there was an exception (though it is highly recommended to log your exceptions and report them using a crash reporting tool like Crashlytics).   

In Java, we have two kinds of exceptions: checked and unchecked. I'll briefly explain both of them, but we'll start with unchecked exceptions. 

Unchecked Exceptions

These are exceptions that are thrown because of flaws in your code. They are a direct or indirect subclass of the RuntimeException superclass. 

Examples of unchecked exceptions include:

  • ArithmeticException: thrown when you divide by zero.
  • ArrayIndexOutOfBoundExceptions: thrown when an array has been accessed with an illegal index. 
  • SecurityException: thrown by the security manager to indicate a security violation.
  • NullPointerException: thrown when invoking a method or property on a null object.

A method that might throw an unchecked exception doesn't contain any information about the exception thrown on its method declaration. 

These types of exception can be prevented by coding right. In the code above, we should have checked if the denominator was zero before performing the operation. For these exceptions, the developer doesn't need to catch the exception using the try...catch block. In other words, we aren't forced by the compiler to wrap the code that might trigger the exception in a try...catch block. Instead, we should just make sure the exceptions never occur in the first place.

Also, remember, Kotlin is a null safe language. In other words, it can help us avoid getting NullPointerExceptions in our code. You can read the Nullability, Loops, and Conditions post to get a refresher on null safety in Kotlin. 

Checked Exceptions in Java

A method that might throw a checked exception needs to declare so in its method signature using the throws keyword. If you call a method that throws a checked exception, you either need to throw it again from your function or to catch it and handle it using a try...catch block. 

Checked exceptions are exceptions that are checked at compile time. These kinds of exceptions inherit from the Exception class. An example of this kind of exception is IOException. This can occur when you try to access a file that can't be opened because it doesn't exist. (FileNotFoundException is a subclass of IOException.)

In the preceding code, we used a try...catch block to handle the IOException inside the editFile() method. We can now call the editFile() method as normal, and the compiler won't complain. 

Looking at the code below, we've refactored the method to instead use the throws keyword in the method signature. This indicates to callers that they need to handle the exception IOException that might be thrown when calling the method editFile().

To call the method above, we need to surround it in a try...catch block to handle the exception.

This has been a brief look at exceptions in Java. Let's now see how Kotlin handles exceptions. 

2. Exceptions in Kotlin

The main difference between Kotlin and Java exception mechanisms is that all exceptions are unchecked in Kotlin. In other words, they are not explicitly declared in the function signatures, as they are in Java.

Here, we have converted the editFile() method to a Kotlin function. You can see that the function doesn't have the throws IOException statement in its function signature. throws isn't even a keyword in Kotlin. 

Also, we can call this function without surrounding it with the try...catch block—and the compiler won't complain. In other words, there's no such thing as checked exceptions in Kotlin. All exceptions are unchecked. (Note that if there is an exception thrown, program execution will stop as normal.) 

If we think this exception might arise, we should still handle it by surrounding the method with a try...catch block—but this is not enforced by the Kotlin compiler. 

If the exception thrown inside the editFile() function is an instance of the IOException class, our catch block will be executed, and we simply print the stack trace for debugging purposes.

The try...catch Block

The try construct with catch and finally clauses in Kotlin is similar to that of Java. 

Here, we are throwing an Exception object inside the try block. Notice we didn't include the new keyword as we do in Java to create a new instance. Also notice that we didn't specify the exception that will be thrown in the function signature as we would have to in Java. 

We handle all subclasses and classes of type Exception in the catch block. The optional finally block is always executed—this is where we typically close any resources or connections that were previously opened so as to prevent resource leaks. For example, if you open a file or create a database or network connection in a try block, you should close or free it in a finally block. 

Note that in Kotlin the throw construct is an expression and can combine with other expressions.

Also, the try construct can be used as an expression.

Here, we assigned the value returned from the try...catch block to the result variable. If the number is not 1, it throws an IllegalArgumentException and the catch block is executed. The false expression in the catch block value will be assigned to the result variable. If the number is 1 instead, then the true expression value will be assigned to the result variable.

Java Interop

Exceptions in Kotlin behave as normal in Java—but I want to make you aware of a useful annotation called @Throws in Kotlin that might come in handy. Because all exceptions in Kotlin are unchecked, developers who consume your Kotlin code from Java might not be aware that your functions throw exceptions. However, you can still add the possible exceptions that might be thrown to a method signature with the @Throw annotation. This will alert Java callers that they need to handle the exception. 

Let's see a practical example of this annotation.

Here, we defined a Kotlin function that can throw an exception IllegalArgumentException only if the type passed to the function is not of type Int

We call this top-level function addNumberToTwo() directly from Java in the following way:

This works fine; the compiler isn't complaining. However, if we want to communicate with Java callers that the addNumberToTwo() top-level function throws an exception, we simply add the @Throws annotation to the function signature. 

This @Throws annotation can accept a comma-separated list of arguments of exception classes. In the code above, we just included one exception class—IllegalArgumentException

Now we have to update our Java code to handle the exception.

If we decompile the Kotlin addNumberToTwo() function, using the Show Kotlin Bytecode feature (if you're in IntelliJ IDEA or Android Studio, use Tools > Kotlin Show Kotlin Bytecode), we'll see the following Java code:

In the generated Java code above (some elements of the generated code were removed for brevity's sake), you can see that the compiler added the throws keyword to the method signature—because we included the @Throws annotation. 

Conclusion

In this tutorial, you learned more about programming in Kotlin by looking into exceptions. We saw that Kotlin doesn't have checked exceptions but that instead, all exceptions are unchecked. We also looked at how to handle exceptions using the try...catch block and saw the usefulness of the @Throws annotation in Kotlin for Java callers. 

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts!


2017-11-01T12:00:00.000Z2017-11-01T12:00:00.000ZChike Mgbemena

Ionic From Scratch: What Is Ionic?

$
0
0

Are you interested in coding mobile apps but don't have the specialized knowledge or experience in programming and developing iOS and Android apps? Well, let me introduce you to the Ionic framework, which lets you write an app once and publish it to any mobile platform.

Ionic mobile apps

So, What Is Ionic?

Simply put, Ionic is a free-to-use framework that allows you to build mobile apps for iOS, Android and Windows Phone, all from one codebase. In other words, Ionic is a tool for cross-platform mobile development.

Ionic was founded in 2012 by a tech start-up called Drifty Co, and it's now the world's top open-source framework for building cross-platform (hybrid) mobile apps. 

How Ionic Works

Ionic enables you to develop mobile apps using web technologies and languages like HTML, CSS, JavaScript, Angular, and TypeScript. Therefore, consider Ionic a front-end software development kit (SDK) for creating hybrid mobile applications. As such, Ionic provides a collection of components that mimic the native look, feel and functionality of each mobile platform. Examples of these components include buttons, tabs, menus, lists, cards, modals, and so on.

Apart from these components that provide the styling and "look and feel" for mobile apps, Ionic also provides the appropriate behaviors like navigation and gestures—for example, swiping, rotation, and pinch events, to name but a few. Ionic also includes a collection of icons called Ionicons. All these components are elements that you use in building your Ionic apps, along with Cordova and PhoneGap plugins, which we'll touch on shortly.

How Hard Is It to Get Started?

It's really not difficult to get started using Ionic. Ionic comes with tools to help you set up, build and run your Ionic project—this is the Ionic Command-Line Interface (CLI). All the front-end libraries and the CLI are open-source projects, so you can use them for free when developing your apps. 

Why Use Ionic?

It is difficult to develop native apps. Developing Android apps alone requires you to learn how to use Android Studio's IDE (Integrated Development Environment) and know the Java or Kotlin programming language. You'll also need to understand Android-specific concepts like activities and intents, and you'll create your app UIs with a custom XML syntax. 

For iOS, you'd need to use the Xcode IDE (which is only available for Mac), as well as Apple's Objective-C or Swift programming languages. Not to mention all the many Mac-specific SDKs and concepts! And on top of that, if you also decide to build for Windows Phone then you will also need to learn how to use Visual Studio's IDE, as well as writing code in C# or Visual Basic and so on...

So, if you want to ship your app to multiple platforms, you would have to rewrite the same functionality in three different languages! Developing apps this way not only requires learning a lot of different languages and tools, it also means you end up re-coding the same logic for two or three different programming languages and mobile platforms. And the same duplication of effort is required when you need to make any changes. Developing apps natively takes a lot of time, money, and skill. So wouldn't it be great to have a single code base that works for all three platforms? 

That's where Ionic comes in!

An Ionic social app running on iPhone

Hybrid Applications

Hybrid apps take advantage of each platform's libraries or user interface components like buttons, lists, and so on. One of these components is webview—a view that displays web pages. This is a native mobile app component that can run a web application. You can therefore write an app in HTML, CSS, and JavaScript and use a webview to display it.

They are called hybrid apps because they use a mix of native code and HTML, CSS, and JavaScript. There are many frameworks that make it easy to create an app that runs a web app in a webview. The most popular is Apache Cordova, usually accessed via its most popular distribution: PhoneGap. Cordova is an open-source project, and PhoneGap, owned by Adobe, is based on Cordova and provides additional features and services on top of it.

Ionic uses the Apache Cordova project to build and run your apps as native apps.

Ionic and Cordova

Cordova acts as a bridge to native code for Ionic. It compiles your HTML, JavaScript, and CSS into native apps, enabling them to run natively on Android, iOS, and Windows Phone devices.

If you simply write a web app in the same way you would write a website and just package it as a mobile app with Cordova, the end result will be an app that looks like a website. Users will notice the style and user interaction are different from a "normal" mobile application. 

That is the missing piece that Ionic provides—native look and feel. Ionic includes a collection of components that have the same look and feel as native components, using the appropriate styles and behaviors for each platform, as previously mentioned. You can therefore write your app in HTML, CSS, and JavaScript, but your app will look like a native app rather than a web page.

Cordova also provides over 200 plugins available as add-ons that you can use within your Ionic projects, which enable you to access native device APIs like the phone's camera, geolocation, gyroscope, and so on. You can use these to enhance your app's features and functionality. 

An Ionic radio app

Ionic and Angular

Chances are, you wouldn't want to create your web apps using vanilla JavaScript, HTML, and CSS alone. Instead, you'd probably use a web framework like Angular. Angular is an incredibly popular framework that makes it easy to build reactive web applications. And now Ionic brings the power of Angular to mobile coding! 

Ionic makes it possible to use the Angular framework to write mobile apps by shipping a rich library of components as well as the tooling to compile Angular TypeScript code into a bundle of vanilla JavaScript, HTML, and CSS, which Apache Cordova can then bundle into a native mobile application.

A quick diagram to illustrate the above looks something like this:

From Angular to mobile app

Conclusion

For anyone out there looking to get into the world of developing mobile apps, I strongly recommend and encourage you to try out Ionic, as it offers you the opportunity to develop cross-platform mobile apps, all from a single code base.

The framework is well supported and has continued to develop and grow over the years, and it continues to get better and better.

2017-11-03T15:00:00.000Z2017-11-03T15:00:00.000ZTinashe Munyaka

Ionic From Scratch: What Is Ionic?

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

Are you interested in coding mobile apps but don't have the specialized knowledge or experience in programming and developing iOS and Android apps? Well, let me introduce you to the Ionic framework, which lets you write an app once and publish it to any mobile platform.

Ionic mobile apps

So, What Is Ionic?

Simply put, Ionic is a free-to-use framework that allows you to build mobile apps for iOS, Android and Windows Phone, all from one codebase. In other words, Ionic is a tool for cross-platform mobile development.

Ionic was founded in 2012 by a tech start-up called Drifty Co, and it's now the world's top open-source framework for building cross-platform (hybrid) mobile apps. 

How Ionic Works

Ionic enables you to develop mobile apps using web technologies and languages like HTML, CSS, JavaScript, Angular, and TypeScript. Therefore, consider Ionic a front-end software development kit (SDK) for creating hybrid mobile applications. As such, Ionic provides a collection of components that mimic the native look, feel and functionality of each mobile platform. Examples of these components include buttons, tabs, menus, lists, cards, modals, and so on.

Apart from these components that provide the styling and "look and feel" for mobile apps, Ionic also provides the appropriate behaviors like navigation and gestures—for example, swiping, rotation, and pinch events, to name but a few. Ionic also includes a collection of icons called Ionicons. All these components are elements that you use in building your Ionic apps, along with Cordova and PhoneGap plugins, which we'll touch on shortly.

How Hard Is It to Get Started?

It's really not difficult to get started using Ionic. Ionic comes with tools to help you set up, build and run your Ionic project—this is the Ionic Command-Line Interface (CLI). All the front-end libraries and the CLI are open-source projects, so you can use them for free when developing your apps. 

Why Use Ionic?

It is difficult to develop native apps. Developing Android apps alone requires you to learn how to use Android Studio's IDE (Integrated Development Environment) and know the Java or Kotlin programming language. You'll also need to understand Android-specific concepts like activities and intents, and you'll create your app UIs with a custom XML syntax. 

For iOS, you'd need to use the Xcode IDE (which is only available for Mac), as well as Apple's Objective-C or Swift programming languages. Not to mention all the many Mac-specific SDKs and concepts! And on top of that, if you also decide to build for Windows Phone then you will also need to learn how to use Visual Studio's IDE, as well as writing code in C# or Visual Basic and so on...

So, if you want to ship your app to multiple platforms, you would have to rewrite the same functionality in three different languages! Developing apps this way not only requires learning a lot of different languages and tools, it also means you end up re-coding the same logic for two or three different programming languages and mobile platforms. And the same duplication of effort is required when you need to make any changes. Developing apps natively takes a lot of time, money, and skill. So wouldn't it be great to have a single code base that works for all three platforms? 

That's where Ionic comes in!

An Ionic social app running on iPhone

Hybrid Applications

Hybrid apps take advantage of each platform's libraries or user interface components like buttons, lists, and so on. One of these components is webview—a view that displays web pages. This is a native mobile app component that can run a web application. You can therefore write an app in HTML, CSS, and JavaScript and use a webview to display it.

They are called hybrid apps because they use a mix of native code and HTML, CSS, and JavaScript. There are many frameworks that make it easy to create an app that runs a web app in a webview. The most popular is Apache Cordova, usually accessed via its most popular distribution: PhoneGap. Cordova is an open-source project, and PhoneGap, owned by Adobe, is based on Cordova and provides additional features and services on top of it.

Ionic uses the Apache Cordova project to build and run your apps as native apps.

Ionic and Cordova

Cordova acts as a bridge to native code for Ionic. It compiles your HTML, JavaScript, and CSS into native apps, enabling them to run natively on Android, iOS, and Windows Phone devices.

If you simply write a web app in the same way you would write a website and just package it as a mobile app with Cordova, the end result will be an app that looks like a website. Users will notice the style and user interaction are different from a "normal" mobile application. 

That is the missing piece that Ionic provides—native look and feel. Ionic includes a collection of components that have the same look and feel as native components, using the appropriate styles and behaviors for each platform, as previously mentioned. You can therefore write your app in HTML, CSS, and JavaScript, but your app will look like a native app rather than a web page.

Cordova also provides over 200 plugins available as add-ons that you can use within your Ionic projects, which enable you to access native device APIs like the phone's camera, geolocation, gyroscope, and so on. You can use these to enhance your app's features and functionality. 

An Ionic radio app

Ionic and Angular

Chances are, you wouldn't want to create your web apps using vanilla JavaScript, HTML, and CSS alone. Instead, you'd probably use a web framework like Angular. Angular is an incredibly popular framework that makes it easy to build reactive web applications. And now Ionic brings the power of Angular to mobile coding! 

Ionic makes it possible to use the Angular framework to write mobile apps by shipping a rich library of components as well as the tooling to compile Angular TypeScript code into a bundle of vanilla JavaScript, HTML, and CSS, which Apache Cordova can then bundle into a native mobile application.

A quick diagram to illustrate the above looks something like this:

From Angular to mobile app

Conclusion

For anyone out there looking to get into the world of developing mobile apps, I strongly recommend and encourage you to try out Ionic, as it offers you the opportunity to develop cross-platform mobile apps, all from a single code base.

The framework is well supported and has continued to develop and grow over the years, and it continues to get better and better.

2017-11-03T15:00:00.000Z2017-11-03T15:00:00.000ZTinashe Munyaka

Secure Coding in Swift 4

$
0
0

From minimizing pointer use to strong type checking at compile time, Swift is a great language for secure development. But that means it's tempting to forget about security altogether. There are still vulnerabilities, and Swift is also enticing to new developers who haven't yet learned about security. 

This tutorial is a secure coding guide that will address changes in Swift 4 as well as the new tooling options available in Xcode 9 that will help you mitigate security vulnerabilities.

Pointers and Overflows

Many security vulnerabilities have revolved around C and its use of pointers. This is because pointers allow you to access raw memory locations, making it easier to read and write to the wrong area. It has been a major way for attackers to maliciously change a program. 

Swift mostly does away with pointers, but it still allows you to interface with C. Many APIs, including Apple's entire Core Foundation API, are based entirely in C, so it's very easy to introduce the use of pointers back into Swift. 

Fortunately, Apple has named the pointer types appropriately:UnsafePointer<T>, UnsafeRawPointer<T>UnsafeBufferPointer<T>, and UnsafeRawBufferPointer. There will come a time when the API you are interfacing with will return these types, and the main rule when using them is don't store or return pointers for later use. For example:

Because we accessed the pointer outside of the closure, we don't know for sure if the pointer still points to the expected memory contents. The safe way to use the pointer in this example would be to keep it, along with the print statement, within the closure. 

Pointers to strings and arrays also have no bounds checking. This means it's easy to use an unsafe pointer on an array but accidentally access beyond its boundary—a buffer overflow.

The good news is that Swift 4 attempts to crash the app instead of continuing with what would be called undefined behavior. We don't know what buffer[5] points to! However, Swift won't catch every case. Set a breakpoint after the following code and look at variables a and c. They will be set to 999.

This demonstrates a stack overflow because without an explicit allocation, variables are generally stored on the stack. 

In the next example, we make an allocation with a capacity of only a single Int8. Allocations are stored on the heap, so the next line will overflow the heap. For this example, Xcode only warns you with a note in the console that gets is unsafe.

So what's the best way to avoid overflows? It's extremely important when interfacing with C to do bounds checking on the input to make sure it's within range. 

You might be thinking that it's pretty hard to remember and find all of the different cases. So to help you out, Xcode comes with a very useful tool called Address Sanitizer. 

Address Sanitizer has been improved in Xcode 9. It is a tool that helps you catch invalid memory access such as the examples we have just seen. If you will be working with the Unsafe* types, it's a good idea to use the Address Sanitizer tool. It is not enabled by default, so to enable it, go to Product > Scheme > Edit Scheme > Diagnostics, and check Address Sanitizer. In Xcode 9 there is a new sub-option, Detect use of stack after return. This new option detects the use-after-scope and use-after-return vulnerabilities from our first example.

Sometimes overlooked is the integer overflow. This is because integer overflows are security holes only when used as an index or size of a buffer, or if the unexpected value of the overflow changes the flow of critical security code. Swift 4 catches most obvious integer overflows at compile time, such as when the number is clearly larger than the max value of the integer. 

For example, the following will not compile.

But a lot of the times the number will arrive dynamically at runtime, such as when a user enters information in a UITextField. Undefined Behavior Sanitizer is a new tool in Xcode 9 which detects signed integer overflow and other type-mismatch bugs. To enable it, go to Product > Scheme > Edit Scheme > Diagnostics, and turn on Undefined Behavior Sanitizer. Then in Build Settings > Undefined Behavior Sanitizer, set Enable Extra Integer Checks to Yes.

There's another thing worth mentioning about undefined behavior. Even though pure Swift hides pointers, references and copies of buffers are still used behind the scenes, so it's possible to run into behavior that you did not expect. For example, when you start iterating over collection indices, the indices could accidentally be modified by you during iteration.

Here we just caused the numbers array to point to a new array inside the loop. Then what does number point to? This would be normally be called a dangling reference, but in this case Swift implicitly creates a reference to a copy of the buffer of your array for the duration of the loop. That means that the print statement will actually print out 1, 2, and 3 instead of 1, 4, 5.... This is good! Swift is saving you from undefined behavior or an app crash, although you might not have expected that output either. Your peer developers won't expect your collection to be mutated during enumeration, so in general, be extra careful during enumeration that you are not altering the collection.

So Swift 4 has great security enforcement at compile time to catch these security vulnerabilities. There are many situations where the vulnerability doesn't exist until run time when there is user interaction. Swift also includes dynamic checking, which can catch many of the issues at run time too, but it's too expensive to do across threads so it's not performed for multithreaded code. Dynamic checking will catch many but not all violations, so it's still important to write secure code in the first place! 

With that, let's turn to another very common area for vulnerabilities—code injection attacks.

Injection and Format String Attacks

Format string attacks happen when an input string is parsed in your app as a command that you did not intend. While pure Swift strings are not susceptible to format string attacks, the Objective-C NSString and Core Foundation CFString classes are, and they are available from Swift. Both of these classes have methods such as stringWithFormat.

Let's say the user can enter arbitrary text from a UITextField.

This could be a security hole if the format string is handled directly.

Swift 4 tries to handle missing format string arguments by returning 0 or NULL, but it is especially a concern if the string will get passed back to the Objective-C runtime.

While most of the time the incorrect way will just cause a crash, an attacker can carefully craft a format string to write data to specific memory locations on the stack to alter your app behavior (such as changing an isAuthenticated variable). 

Another big culprit is NSPredicate, which can accept a format string that is used to specify what data is retrieved from Core Data. Clauses such as LIKE and CONTAINS allow wildcards and should be avoided, or at least only used for searches. The idea is to avoid enumeration of accounts, for example, where the attacker enters "a*" as the account name. If you change the LIKE clause to ==, this means the string literally has to match “a*”. 

Other common attacks happen by terminating the input string early with a single-quote character so additional commands can be entered. For instance, a login could be bypassed by entering ') OR 1=1 OR (password LIKE '* into the UITextField. That line translates to "where password is like anything”, which bypasses the authentication altogether. The solution is to fully escape any attempts at injection by adding your own double quotes in code. That way, any additional quotes from the user are seen as part of the input string instead of being a special terminating character:

One more way to safeguard against these attacks is to simply search for and exclude specific characters that you know could be harmful in the string. Examples would include quotes, or even dots and slashes. For instance, it is possible to do a directory traversal attack when input gets passed directly to the FileManager class. In this example, the user enters "../" to view the parent directory of the path instead of the intended sub-directory.

Other special characters might include a NULL terminating byte if the string gets used as a C string. Pointers to C strings require a NULL terminating byte. Because of this, it is possible to manipulate the string simply by introducing a NULL byte. The attacker might want to terminate the string early if there was a flag such as needs_auth=1, or when access is on by default and turned off explicitly such as with is_subscriber=0.

Parsing HTML, XML, and JSON strings requires special attention as well. The safest way to work with them is to use Foundation's native libraries that provide objects for each node, such as the NSXMLParser class. Swift 4 introduces type-safe serialization to external formats such as JSON. But if you are reading XML or HTML using a custom system, be sure that special characters from the user input cannot be used to instruct the interpreter.

  • < must become &lt.
  • > should get replaced with &gt.
  • & should become &amp.
  • Inside attribute values, any or ' need to become &quot and &apos, respectively.

Here is an example of a quick way to remove or replace specific characters:

A final area for injection attacks is inside URL handlers. Check to make sure user input is not used directly inside the custom URL handlers openURL and didReceiveRemoteNotification. Verify the URL is what you are expecting and that it doesn't allow a user to arbitrarily enter info to manipulate your logic. For example, instead of letting the user choose which screen in the stack to navigate to by index, allow only specific screens using an opaque identifier, such as t=es84jg5urw

If you are using WKWebViews in your app, it might be good to check the URLs that will be loaded there as well. You can overridedecidePolicyFor navigationAction, which lets you choose if you want to continue with the URL request. 

Some known webview tricks include loading custom URL schemes the developer did not intend, such as an app-id: to launch an entirely different app or sms: to send a text. Note that embedded webviews don't show a bar with the URL address or SSL status (the lock icon), so the user is not able to determine if the connection is trusted. 

If the webview is full screen, for example, the URL could be hijacked with a webpage that looks just like your login screen except directing the credentials to a malicious domain instead. Other attacks in the past have included cross-site scripting attacks that have leaked cookies and even the entire filesystem. 

The best prevention for all of the mentioned attacks is to take the time to design your interface using native UI controls instead of simply displaying a web-based version within your app.

So far, we've been looking at relatively straightforward kinds of attacks. But let's finish off with a more advanced attack that can happen in the runtime.

Runtime Hacking

Just as Swift becomes more vulnerable when you interface with C, interfacing with Objective-C brings separate vulnerabilities to the table. 

We have already seen the issues with NSString and format string attacks. Another point is that Objective-C is much more dynamic as a language, allowing loose types and methods to be passed around. If your Swift class inherits from NSObject, then it becomes open to Objective-C runtime attacks. 

The most common vulnerability involves dynamically swapping an important security method for another method. For example, a method that returns if a user is validated could be swapped for another method that will almost always return true, such as isRetinaDisplay. Minimizing the use of Objective-C will make your app more robust against this type of attack.

In Swift 4, methods on classes that inherit from an Objective-C class are only exposed to the Objective-C runtime if those methods or the classes themselves are marked with @attribute. Often the Swift function is called instead, even if the @objc attribute is used. This can happen when the method has an @objc attribute but is never actually called from Objective-C. 

In other words, Swift 4 introduces less @objc inference, so this limits the attack surface compared to previous versions. Still, to support the runtime features, Objective-C-based binaries need to retain a lot of class information that cannot be stripped away. This is enough for reverse engineers to rebuild the class interface to figure out what security sections to patch, for example. 

In Swift, there is less information exposed in the binary, and function names are mangled. However, the mangling can be undone by the Xcode tool swift-demangle. In fact, Swift functions have aconsistent naming scheme, indicating if each one is a Swift function or not, part of a class, module name and length, class name and length, method name and length, attributes, parameters, and return type. 

These names are shorter in Swift 4. If you're concerned about reverse engineering, make sure the release version of your app strips symbols by going to Build Settings > Deployment > Strip Swift Symbols and setting the option to Yes.

Beyond obfuscating critical security code, you can also request it to be inline. This means that any place that the function is called in your code, the code will be repeated in that place instead of existing only in one location of the binary. 

This way, if an attacker manages to bypass a particular security check, it will not affect any other occurrences of that check situated in other places of your code. Each check has to be patched or hooked, making it much more difficult to successfully perform a crack. You can inline code like this:

Conclusion

Thinking about security should be a big part of development. Merely expecting the language to be secure can lead to vulnerabilities that could have been avoided. Swift is popular for iOS development, but it is available for macOS desktop apps, tvOS, watchOS, and Linux (so you could use it for server-side components where the potential for code execution exploits is much higher). App sandboxing can be broken, such as in the case of jailbroken devices which allow unsigned code to run, so it's important to still think about security and pay attention to Xcode notices while you debug. 

A final tip is to treat compiler warnings as errors. You can force Xcode to do this by going to Build Settings and setting Treat Warnings as Errors to Yes. Don't forget to modernize your project settings when migrating to Xcode 9 to get improved warnings, and last but not least, make use of the new features available by adopting Swift 4 today!

For a primer on other aspects of secure coding for iOS, check out some of my other posts here on Envato Tuts+!

2017-11-08T18:00:00.000Z2017-11-08T18:00:00.000ZCollin Stuart

Secure Coding in Swift 4

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

From minimizing pointer use to strong type checking at compile time, Swift is a great language for secure development. But that means it's tempting to forget about security altogether. There are still vulnerabilities, and Swift is also enticing to new developers who haven't yet learned about security. 

This tutorial is a secure coding guide that will address changes in Swift 4 as well as the new tooling options available in Xcode 9 that will help you mitigate security vulnerabilities.

Pointers and Overflows

Many security vulnerabilities have revolved around C and its use of pointers. This is because pointers allow you to access raw memory locations, making it easier to read and write to the wrong area. It has been a major way for attackers to maliciously change a program. 

Swift mostly does away with pointers, but it still allows you to interface with C. Many APIs, including Apple's entire Core Foundation API, are based entirely in C, so it's very easy to introduce the use of pointers back into Swift. 

Fortunately, Apple has named the pointer types appropriately:UnsafePointer<T>, UnsafeRawPointer<T>UnsafeBufferPointer<T>, and UnsafeRawBufferPointer. There will come a time when the API you are interfacing with will return these types, and the main rule when using them is don't store or return pointers for later use. For example:

Because we accessed the pointer outside of the closure, we don't know for sure if the pointer still points to the expected memory contents. The safe way to use the pointer in this example would be to keep it, along with the print statement, within the closure. 

Pointers to strings and arrays also have no bounds checking. This means it's easy to use an unsafe pointer on an array but accidentally access beyond its boundary—a buffer overflow.

The good news is that Swift 4 attempts to crash the app instead of continuing with what would be called undefined behavior. We don't know what buffer[5] points to! However, Swift won't catch every case. Set a breakpoint after the following code and look at variables a and c. They will be set to 999.

This demonstrates a stack overflow because without an explicit allocation, variables are generally stored on the stack. 

In the next example, we make an allocation with a capacity of only a single Int8. Allocations are stored on the heap, so the next line will overflow the heap. For this example, Xcode only warns you with a note in the console that gets is unsafe.

So what's the best way to avoid overflows? It's extremely important when interfacing with C to do bounds checking on the input to make sure it's within range. 

You might be thinking that it's pretty hard to remember and find all of the different cases. So to help you out, Xcode comes with a very useful tool called Address Sanitizer. 

Address Sanitizer has been improved in Xcode 9. It is a tool that helps you catch invalid memory access such as the examples we have just seen. If you will be working with the Unsafe* types, it's a good idea to use the Address Sanitizer tool. It is not enabled by default, so to enable it, go to Product > Scheme > Edit Scheme > Diagnostics, and check Address Sanitizer. In Xcode 9 there is a new sub-option, Detect use of stack after return. This new option detects the use-after-scope and use-after-return vulnerabilities from our first example.

Sometimes overlooked is the integer overflow. This is because integer overflows are security holes only when used as an index or size of a buffer, or if the unexpected value of the overflow changes the flow of critical security code. Swift 4 catches most obvious integer overflows at compile time, such as when the number is clearly larger than the max value of the integer. 

For example, the following will not compile.

But a lot of the times the number will arrive dynamically at runtime, such as when a user enters information in a UITextField. Undefined Behavior Sanitizer is a new tool in Xcode 9 which detects signed integer overflow and other type-mismatch bugs. To enable it, go to Product > Scheme > Edit Scheme > Diagnostics, and turn on Undefined Behavior Sanitizer. Then in Build Settings > Undefined Behavior Sanitizer, set Enable Extra Integer Checks to Yes.

There's another thing worth mentioning about undefined behavior. Even though pure Swift hides pointers, references and copies of buffers are still used behind the scenes, so it's possible to run into behavior that you did not expect. For example, when you start iterating over collection indices, the indices could accidentally be modified by you during iteration.

Here we just caused the numbers array to point to a new array inside the loop. Then what does number point to? This would be normally be called a dangling reference, but in this case Swift implicitly creates a reference to a copy of the buffer of your array for the duration of the loop. That means that the print statement will actually print out 1, 2, and 3 instead of 1, 4, 5.... This is good! Swift is saving you from undefined behavior or an app crash, although you might not have expected that output either. Your peer developers won't expect your collection to be mutated during enumeration, so in general, be extra careful during enumeration that you are not altering the collection.

So Swift 4 has great security enforcement at compile time to catch these security vulnerabilities. There are many situations where the vulnerability doesn't exist until run time when there is user interaction. Swift also includes dynamic checking, which can catch many of the issues at run time too, but it's too expensive to do across threads so it's not performed for multithreaded code. Dynamic checking will catch many but not all violations, so it's still important to write secure code in the first place! 

With that, let's turn to another very common area for vulnerabilities—code injection attacks.

Injection and Format String Attacks

Format string attacks happen when an input string is parsed in your app as a command that you did not intend. While pure Swift strings are not susceptible to format string attacks, the Objective-C NSString and Core Foundation CFString classes are, and they are available from Swift. Both of these classes have methods such as stringWithFormat.

Let's say the user can enter arbitrary text from a UITextField.

This could be a security hole if the format string is handled directly.

Swift 4 tries to handle missing format string arguments by returning 0 or NULL, but it is especially a concern if the string will get passed back to the Objective-C runtime.

While most of the time the incorrect way will just cause a crash, an attacker can carefully craft a format string to write data to specific memory locations on the stack to alter your app behavior (such as changing an isAuthenticated variable). 

Another big culprit is NSPredicate, which can accept a format string that is used to specify what data is retrieved from Core Data. Clauses such as LIKE and CONTAINS allow wildcards and should be avoided, or at least only used for searches. The idea is to avoid enumeration of accounts, for example, where the attacker enters "a*" as the account name. If you change the LIKE clause to ==, this means the string literally has to match “a*”. 

Other common attacks happen by terminating the input string early with a single-quote character so additional commands can be entered. For instance, a login could be bypassed by entering ') OR 1=1 OR (password LIKE '* into the UITextField. That line translates to "where password is like anything”, which bypasses the authentication altogether. The solution is to fully escape any attempts at injection by adding your own double quotes in code. That way, any additional quotes from the user are seen as part of the input string instead of being a special terminating character:

One more way to safeguard against these attacks is to simply search for and exclude specific characters that you know could be harmful in the string. Examples would include quotes, or even dots and slashes. For instance, it is possible to do a directory traversal attack when input gets passed directly to the FileManager class. In this example, the user enters "../" to view the parent directory of the path instead of the intended sub-directory.

Other special characters might include a NULL terminating byte if the string gets used as a C string. Pointers to C strings require a NULL terminating byte. Because of this, it is possible to manipulate the string simply by introducing a NULL byte. The attacker might want to terminate the string early if there was a flag such as needs_auth=1, or when access is on by default and turned off explicitly such as with is_subscriber=0.

Parsing HTML, XML, and JSON strings requires special attention as well. The safest way to work with them is to use Foundation's native libraries that provide objects for each node, such as the NSXMLParser class. Swift 4 introduces type-safe serialization to external formats such as JSON. But if you are reading XML or HTML using a custom system, be sure that special characters from the user input cannot be used to instruct the interpreter.

  • < must become &lt.
  • > should get replaced with &gt.
  • & should become &amp.
  • Inside attribute values, any or ' need to become &quot and &apos, respectively.

Here is an example of a quick way to remove or replace specific characters:

A final area for injection attacks is inside URL handlers. Check to make sure user input is not used directly inside the custom URL handlers openURL and didReceiveRemoteNotification. Verify the URL is what you are expecting and that it doesn't allow a user to arbitrarily enter info to manipulate your logic. For example, instead of letting the user choose which screen in the stack to navigate to by index, allow only specific screens using an opaque identifier, such as t=es84jg5urw

If you are using WKWebViews in your app, it might be good to check the URLs that will be loaded there as well. You can overridedecidePolicyFor navigationAction, which lets you choose if you want to continue with the URL request. 

Some known webview tricks include loading custom URL schemes the developer did not intend, such as an app-id: to launch an entirely different app or sms: to send a text. Note that embedded webviews don't show a bar with the URL address or SSL status (the lock icon), so the user is not able to determine if the connection is trusted. 

If the webview is full screen, for example, the URL could be hijacked with a webpage that looks just like your login screen except directing the credentials to a malicious domain instead. Other attacks in the past have included cross-site scripting attacks that have leaked cookies and even the entire filesystem. 

The best prevention for all of the mentioned attacks is to take the time to design your interface using native UI controls instead of simply displaying a web-based version within your app.

So far, we've been looking at relatively straightforward kinds of attacks. But let's finish off with a more advanced attack that can happen in the runtime.

Runtime Hacking

Just as Swift becomes more vulnerable when you interface with C, interfacing with Objective-C brings separate vulnerabilities to the table. 

We have already seen the issues with NSString and format string attacks. Another point is that Objective-C is much more dynamic as a language, allowing loose types and methods to be passed around. If your Swift class inherits from NSObject, then it becomes open to Objective-C runtime attacks. 

The most common vulnerability involves dynamically swapping an important security method for another method. For example, a method that returns if a user is validated could be swapped for another method that will almost always return true, such as isRetinaDisplay. Minimizing the use of Objective-C will make your app more robust against this type of attack.

In Swift 4, methods on classes that inherit from an Objective-C class are only exposed to the Objective-C runtime if those methods or the classes themselves are marked with @attribute. Often the Swift function is called instead, even if the @objc attribute is used. This can happen when the method has an @objc attribute but is never actually called from Objective-C. 

In other words, Swift 4 introduces less @objc inference, so this limits the attack surface compared to previous versions. Still, to support the runtime features, Objective-C-based binaries need to retain a lot of class information that cannot be stripped away. This is enough for reverse engineers to rebuild the class interface to figure out what security sections to patch, for example. 

In Swift, there is less information exposed in the binary, and function names are mangled. However, the mangling can be undone by the Xcode tool swift-demangle. In fact, Swift functions have aconsistent naming scheme, indicating if each one is a Swift function or not, part of a class, module name and length, class name and length, method name and length, attributes, parameters, and return type. 

These names are shorter in Swift 4. If you're concerned about reverse engineering, make sure the release version of your app strips symbols by going to Build Settings > Deployment > Strip Swift Symbols and setting the option to Yes.

Beyond obfuscating critical security code, you can also request it to be inline. This means that any place that the function is called in your code, the code will be repeated in that place instead of existing only in one location of the binary. 

This way, if an attacker manages to bypass a particular security check, it will not affect any other occurrences of that check situated in other places of your code. Each check has to be patched or hooked, making it much more difficult to successfully perform a crack. You can inline code like this:

Conclusion

Thinking about security should be a big part of development. Merely expecting the language to be secure can lead to vulnerabilities that could have been avoided. Swift is popular for iOS development, but it is available for macOS desktop apps, tvOS, watchOS, and Linux (so you could use it for server-side components where the potential for code execution exploits is much higher). App sandboxing can be broken, such as in the case of jailbroken devices which allow unsigned code to run, so it's important to still think about security and pay attention to Xcode notices while you debug. 

A final tip is to treat compiler warnings as errors. You can force Xcode to do this by going to Build Settings and setting Treat Warnings as Errors to Yes. Don't forget to modernize your project settings when migrating to Xcode 9 to get improved warnings, and last but not least, make use of the new features available by adopting Swift 4 today!

For a primer on other aspects of secure coding for iOS, check out some of my other posts here on Envato Tuts+!

2017-11-08T18:00:00.000Z2017-11-08T18:00:00.000ZCollin Stuart

Implementing an Event Bus With LiveData

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

At the last Google I/O, the Android team released a set of powerful Android Architecture Components. They call it:

A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.

If you haven't learnt about them, you are strongly advised to check out our awesome series here on Envato Tuts+ about Android Architecture Components by Tin Megali. Make sure you go dive in! 

In this tutorial, I'll show you how to use the LiveData components from the Android Architectural Components to create an event bus. An event bus can be used to effectively communicate between Android components or between layers of your application—for example, communicating to an Activity from an IntentService that a file has finished downloading. 

We'll build a very simple app that triggers an IntentService to do some work—from an Activity. Our IntentService will then communicate back to the Activity when the work is completed. Our communication channel will be from the LiveData library. 

Prerequisites

To be able to follow this tutorial, you'll need:

You can also learn all the ins and outs of the Kotlin language in my Kotlin From Scratch series.

1. Create an Android Studio Project

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

Android Studio new project screen

2. Add the Lifecycle Components

After creating a new project, specify the LifeCycle and the LiveData artifacts in your app module's build.gradle. Note that as of this writing, the new architectural components are now in a stable version. So this means you can start using them in production apps. 

These artifacts are available at Google’s Maven repository. 

By adding the dependencies, we have taught gradle how to find the library. Make sure you remember to sync your project after adding them. 

3. Create the LifecycleOwner Activity Subclass

Here our MainActivity implements the LifecycleOwner interface. 

Our activity simply handles the standard activity lifecycle events. Inside each of the lifecycle events, it calls the registry.handleLifecycleEvent(), passing the corresponding event as a parameter.   

4. Create the Layout

We just have a Button that triggers the service. A TextView (invisible by default) shows the text "Work completed!" when the service communicates to our MainActivity

5. Initialize the Widgets

We declared our doWorkButton and resultTextView properties inside the MainActivity class with the lateinit modifier. We then initialize them inside the onCreate() method. Anytime the doWorkButton is clicked, we disable it (to prevent clicking the button more than once) and start our MyIntentService (we'll get to that shortly). 

6. Create the Custom Event Class

We just create a simple event message class that we want to pass around on the event bus (or LiveData). 

You can add more properties to this class if you want. 

7. Service Implementation

We implemented an IntentService called MyIntentService. Remember that IntentService lives outside the activity scope and has a background thread, so it is recommended to perform time-consuming tasks such as downloading or fetching remote data via an API inside it.  

However, note that in Android 8.0 if you don't make your IntentService a foreground service by using startForeground(), the Android system will not allow your service to run more than 1 minute—or else it will be stopped immediately. This mechanism is to efficiently manage system resources such as battery life. If your app is targeting Android 8.0, you are advised to use the JobIntentService instead. 

We create a nameless companion object whose companion class is MyIntentService. This companion object has a property called BUS, which is an instance of MutableLiveData.  Remember that companion objects are singletons, so this means that only a single instance of BUS exists. We also passed our CustomEvent as a type argument to the generic MutableLiveData class. 

Remember that the MutableLiveData class is a subclass of LiveData—and has a method called postValue() that can be called from a background thread. 

Inside onHandleIntent(), we have our business logic. Remember that this method is called on a background thread (one of the major differences between an IntentService and a normal Service). The IntentService ends immediately by itself when the onHandleIntent() method finishes its job.  

In our own case, we are simulating work being done (this work can be a file download or communicating with a remote API) by sleeping the current thread for 30 seconds. We then checked if our BUS has any active observers using the hasActiveObservers() method. If there are any, notify and pass our event message to them by using the method postValue(), or else we can simply show a notification (this was not coded in the example above for brevity's sake). 

Remember to include the service in your manifest file.

8. Observer Implementation

We need at least one observer for our mechanism to be useful. So inside the MainActivity class, we are going to subscribe an anonymous observer. 

Inside the onCreate() of MainActivity, we got the event bus BUS from MyIntentService. Then we registered an observer for the event bus (i.e. LiveData) using the observe() method. Next, we registered and inlined an anonymous observer, using the MainActivity as LifecycleOwner. This anonymous observer gets notified when any of the following happens:

  • There is already data available in the LiveData when it subscribes. 
  • The data inside the LiveData gets modified. 

When either of these occurs, we get the event data (from the LiveData) on the main application thread as input to the lambda. We then do the following inside the lambda's body:

  • Make the resultTextView visible.
  • Enable the doWorkButton.
  • Log our custom event property eventProp value to Logcat.

Remember the following about LiveData:

  • When a new observer is attached to our LiveData after a configuration change, LiveData will send the last data it received to the observer—even without us explicitly telling it to do so. In other words, it does this automatically. 
  • When the LifecycleOwner is destroyed, the observer will automatically be unsubscribed. 
  • Finally, LiveData is an observable that is lifecycle-aware. According to the docs:
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

9. Testing the App

Finally, you can run the app! Click the Do Work button and after 30 seconds, you'll see the result. 

Tutorial project result

You can get the complete source code from our GitHub repo.

Conclusion

In this tutorial, you learned how to easily use the LiveData components from the Android Architectural Components to create an event bus—so as to effectively communicate with components of your app. 

I assume you're aware of other libraries you can use for the same purpose, such as Android LocalBroadcastManager or the popular greenrobot EventBus to implement an event bus in your Android application. You can see that using the LiveData instead is preferable to them—because you avoid writing boilerplate or verbose code, and LiveData provides you with better flexibility. 

To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

2017-11-10T14:00:00.000Z2017-11-10T14:00:00.000ZChike Mgbemena

Implementing an Event Bus With LiveData

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

At the last Google I/O, the Android team released a set of powerful Android Architecture Components. They call it:

A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.

If you haven't learnt about them, you are strongly advised to check out our awesome series here on Envato Tuts+ about Android Architecture Components by Tin Megali. Make sure you go dive in! 

In this tutorial, I'll show you how to use the LiveData components from the Android Architectural Components to create an event bus. An event bus can be used to effectively communicate between Android components or between layers of your application—for example, communicating to an Activity from an IntentService that a file has finished downloading. 

We'll build a very simple app that triggers an IntentService to do some work—from an Activity. Our IntentService will then communicate back to the Activity when the work is completed. Our communication channel will be from the LiveData library. 

Prerequisites

To be able to follow this tutorial, you'll need:

You can also learn all the ins and outs of the Kotlin language in my Kotlin From Scratch series.

1. Create an Android Studio Project

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

Android Studio new project screen

2. Add the Lifecycle Components

After creating a new project, specify the LifeCycle and the LiveData artifacts in your app module's build.gradle. Note that as of this writing, the new architectural components are now in a stable version. So this means you can start using them in production apps. 

These artifacts are available at Google’s Maven repository. 

By adding the dependencies, we have taught gradle how to find the library. Make sure you remember to sync your project after adding them. 

3. Create the LifecycleOwner Activity Subclass

Here our MainActivity implements the LifecycleOwner interface. 

Our activity simply handles the standard activity lifecycle events. Inside each of the lifecycle events, it calls the registry.handleLifecycleEvent(), passing the corresponding event as a parameter.   

4. Create the Layout

We just have a Button that triggers the service. A TextView (invisible by default) shows the text "Work completed!" when the service communicates to our MainActivity

5. Initialize the Widgets

We declared our doWorkButton and resultTextView properties inside the MainActivity class with the lateinit modifier. We then initialize them inside the onCreate() method. Anytime the doWorkButton is clicked, we disable it (to prevent clicking the button more than once) and start our MyIntentService (we'll get to that shortly). 

6. Create the Custom Event Class

We just create a simple event message class that we want to pass around on the event bus (or LiveData). 

You can add more properties to this class if you want. 

7. Service Implementation

We implemented an IntentService called MyIntentService. Remember that IntentService lives outside the activity scope and has a background thread, so it is recommended to perform time-consuming tasks such as downloading or fetching remote data via an API inside it.  

However, note that in Android 8.0 if you don't make your IntentService a foreground service by using startForeground(), the Android system will not allow your service to run more than 1 minute—or else it will be stopped immediately. This mechanism is to efficiently manage system resources such as battery life. If your app is targeting Android 8.0, you are advised to use the JobIntentService instead. 

We create a nameless companion object whose companion class is MyIntentService. This companion object has a property called BUS, which is an instance of MutableLiveData.  Remember that companion objects are singletons, so this means that only a single instance of BUS exists. We also passed our CustomEvent as a type argument to the generic MutableLiveData class. 

Remember that the MutableLiveData class is a subclass of LiveData—and has a method called postValue() that can be called from a background thread. 

Inside onHandleIntent(), we have our business logic. Remember that this method is called on a background thread (one of the major differences between an IntentService and a normal Service). The IntentService ends immediately by itself when the onHandleIntent() method finishes its job.  

In our own case, we are simulating work being done (this work can be a file download or communicating with a remote API) by sleeping the current thread for 30 seconds. We then checked if our BUS has any active observers using the hasActiveObservers() method. If there are any, notify and pass our event message to them by using the method postValue(), or else we can simply show a notification (this was not coded in the example above for brevity's sake). 

Remember to include the service in your manifest file.

8. Observer Implementation

We need at least one observer for our mechanism to be useful. So inside the MainActivity class, we are going to subscribe an anonymous observer. 

Inside the onCreate() of MainActivity, we got the event bus BUS from MyIntentService. Then we registered an observer for the event bus (i.e. LiveData) using the observe() method. Next, we registered and inlined an anonymous observer, using the MainActivity as LifecycleOwner. This anonymous observer gets notified when any of the following happens:

  • There is already data available in the LiveData when it subscribes. 
  • The data inside the LiveData gets modified. 

When either of these occurs, we get the event data (from the LiveData) on the main application thread as input to the lambda. We then do the following inside the lambda's body:

  • Make the resultTextView visible.
  • Enable the doWorkButton.
  • Log our custom event property eventProp value to Logcat.

Remember the following about LiveData:

  • When a new observer is attached to our LiveData after a configuration change, LiveData will send the last data it received to the observer—even without us explicitly telling it to do so. In other words, it does this automatically. 
  • When the LifecycleOwner is destroyed, the observer will automatically be unsubscribed. 
  • Finally, LiveData is an observable that is lifecycle-aware. According to the docs:
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

9. Testing the App

Finally, you can run the app! Click the Do Work button and after 30 seconds, you'll see the result. 

Tutorial project result

You can get the complete source code from our GitHub repo.

Conclusion

In this tutorial, you learned how to easily use the LiveData components from the Android Architectural Components to create an event bus—so as to effectively communicate with components of your app. 

I assume you're aware of other libraries you can use for the same purpose, such as Android LocalBroadcastManager or the popular greenrobot EventBus to implement an event bus in your Android application. You can see that using the LiveData instead is preferable to them—because you avoid writing boilerplate or verbose code, and LiveData provides you with better flexibility. 

To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

2017-11-10T14:00:00.000Z2017-11-10T14:00:00.000ZChike Mgbemena

Java 8 for Android Development: Stream API and Date & Time Libraries

$
0
0

In this three-part series, we’ve been exploring all the major Java 8 features that you can start using in your Android projects today.

In Cleaner Code With Lambda Expressions, we focused on cutting boilerplate from your projects using lambda expressions, and then in Default and Static Methods, we saw how to make these lambda expressions more concise by combining them with method references. We also covered Repeating Annotations and how to declare non-abstract methods in your interfaces using default and static interface methods.

In this final post, we’re going to look at type annotations, functional interfaces, and how to take a more functional approach to data processing with Java 8’s new Stream API.

I’ll also show you how to access some additional Java 8 features that aren’t currently supported by the Android platform, using the Joda-Time and ThreeTenABP libraries.

Type Annotations

Annotations help you write code that’s more robust and less error-prone, by informing code inspection tools such as Lint about the errors they should be looking out for. These inspection tools will then warn you if a piece of code doesn’t conform to the rules laid out by these annotations.

Annotations aren’t a new feature (in fact, they date back to Java 5.0), but in previous versions of Java it was only possible to apply annotations to declarations.

With the release of Java 8, you can now use annotations anywhere you've used a type, including method receivers; class instance creation expressions; the implementation of interfaces; generics and arrays; the specification of throws and implements clauses; and type casting.

Frustratingly, although Java 8 does make it possible to use annotations in more locations than ever before, it doesn’t provide any annotations that are specific to types.

Android’s Annotations Support Library provides access to some additional annotations, such as @Nullable, @NonNull, and annotations for validating resource types such as  @DrawableRes, @DimenRes, @ColorRes, and @StringRes. However, you may also want to use a third-party static analysis tool, such as the Checker Framework, which was co-developed with the JSR 308 specification (the Annotations on Java Types specification). This framework provides its own set of annotations that can be applied to types, plus a number of "checkers" (annotation processors) that hook into the compilation process and perform specific “checks” for each type annotation that’s included in the Checker Framework.

Since Type Annotations don’t affect runtime operation, you can use Java 8’s Type Annotations in your projects while remaining backwards compatible with earlier versions of Java.

Stream API

The Stream API offers an alternative, “pipes-and-filters” approach to collections processing.

Prior to Java 8, you manipulated collections manually, typically by iterating over the collection and operating on each element in turn. This explicit looping required a lot of boilerplate, plus it’s difficult to grasp the for-loop structure until you reach the body of the loop.

The Stream API gives you a way of processing data more efficiently, by performing a single run over that data—regardless of the amount of data you’re processing, or whether you're performing multiple computations.

In Java 8, every class that implements java.util.Collection has a stream method that can convert its instances into Stream objects. For example, if you have an Array:

Then you can convert it into a Stream with the following:

The Stream API processes data by carrying values from a source, through a series of computational steps, known as a stream pipeline. A stream pipeline is composed of the following:

  • A source, such as a Collection, array, or generator function.
  • Zero or more intermediate “lazy” operations. Intermediate operations don’t start processing elements until you invoke a terminal operation—which is why they’re considered lazy. For example, calling Stream.filter() on a data source merely sets up the stream pipeline; no filtering actually occurs until you call the terminal operation. This makes it possible to string multiple operations together, and then perform all of these computations in a single pass of the data. Intermediate operations produce a new stream (for example, filter will produce a stream containing the filtered elements) without modifying the data source, so you’re free to use the original data elsewhere in your project, or create multiple streams from the same source.
  • A terminal operation, such as Stream.forEach. When you invoke the terminal operation, all of your intermediate operations will run and produce a new stream. A stream isn’t capable of storing elements, so as soon as you invoke a terminal operation, that stream is considered “consumed” and is no longer usable. If you do want to revisit the elements of a stream, then you’ll need to generate a new stream from the original data source.

Creating a Stream

There are various ways of obtaining a stream from a data source, including:

  • Stream.of() Creates a stream from individual values:

  • IntStream.range() Creates a stream from a range of numbers:

  • Stream.iterate() Creates a stream by repeatedly applying an operator to each element. For example, here we’re creating a stream where each element increases in value by one:

Transforming a Stream With Operations

There are a ton of operations that you can use to perform functional-style computations on your streams. In this section, I’m going to cover just a few of the most commonly used stream operations.

Map

The map() operation takes a lambda expression as its only argument, and uses this expression to transform the value or the type of every element in the stream. For example, the following gives us a new stream, where every String has been converted to uppercase:

Limit

This operation sets a limit on the size of a stream. For example, if you wanted to create a new stream containing a maximum of five values, then you’d use the following:

Filter

The filter(Predicate<T>) operation lets you define filtering criteria using a lambda expression. This lambda expression must return a boolean value that determines whether each element should be included in the resulting stream. For example, if you had an array of strings and wanted to filter out any strings that contained less than three characters, you’d use the following:  

Sorted

This operation sorts the elements of a stream. For example, the following returns a stream of numbers arranged in ascending order:

Parallel Processing

All stream operations can execute in serial or in parallel, although streams are sequential unless you explicitly specify otherwise. For example, the following will process each element one by one:

To execute a stream in parallel, you need to explicitly mark that stream as parallel, using the parallel() method:

Under the hood, parallel streams use the Fork/Join Framework, so the number of available threads always equals the number of available cores in the CPU.

The drawback to parallel streams is that different cores may be involved each time the code is executed, so you’ll typically get a different output with each execution. Therefore, you should only use parallel streams when the processing order is unimportant, and avoid parallel streams when performing order-based operations, such as findFirst().

Terminal Operations

You collect the results from a stream using a terminal operation, which is always the last element in a chain of stream methods, and always returns something other than a stream.

There are a few different types of terminal operations that return various types of data, but in this section we’re going to look at two of the most commonly used terminal operations.

Collect

The Collect operation gathers all the processed elements into a container, such as a List or Set. Java 8 provides a Collectors utility class, so you don’t need to worry about implementing the Collectors interface, plus factories for many common collectors, including toList(), toSet(), and toCollection().

The following code will produce a List containing red shapes only:

Alternatively, you could collect these filtered elements into a Set:

forEach

The forEach() operation performs some action on each element of the stream, making it the Stream API’s equivalent of a for-each statement.

If you had an items list, then you could use forEach to print all the items that are included in this List:

In the above example we’re using a lambda expression, so it's possible to perform the same work in less code, using a method reference:

Functional Interfaces

A functional interface is an interface that contains exactly one abstract method, known as the functional method.

The concept of single-method interfaces isn’t new—Runnable, Comparator, Callable, and OnClickListener are all examples of this kind of interface, although in previous versions of Java they were known as Single Abstract Method Interfaces (SAM interfaces).  

This is more than a simple name change, as there are some notable differences in how you work with functional (or SAM) interfaces in Java 8, compared with earlier versions.

Prior to Java 8, you typically instantiated a functional interface using a bulky anonymous class implementation. For example, here we’re creating an instance of Runnable using an anonymous class:

As we saw back in part one, when you have a single-method interface, you can instantiate that interface using a lambda expression, rather than an anonymous class. Now, we can update this rule: you can instantiate functional interfaces, using a lambda expression. For example:

Java 8 also introduces a @FunctionalInterface annotation that lets you mark an interface as a functional interface:

To ensure backwards compatibility with earlier versions of Java, the @FunctionalInterface annotation is optional; however, it’s recommended to help ensure you’re implementing your functional interfaces correctly.

If you try to implement two or more methods in an interface that’s marked as @FunctionalInterface, then the compiler will complain that it’s discovered multiple non-overriding abstract methods. For example, the following won’t compile:

And, if you try to compile a @FunctionInterface interface that contains zero methods, then you’re going to encounter a No target method found error.

Functional interfaces must contain exactly one abstract method, but since default and static methods don’t have a body, they’re considered non-abstract. This means that you can include multiple default and static methods in an interface, mark it as @FunctionalInterface, and it’ll still compile.

Java 8 also added a java.util.function package that contains lots of functional interfaces. It's well worth taking the time to familiarize yourself with all of these new functional interfaces, just so you know exactly what’s available out of the box.

JSR-310: Java’s New Date and Time API

Working with date and time in Java has never been particularly straightforward, with many APIs omitting important functionality, such as time-zone information.

Java 8 introduced a new Date and Time API (JSR-310) that aims to resolve these issues, but unfortunately at the time of writing this API isn’t supported on the Android platform. However, you can use some of the new Date and Time features in your Android projects today, using a third-party library.

In this final section, I’m going to show you how to set up and use two popular third-party libraries that make it possible to use Java 8’s Date and Time API on Android.

ThreeTen Android Backport

ThreeTen Android Backport (also known as ThreeTenABP) is an adaption of the popular ThreeTen backport project, which provides an implementation of JSR-310 for Java 6.0 and Java 7.0. ThreeTenABP is designed to provide access to all the Date and Time API classes (albeit with a different package name) without adding a large number of methods to your Android projects.

To start using this library, open your module-level build.gradle file and add ThreeTenABP as a project dependency:

You then need to add the ThreeTenABP import statement:

And initialize the time-zone information in your Application.onCreate() method:

ThreeTenABP contains two classes that display two “types” of time and date information:

  • LocalDateTime, which stores a time and a date in the format 2017-10-16T13:17:57.138
  • ZonedDateTime, which is time-zone aware and stores date and time information in the following format: 2011-12-03T10:15:30+01:00[Europe/Paris]

To give you an idea of how you’d use this library to retrieve date and time information, let’s use the LocalDateTime class to display the current date and time:

Display the date and time using the ThreeTen Android Backport library

This isn’t the most user-friendly way of displaying the date and time! To parse this raw data into something more human-readable, you can use the DateTimeFormatter class and set it to one of the following values:

  • BASIC_ISO_DATE. Formats the date as 2017-1016+01.00
  • ISO_LOCAL_DATE. Formats the date as 2017-10-16
  • ISO_LOCAL_TIME. Formats the time as 14:58:43.242
  • ISO_LOCAL_DATE_TIME. Formats the date and the time as 2017-10-16T14:58:09.616
  • ISO_OFFSET_DATE. Formats the date as 2017-10-16+01.00
  • ISO_OFFSET_TIME.  Formats the time as 14:58:56.218+01:00
  • ISO_OFFSET_DATE_TIME. Formats the date and time as 2017-10-16T14:5836.758+01:00
  • ISO_ZONED_DATE_TIME. Formats the date and time as 2017-10-16T14:58:51.324+01:00(Europe/London)
  • ISO_INSTANT. Formats the date and time as 2017-10-16T13:52:45.246Z
  • ISO_DATE. Formats the date as 2017-10-16+01:00
  • ISO_TIME. Formats the time as 14:58:40.945+01:00
  • ISO_DATE_TIME. Formats the date and time as 2017-10-16T14:55:32.263+01:00(Europe/London)
  • ISO_ORDINAL_DATE. Formats the date as 2017-289+01:00
  • ISO_WEEK_DATE. Formats the date as 2017-W42-1+01:00
  • RFC_1123_DATE_TIME. Formats the date and time as Mon, 16 OCT 2017 14:58:43+01:00

Here, we’re updating our app to display the date and time with DateTimeFormatter.ISO_DATE formatting:

To display this information in a different format, simply substitute DateTimeFormatter.ISO_DATE for another value. For example:

Joda-Time

Prior to Java 8, the Joda-Time library was considered the standard library for handling date and time in Java, to the point where Java 8’s new Date and Time API actually draws “heavily on experience gained from the Joda-Time project.”

While the Joda-Time website recommends that users migrate to Java 8 Date and Time as soon as possible, since Android doesn’t currently support this API, Joda-Time is still a viable option for Android development. However, note that Joda-Time does have a large API and loads time-zone information using a JAR resource, both of which can affect your app’s performance.

To start working with the Joda-Time library, open your module-level build.gradle file and add the following:

The Joda-Time library has six major date and time classes:

  • Instant: Represents a point in the timeline; for example, you can obtain the current date and time by calling Instant.now().
  • DateTime: A general-purpose replacement for JDK’s Calendar class.
  • LocalDate: A date without a time, or any reference to a time zone.
  • LocalTime: A time without a date or any reference to a time zone, for example 14:00:00.
  • LocalDateTime: A local date and time, still without any time-zone information.
  • ZonedDateTime: A date and time with a time zone.

Let’s take a look at how you’d print date and time using Joda-Time. In the following example I’m reusing code from our ThreeTenABP example, so to make things more interesting I’m also using withZone to convert the date and time into a ZonedDateTime value.

Display the date and time using the Joda-Time library

You’ll find a full list of supported time zones in the official Joda-Time docs.

Conclusion

In this post, we looked at how to create more robust code using type annotations, and explored the “pipes-and-filters” approach to data processing with Java 8’s new Stream API.

We also looked at how interfaces have evolved in Java 8 and how to use them in combination with other features we’ve been exploring throughout this series, including lambda expressions and static interface methods.

To wrap things up, I showed you how to access some additional Java 8 features that Android currently doesn’t support by default, using the Joda-Time and ThreeTenABP projects.

You can learn more about the Java 8 release at Oracle’s website.

And while you're here, check out some of our other posts about Java 8 and Android development!

2017-11-14T12:51:31.437Z2017-11-14T12:51:31.437ZJessica Thornsby

Java 8 for Android Development: Stream API and Date & Time Libraries

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

In this three-part series, we’ve been exploring all the major Java 8 features that you can start using in your Android projects today.

In Cleaner Code With Lambda Expressions, we focused on cutting boilerplate from your projects using lambda expressions, and then in Default and Static Methods, we saw how to make these lambda expressions more concise by combining them with method references. We also covered Repeating Annotations and how to declare non-abstract methods in your interfaces using default and static interface methods.

In this final post, we’re going to look at type annotations, functional interfaces, and how to take a more functional approach to data processing with Java 8’s new Stream API.

I’ll also show you how to access some additional Java 8 features that aren’t currently supported by the Android platform, using the Joda-Time and ThreeTenABP libraries.

Type Annotations

Annotations help you write code that’s more robust and less error-prone, by informing code inspection tools such as Lint about the errors they should be looking out for. These inspection tools will then warn you if a piece of code doesn’t conform to the rules laid out by these annotations.

Annotations aren’t a new feature (in fact, they date back to Java 5.0), but in previous versions of Java it was only possible to apply annotations to declarations.

With the release of Java 8, you can now use annotations anywhere you've used a type, including method receivers; class instance creation expressions; the implementation of interfaces; generics and arrays; the specification of throws and implements clauses; and type casting.

Frustratingly, although Java 8 does make it possible to use annotations in more locations than ever before, it doesn’t provide any annotations that are specific to types.

Android’s Annotations Support Library provides access to some additional annotations, such as @Nullable, @NonNull, and annotations for validating resource types such as  @DrawableRes, @DimenRes, @ColorRes, and @StringRes. However, you may also want to use a third-party static analysis tool, such as the Checker Framework, which was co-developed with the JSR 308 specification (the Annotations on Java Types specification). This framework provides its own set of annotations that can be applied to types, plus a number of "checkers" (annotation processors) that hook into the compilation process and perform specific “checks” for each type annotation that’s included in the Checker Framework.

Since Type Annotations don’t affect runtime operation, you can use Java 8’s Type Annotations in your projects while remaining backwards compatible with earlier versions of Java.

Stream API

The Stream API offers an alternative, “pipes-and-filters” approach to collections processing.

Prior to Java 8, you manipulated collections manually, typically by iterating over the collection and operating on each element in turn. This explicit looping required a lot of boilerplate, plus it’s difficult to grasp the for-loop structure until you reach the body of the loop.

The Stream API gives you a way of processing data more efficiently, by performing a single run over that data—regardless of the amount of data you’re processing, or whether you're performing multiple computations.

In Java 8, every class that implements java.util.Collection has a stream method that can convert its instances into Stream objects. For example, if you have an Array:

Then you can convert it into a Stream with the following:

The Stream API processes data by carrying values from a source, through a series of computational steps, known as a stream pipeline. A stream pipeline is composed of the following:

  • A source, such as a Collection, array, or generator function.
  • Zero or more intermediate “lazy” operations. Intermediate operations don’t start processing elements until you invoke a terminal operation—which is why they’re considered lazy. For example, calling Stream.filter() on a data source merely sets up the stream pipeline; no filtering actually occurs until you call the terminal operation. This makes it possible to string multiple operations together, and then perform all of these computations in a single pass of the data. Intermediate operations produce a new stream (for example, filter will produce a stream containing the filtered elements) without modifying the data source, so you’re free to use the original data elsewhere in your project, or create multiple streams from the same source.
  • A terminal operation, such as Stream.forEach. When you invoke the terminal operation, all of your intermediate operations will run and produce a new stream. A stream isn’t capable of storing elements, so as soon as you invoke a terminal operation, that stream is considered “consumed” and is no longer usable. If you do want to revisit the elements of a stream, then you’ll need to generate a new stream from the original data source.

Creating a Stream

There are various ways of obtaining a stream from a data source, including:

  • Stream.of() Creates a stream from individual values:

  • IntStream.range() Creates a stream from a range of numbers:

  • Stream.iterate() Creates a stream by repeatedly applying an operator to each element. For example, here we’re creating a stream where each element increases in value by one:

Transforming a Stream With Operations

There are a ton of operations that you can use to perform functional-style computations on your streams. In this section, I’m going to cover just a few of the most commonly used stream operations.

Map

The map() operation takes a lambda expression as its only argument, and uses this expression to transform the value or the type of every element in the stream. For example, the following gives us a new stream, where every String has been converted to uppercase:

Limit

This operation sets a limit on the size of a stream. For example, if you wanted to create a new stream containing a maximum of five values, then you’d use the following:

Filter

The filter(Predicate<T>) operation lets you define filtering criteria using a lambda expression. This lambda expression must return a boolean value that determines whether each element should be included in the resulting stream. For example, if you had an array of strings and wanted to filter out any strings that contained less than three characters, you’d use the following:  

Sorted

This operation sorts the elements of a stream. For example, the following returns a stream of numbers arranged in ascending order:

Parallel Processing

All stream operations can execute in serial or in parallel, although streams are sequential unless you explicitly specify otherwise. For example, the following will process each element one by one:

To execute a stream in parallel, you need to explicitly mark that stream as parallel, using the parallel() method:

Under the hood, parallel streams use the Fork/Join Framework, so the number of available threads always equals the number of available cores in the CPU.

The drawback to parallel streams is that different cores may be involved each time the code is executed, so you’ll typically get a different output with each execution. Therefore, you should only use parallel streams when the processing order is unimportant, and avoid parallel streams when performing order-based operations, such as findFirst().

Terminal Operations

You collect the results from a stream using a terminal operation, which is always the last element in a chain of stream methods, and always returns something other than a stream.

There are a few different types of terminal operations that return various types of data, but in this section we’re going to look at two of the most commonly used terminal operations.

Collect

The Collect operation gathers all the processed elements into a container, such as a List or Set. Java 8 provides a Collectors utility class, so you don’t need to worry about implementing the Collectors interface, plus factories for many common collectors, including toList(), toSet(), and toCollection().

The following code will produce a List containing red shapes only:

Alternatively, you could collect these filtered elements into a Set:

forEach

The forEach() operation performs some action on each element of the stream, making it the Stream API’s equivalent of a for-each statement.

If you had an items list, then you could use forEach to print all the items that are included in this List:

In the above example we’re using a lambda expression, so it's possible to perform the same work in less code, using a method reference:

Functional Interfaces

A functional interface is an interface that contains exactly one abstract method, known as the functional method.

The concept of single-method interfaces isn’t new—Runnable, Comparator, Callable, and OnClickListener are all examples of this kind of interface, although in previous versions of Java they were known as Single Abstract Method Interfaces (SAM interfaces).  

This is more than a simple name change, as there are some notable differences in how you work with functional (or SAM) interfaces in Java 8, compared with earlier versions.

Prior to Java 8, you typically instantiated a functional interface using a bulky anonymous class implementation. For example, here we’re creating an instance of Runnable using an anonymous class:

As we saw back in part one, when you have a single-method interface, you can instantiate that interface using a lambda expression, rather than an anonymous class. Now, we can update this rule: you can instantiate functional interfaces, using a lambda expression. For example:

Java 8 also introduces a @FunctionalInterface annotation that lets you mark an interface as a functional interface:

To ensure backwards compatibility with earlier versions of Java, the @FunctionalInterface annotation is optional; however, it’s recommended to help ensure you’re implementing your functional interfaces correctly.

If you try to implement two or more methods in an interface that’s marked as @FunctionalInterface, then the compiler will complain that it’s discovered multiple non-overriding abstract methods. For example, the following won’t compile:

And, if you try to compile a @FunctionInterface interface that contains zero methods, then you’re going to encounter a No target method found error.

Functional interfaces must contain exactly one abstract method, but since default and static methods don’t have a body, they’re considered non-abstract. This means that you can include multiple default and static methods in an interface, mark it as @FunctionalInterface, and it’ll still compile.

Java 8 also added a java.util.function package that contains lots of functional interfaces. It's well worth taking the time to familiarize yourself with all of these new functional interfaces, just so you know exactly what’s available out of the box.

JSR-310: Java’s New Date and Time API

Working with date and time in Java has never been particularly straightforward, with many APIs omitting important functionality, such as time-zone information.

Java 8 introduced a new Date and Time API (JSR-310) that aims to resolve these issues, but unfortunately at the time of writing this API isn’t supported on the Android platform. However, you can use some of the new Date and Time features in your Android projects today, using a third-party library.

In this final section, I’m going to show you how to set up and use two popular third-party libraries that make it possible to use Java 8’s Date and Time API on Android.

ThreeTen Android Backport

ThreeTen Android Backport (also known as ThreeTenABP) is an adaption of the popular ThreeTen backport project, which provides an implementation of JSR-310 for Java 6.0 and Java 7.0. ThreeTenABP is designed to provide access to all the Date and Time API classes (albeit with a different package name) without adding a large number of methods to your Android projects.

To start using this library, open your module-level build.gradle file and add ThreeTenABP as a project dependency:

You then need to add the ThreeTenABP import statement:

And initialize the time-zone information in your Application.onCreate() method:

ThreeTenABP contains two classes that display two “types” of time and date information:

  • LocalDateTime, which stores a time and a date in the format 2017-10-16T13:17:57.138
  • ZonedDateTime, which is time-zone aware and stores date and time information in the following format: 2011-12-03T10:15:30+01:00[Europe/Paris]

To give you an idea of how you’d use this library to retrieve date and time information, let’s use the LocalDateTime class to display the current date and time:

Display the date and time using the ThreeTen Android Backport library

This isn’t the most user-friendly way of displaying the date and time! To parse this raw data into something more human-readable, you can use the DateTimeFormatter class and set it to one of the following values:

  • BASIC_ISO_DATE. Formats the date as 2017-1016+01.00
  • ISO_LOCAL_DATE. Formats the date as 2017-10-16
  • ISO_LOCAL_TIME. Formats the time as 14:58:43.242
  • ISO_LOCAL_DATE_TIME. Formats the date and the time as 2017-10-16T14:58:09.616
  • ISO_OFFSET_DATE. Formats the date as 2017-10-16+01.00
  • ISO_OFFSET_TIME.  Formats the time as 14:58:56.218+01:00
  • ISO_OFFSET_DATE_TIME. Formats the date and time as 2017-10-16T14:5836.758+01:00
  • ISO_ZONED_DATE_TIME. Formats the date and time as 2017-10-16T14:58:51.324+01:00(Europe/London)
  • ISO_INSTANT. Formats the date and time as 2017-10-16T13:52:45.246Z
  • ISO_DATE. Formats the date as 2017-10-16+01:00
  • ISO_TIME. Formats the time as 14:58:40.945+01:00
  • ISO_DATE_TIME. Formats the date and time as 2017-10-16T14:55:32.263+01:00(Europe/London)
  • ISO_ORDINAL_DATE. Formats the date as 2017-289+01:00
  • ISO_WEEK_DATE. Formats the date as 2017-W42-1+01:00
  • RFC_1123_DATE_TIME. Formats the date and time as Mon, 16 OCT 2017 14:58:43+01:00

Here, we’re updating our app to display the date and time with DateTimeFormatter.ISO_DATE formatting:

To display this information in a different format, simply substitute DateTimeFormatter.ISO_DATE for another value. For example:

Joda-Time

Prior to Java 8, the Joda-Time library was considered the standard library for handling date and time in Java, to the point where Java 8’s new Date and Time API actually draws “heavily on experience gained from the Joda-Time project.”

While the Joda-Time website recommends that users migrate to Java 8 Date and Time as soon as possible, since Android doesn’t currently support this API, Joda-Time is still a viable option for Android development. However, note that Joda-Time does have a large API and loads time-zone information using a JAR resource, both of which can affect your app’s performance.

To start working with the Joda-Time library, open your module-level build.gradle file and add the following:

The Joda-Time library has six major date and time classes:

  • Instant: Represents a point in the timeline; for example, you can obtain the current date and time by calling Instant.now().
  • DateTime: A general-purpose replacement for JDK’s Calendar class.
  • LocalDate: A date without a time, or any reference to a time zone.
  • LocalTime: A time without a date or any reference to a time zone, for example 14:00:00.
  • LocalDateTime: A local date and time, still without any time-zone information.
  • ZonedDateTime: A date and time with a time zone.

Let’s take a look at how you’d print date and time using Joda-Time. In the following example I’m reusing code from our ThreeTenABP example, so to make things more interesting I’m also using withZone to convert the date and time into a ZonedDateTime value.

Display the date and time using the Joda-Time library

You’ll find a full list of supported time zones in the official Joda-Time docs.

Conclusion

In this post, we looked at how to create more robust code using type annotations, and explored the “pipes-and-filters” approach to data processing with Java 8’s new Stream API.

We also looked at how interfaces have evolved in Java 8 and how to use them in combination with other features we’ve been exploring throughout this series, including lambda expressions and static interface methods.

To wrap things up, I showed you how to access some additional Java 8 features that Android currently doesn’t support by default, using the Joda-Time and ThreeTenABP projects.

You can learn more about the Java 8 release at Oracle’s website.

And while you're here, check out some of our other posts about Java 8 and Android development!

2017-11-14T12:51:31.437Z2017-11-14T12:51:31.437ZJessica Thornsby

Ionic From Scratch: Getting Started With Ionic

$
0
0

So you've heard about Ionic and you're wondering how to get started? In this tutorial you will learn how to set up an Ionic development environment on your computer, as well as how to create an Ionic project. 

Requirements for Coding an Ionic App

Well, congratulations, if you are viewing this article via a computer you have one of the most important prerequisites for developing Ionic apps: you will require a physical personal computer (PC) to do so. This can be a computer running Windows, Mac, or Linux.

Since we build Ionic apps using web technologies, you will also need web development tools installed. This includes a web browser (preferably Google Chrome) to run and debug our apps, and a text editor (such as Sublime, Atom, or Visual Studio Code) to write and edit our code. If you are new to development, I would recommend Visual Studio Code as it is commonly used and free.

With these basic requirements installed on your computer, let's go ahead and install the dependencies we need to build Ionic apps.

Setting Up Dependencies and Installing Ionic

Unfortunately, there is no single installer package that automatically installs an Ionic development environment on your computer. Regardless of your operating system, you have to install each of the required dependencies manually. So let's go ahead and get started setting up our Ionic development environment.

Install Node.js

The first dependency we need to install is Node.js, which is a server-side JavaScript framework. We will be using Node.js for its node package manager (npm), which will allow us to install all the packages and tools we need for our projects. We will also use Node.js to run a development server service that will let us preview apps in the browser.

Ionic download page

Ionic recommends that, when installing Node.js, you should select the most recent Long Term Support (LTS) version. In my case, as you can see above, that's version 8.9.1 LTS. Ionic recommends using LTS versions as they are more stable.

So simply download the LTS version, go through the installer instructions, and once the installation is finished you'll be ready to continue with the next step.

Installing Cordova and Ionic

With Node.js installed, you're now ready to install Cordova and Ionic. Here is where things might get a little bit tricky for some, especially those that have never worked with the Command Line Interface (CLI) before. It might all look a bit daunting at first, and you might feel as if you are going to end up breaking something on your beloved computer! Well, you won't, so just relax and try to follow along.

On Mac and Linux, search for Terminal, which is the CLI we will be using to install Cordova and Ionic. On Windows, search for Command Prompt. This is the equivalent to Terminal on a Windows PC.

Installing on Mac and Linux

With Terminal opened on Mac or Linux, type the following command and run it by pressing Enter on your keyboard.

Thereafter, you might be prompted to enter a password, If so, enter the password you use to log in to your computer and press Enter again.

Installing Cordova and Ionic on Mac

Installing on Windows

From the Command Prompt on Windows, type the following command and run it by pressing Enter on your keyboard.

Installing Ionic and Cordova on Windows

As you might have noticed, we are using the Node Package Manager (npm) to install both Ionic and Cordova above, so it is of the utmost importance to install Node.js first! You might have also noticed that on Mac and Linux we are using sudo in front of our command. This is necessary to allow the installation of Ionic and Cordova globally on these systems.

The install process can take a few minutes, depending on your internet connection, but once it's done you should see something like this:

Successful install of Ionic and Cordova

Cool, so with Ionic and Cordova successfully installed, let's move on over to the next section and install additional software we'll need to successfully build our iOS and Android apps from our Ionic projects.

Platform-Specific Setup

You don't necessarily have to install these software tools right now; you can carry on building Ionic apps using web technologies we discussed earlier on. So feel free to skip this part if you are keen to just jump right in and create your first Ionic project. 

However, if you want to run your apps on a real mobile device like an Android phone or iPhone, you'll eventually have to install the platform-specific tools for those platforms. We'll look more closely at developing for Android and iOS devices in future tutorials.

Setup for Android Apps

If you want to be able to compile Android apps from your Ionic project, you'll need to first install the Java Development Kit (JDK) 8 or later. Go to the JDK website, accept the license agreement, and select the relevant download option based on your operating system. Then follow the install instructions.

Java Development Kit download options

After you've successfully installed the JDK, you need to also install Android Studio, the Android IDE (integrated development environment).

Android Studio download

With these two packages installed, you'll be able to compile and package an Android app from your Ionic project.

Setup for iOS Apps

Building iOS apps from your Ionic projects is only possible on a Mac OS computer, unfortunately, which means you will be unable to compile or build iOS apps from a computer running Windows or Linux. (Though you can code your app now on a Windows computer, and later build it for iOS from a Mac.)

In order to compile iOS apps on your Mac OS, you will need to install Xcode. Simply head over to the AppStore on your Mac and search for Xcode. This is a free download.

Xcode download page

After you have successfully installed Xcode, you will also need to install additional command line tools for Xcode. In order to do this, open Terminal and run the following command.

This will install additional tools Cordova will use to build your iOS projects.

Installing the Xcode command line tools

To be able to build your iOS projects from the command line, you will also need to run the following command.

Installing ios-deploy

With everything set up, you're ready to build iOS apps from your Ionic projects.

Creating Your First Ionic Project

Ionic uses the command line—and in particular the Ionic CLI, which was automatically installed during our setup process—to create, test and build your Ionic applications. So have the courage again to open up Terminal or Command Prompt (depending on your operating system). 

A quick word of advice before we continue: learn to embrace the Ionic CLI tool. It has now officially become your new friend, so learn to love it! 

The first thing we need to do is specify where we want to save our Ionic project. For the purpose of this exercise, we'll simply save it onto our desktop. So navigate to the desktop with the following command.

Navigate to the desktop

We have a few options for the type of Ionic application we'd like to create, and these are categorized as Ionic project templates. For the beginner, three types of templates exist: a Blank template, a Tabs template, and a SideMenu template. We will be using the tabs template in this example, so let's go ahead and create our project.

We are going to be calling our Ionic project DemoApp. So to create our DemoApp project using the tabs template and save it onto our desktop, we need to run the following command in our CLI.

Ready to run ionic start

This command will take a little while to run as it downloads all your project template packages and application dependencies. During the install you might be asked if you would like to install the free Ionic Pro SDK and connect your app. Answer No and press Enter again to continue with the install. Once installation is complete, you should see something like this:

A successfully created Ionic project

Congratulations! You've successfully created your first Ionic project.

Run Your Ionic App

With the project setup complete, we are now ready to view our Ionic application. To do so, navigate to your newly created project folder via the CLI by running cd ./DemoApp and once inside this folder run either ionic serve or ionic lab.

Ready to run ionic serve

ionic serve and ionic lab are Ionic CLI commands that will compile your application and start up a local dev server, allowing you to view your Ionic application inside a web browser on your computer.

The app in action

In the image above, I've run the ionic lab command, and as you can see, I'm able to view my Ionic project compiled as a web app. We still haven't managed to compile it as a native application as yet, but we will do so in later tutorials.

Conclusion

I remember that when I started developing Ionic apps, it was very confusing at first, especially having to do a lot of the initial work via the CLI. As someone that was not accustomed to working with the CLI at all, this was a scary journey for me—so I can imagine how some of you might be feeling out there. My advice to you is embrace it—you'll get more comfortable and used to it as you go along, and don't worry, you won't break anything on your beloved computer!

We've covered a lot of ground in this post, but with this knowledge you're over one of the biggest hurdles to coding Ionic apps. Stay tuned for the next post in this series!

Until then, check out some of our other great posts about coding Ionic apps, or try one of our comprehensive video courses on Ionic app development!

2017-11-20T21:06:43.218Z2017-11-20T21:06:43.218ZTinashe Munyaka

Ionic From Scratch: Getting Started With Ionic

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

So you've heard about Ionic and you're wondering how to get started? In this tutorial you will learn how to set up an Ionic development environment on your computer, as well as how to create an Ionic project. 

Requirements for Coding an Ionic App

Well, congratulations, if you are viewing this article via a computer you have one of the most important prerequisites for developing Ionic apps: you will require a physical personal computer (PC) to do so. This can be a computer running Windows, Mac, or Linux.

Since we build Ionic apps using web technologies, you will also need web development tools installed. This includes a web browser (preferably Google Chrome) to run and debug our apps, and a text editor (such as Sublime, Atom, or Visual Studio Code) to write and edit our code. If you are new to development, I would recommend Visual Studio Code as it is commonly used and free.

With these basic requirements installed on your computer, let's go ahead and install the dependencies we need to build Ionic apps.

Setting Up Dependencies and Installing Ionic

Unfortunately, there is no single installer package that automatically installs an Ionic development environment on your computer. Regardless of your operating system, you have to install each of the required dependencies manually. So let's go ahead and get started setting up our Ionic development environment.

Install Node.js

The first dependency we need to install is Node.js, which is a server-side JavaScript framework. We will be using Node.js for its node package manager (npm), which will allow us to install all the packages and tools we need for our projects. We will also use Node.js to run a development server service that will let us preview apps in the browser.

Ionic download page

Ionic recommends that, when installing Node.js, you should select the most recent Long Term Support (LTS) version. In my case, as you can see above, that's version 8.9.1 LTS. Ionic recommends using LTS versions as they are more stable.

So simply download the LTS version, go through the installer instructions, and once the installation is finished you'll be ready to continue with the next step.

Installing Cordova and Ionic

With Node.js installed, you're now ready to install Cordova and Ionic. Here is where things might get a little bit tricky for some, especially those that have never worked with the Command Line Interface (CLI) before. It might all look a bit daunting at first, and you might feel as if you are going to end up breaking something on your beloved computer! Well, you won't, so just relax and try to follow along.

On Mac and Linux, search for Terminal, which is the CLI we will be using to install Cordova and Ionic. On Windows, search for Command Prompt. This is the equivalent to Terminal on a Windows PC.

Installing on Mac and Linux

With Terminal opened on Mac or Linux, type the following command and run it by pressing Enter on your keyboard.

Thereafter, you might be prompted to enter a password, If so, enter the password you use to log in to your computer and press Enter again.

Installing Cordova and Ionic on Mac

Installing on Windows

From the Command Prompt on Windows, type the following command and run it by pressing Enter on your keyboard.

Installing Ionic and Cordova on Windows

As you might have noticed, we are using the Node Package Manager (npm) to install both Ionic and Cordova above, so it is of the utmost importance to install Node.js first! You might have also noticed that on Mac and Linux we are using sudo in front of our command. This is necessary to allow the installation of Ionic and Cordova globally on these systems.

The install process can take a few minutes, depending on your internet connection, but once it's done you should see something like this:

Successful install of Ionic and Cordova

Cool, so with Ionic and Cordova successfully installed, let's move on over to the next section and install additional software we'll need to successfully build our iOS and Android apps from our Ionic projects.

Platform-Specific Setup

You don't necessarily have to install these software tools right now; you can carry on building Ionic apps using web technologies we discussed earlier on. So feel free to skip this part if you are keen to just jump right in and create your first Ionic project. 

However, if you want to run your apps on a real mobile device like an Android phone or iPhone, you'll eventually have to install the platform-specific tools for those platforms. We'll look more closely at developing for Android and iOS devices in future tutorials.

Setup for Android Apps

If you want to be able to compile Android apps from your Ionic project, you'll need to first install the Java Development Kit (JDK) 8 or later. Go to the JDK website, accept the license agreement, and select the relevant download option based on your operating system. Then follow the install instructions.

Java Development Kit download options

After you've successfully installed the JDK, you need to also install Android Studio, the Android IDE (integrated development environment).

Android Studio download

With these two packages installed, you'll be able to compile and package an Android app from your Ionic project.

Setup for iOS Apps

Building iOS apps from your Ionic projects is only possible on a Mac OS computer, unfortunately, which means you will be unable to compile or build iOS apps from a computer running Windows or Linux. (Though you can code your app now on a Windows computer, and later build it for iOS from a Mac.)

In order to compile iOS apps on your Mac OS, you will need to install Xcode. Simply head over to the AppStore on your Mac and search for Xcode. This is a free download.

Xcode download page

After you have successfully installed Xcode, you will also need to install additional command line tools for Xcode. In order to do this, open Terminal and run the following command.

This will install additional tools Cordova will use to build your iOS projects.

Installing the Xcode command line tools

To be able to build your iOS projects from the command line, you will also need to run the following command.

Installing ios-deploy

With everything set up, you're ready to build iOS apps from your Ionic projects.

Creating Your First Ionic Project

Ionic uses the command line—and in particular the Ionic CLI, which was automatically installed during our setup process—to create, test and build your Ionic applications. So have the courage again to open up Terminal or Command Prompt (depending on your operating system). 

A quick word of advice before we continue: learn to embrace the Ionic CLI tool. It has now officially become your new friend, so learn to love it! 

The first thing we need to do is specify where we want to save our Ionic project. For the purpose of this exercise, we'll simply save it onto our desktop. So navigate to the desktop with the following command.

Navigate to the desktop

We have a few options for the type of Ionic application we'd like to create, and these are categorized as Ionic project templates. For the beginner, three types of templates exist: a Blank template, a Tabs template, and a SideMenu template. We will be using the tabs template in this example, so let's go ahead and create our project.

We are going to be calling our Ionic project DemoApp. So to create our DemoApp project using the tabs template and save it onto our desktop, we need to run the following command in our CLI.

Ready to run ionic start

This command will take a little while to run as it downloads all your project template packages and application dependencies. During the install you might be asked if you would like to install the free Ionic Pro SDK and connect your app. Answer No and press Enter again to continue with the install. Once installation is complete, you should see something like this:

A successfully created Ionic project

Congratulations! You've successfully created your first Ionic project.

Run Your Ionic App

With the project setup complete, we are now ready to view our Ionic application. To do so, navigate to your newly created project folder via the CLI by running cd ./DemoApp and once inside this folder run either ionic serve or ionic lab.

Ready to run ionic serve

ionic serve and ionic lab are Ionic CLI commands that will compile your application and start up a local dev server, allowing you to view your Ionic application inside a web browser on your computer.

The app in action

In the image above, I've run the ionic lab command, and as you can see, I'm able to view my Ionic project compiled as a web app. We still haven't managed to compile it as a native application as yet, but we will do so in later tutorials.

Conclusion

I remember that when I started developing Ionic apps, it was very confusing at first, especially having to do a lot of the initial work via the CLI. As someone that was not accustomed to working with the CLI at all, this was a scary journey for me—so I can imagine how some of you might be feeling out there. My advice to you is embrace it—you'll get more comfortable and used to it as you go along, and don't worry, you won't break anything on your beloved computer!

We've covered a lot of ground in this post, but with this knowledge you're over one of the biggest hurdles to coding Ionic apps. Stay tuned for the next post in this series!

Until then, check out some of our other great posts about coding Ionic apps, or try one of our comprehensive video courses on Ionic app development!

2017-11-20T21:06:43.218Z2017-11-20T21:06:43.218ZTinashe Munyaka

10 Best iOS Photo App Templates

$
0
0

Photo apps are among the most popular of iOS apps to be found in the App Store today. If you’re not an experienced developer but have long fantasised about building a photo app yourself, I’m here to make your dream a reality with this list of the ten best iOS photo app templates available at CodeCanyon.

App templates are ideal for novice coders because they already have core functions implemented for you so that you can customise the app easily and add the elements you most prefer to the app's code to create the product you want.  

So whether you’re interested in building an app for photo editing, adding text to photos, or creating your own social media photo app, there’s a photo app template here for you.

1. PIXL

First up is PIXL, a handy photo editor app template with a customisable camera built-in. This means that users can take photos with the camera and start editing them right away or edit photos already in their photo library.

PIXL

Some of the app’s best features are its filters, its brightness, saturation, contrast, and tonal adjustments, resizing and cropping controls, as well as the ability to add stickers, frames, and text.

When users have completed their edits, they can share their images directly from the app on Facebook, Instagram, Twitter, etc. The app supports both iAd and AdMob and was created with Objective-C.

2. Photo/Video Social App

If you’d love to create your own Instagram-like app, check out the Photo/Video Social App template. This template allows developers to create a photo and video sharing app in the vein of Instagram where users can follow, like, comment, and share photos. 

PhotoVideo Social App

Users can log in with their email, Google, or Facebook accounts, and the app supports monetisation with AdMob. It also supports push notifications and comes with built-in Analytics to monitor performance.

The app template is written with Swift 4 and uses the latest version of Firebase.

User Bornagainfatkid says of the template:

“This is an awesome template, the documentation is very well written with video support. I was able to get this running in Xcode with minimal effort and posting to Firebase needed under an hour of just going over the documents. It does exactly what is listed in the description.”

3. iOS Image Editor

The beauty of the iOS Image Editor app template is that it gives developers two powerful photo editing templates for one, with both PhotoGram and PicStick templates in one bundle.

iOS Image Editor

Both apps feature tools like exposure, saturation, contrast, brightness and sharpness adjustment, filters, frames, stickers, focus and blur, image rotation, crop and resize, blemish removal, text and drawing features and more.

These Objective-C templates have AdMob and iAd implemented for easy monetisation, but if you don’t want to use ads, they can be disabled with one click.

4. Photo Collage Maker

Photo collages have become very popular over the past few years, so it’s no surprise that the Photo Collage Maker app template has made it onto our top ten list.

Photo Collage Maker

Written in Objective-C, this template will help you create a fabulous photo collage app easily and quickly that will allow users to drag and drop photos from their photo library, edit them, and then arrange them in one of a wide selection of collage styles. Users can also select their frame style, size, and colour, as well as adding stickers and text to their creation.

The template supports monetisation with AdMob.

5. Polaroyd

If you love the vintage look of Polaroid and want to create an app that allows users to replicate this effect in their photos, the Polaroyd app template may be just the thing for you.

Polaroyd

Created with Swift, this template allows the app's users to take photos with the built-in camera or upload them from their photo library and edit them with a range of adjustments and filters to create the Polaroid look.

Users can also add different Polaroid frames and captions to their images and share them on Facebook and Twitter, email or messenger. 

6. Photo Stickers App

The Photo Stickers App is a template written in Objective-C and is ideal for developers who want to create an app for adding stickers to photos.

Photo Stickers App

Developers can create a range of stickers for use in their app, and users of their app can drag and drop these stickers on photos they’ve either taken with the app’s built-in camera or selected from their photo library. Users can move, scale, or rotate their stickers.

Once the user has created their composition, they can share it on Facebook, Twitter, Instagram, WhatsApp, etc. The app supports AdMob and iAD for easy monetisation.

7. Photo Trivia Quiz

Developing your own photo quiz app has never been easier. With the Photo Trivia Quiz app template, you can create a wide range of photo-driven quizzes by creating your own categories, uploading your own photos, and creating questions for users to answer. 

Photo Trivia Quiz

You can also customise the parameters of the quiz. For example, users might need to fight against the clock so that the faster they answer questions, the more points they get. Or they might need to collect a set amount of points to unlock a new level of the quiz.

The template provides two versions—one for iPhones and the other for iPads—and supports a variety of ad providers like AdMob and Chartboost.

8. Gif Factory App

If you want to create an app that allows users to turn their photos or videos into a GIF sequence, then the Gif Factory App template is perfect for you. The app is designed to enable users to use photo sequences or video clips and turn them into animated GIFs quickly and easily.

Gif Factory App

Even if users aren’t interested in creating their own GIFs from scratch, they can use the app to play GIFs stored in their photo library and edit them as they wish. All GIFs can be shared via email, messaging, and social media.

The template, which is written in Swift, is fully AdMob integrated.

9. QuickTxt

The power of the QuickTxt app template is its simplicity and ease of use. The app template, which is written in Swift, targets developers who want to create a straightforward text app that allows users to add text to their images and share them quickly via Email, Facebook, Twitter, Instagram, WhatsApp, etc.

QuickTxt

Users can select their fonts, adjust text size and colour, move and scale photos, and apply a coloured background to their images.

10. Funny Face Maker

To round off our list, check out the Funny Face Maker app template. This app template helps developers create one of those incredibly silly apps that few of us can resist, maybe because they bring a bit of comic relief to our day by allowing us to make funny photos of ourselves that will keep family and friends endlessly amused.

Funny Face Maker

The template provides a huge selection of fun objects and effects for developers to select for inclusion in their app.

For the end user, the app is very easy to use. They just need to take a photo with their camera or select the photo they want to manipulate from their photo library, and then select the fun object or objects they want to use. Users can resize and move the object(s) as needed, and save the image. Finally, they can share on social media, by email or messenger.

Conclusion

These top 10 iOS photo app templates are just a small selection of the iOS photo app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

If you want to explore more iOS apps and templates, then check out some of our other posts on CodeCanyon app templates!

2017-11-24T12:18:59.000Z2017-11-24T12:18:59.000ZNona Blackman

10 Best iOS Photo App Templates

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

Photo apps are among the most popular of iOS apps to be found in the App Store today. If you’re not an experienced developer but have long fantasised about building a photo app yourself, I’m here to make your dream a reality with this list of the ten best iOS photo app templates available at CodeCanyon.

App templates are ideal for novice coders because they already have core functions implemented for you so that you can customise the app easily and add the elements you most prefer to the app's code to create the product you want.  

So whether you’re interested in building an app for photo editing, adding text to photos, or creating your own social media photo app, there’s a photo app template here for you.

1. PIXL

First up is PIXL, a handy photo editor app template with a customisable camera built-in. This means that users can take photos with the camera and start editing them right away or edit photos already in their photo library.

PIXL

Some of the app’s best features are its filters, its brightness, saturation, contrast, and tonal adjustments, resizing and cropping controls, as well as the ability to add stickers, frames, and text.

When users have completed their edits, they can share their images directly from the app on Facebook, Instagram, Twitter, etc. The app supports both iAd and AdMob and was created with Objective-C.

2. Photo/Video Social App

If you’d love to create your own Instagram-like app, check out the Photo/Video Social App template. This template allows developers to create a photo and video sharing app in the vein of Instagram where users can follow, like, comment, and share photos. 

PhotoVideo Social App

Users can log in with their email, Google, or Facebook accounts, and the app supports monetisation with AdMob. It also supports push notifications and comes with built-in Analytics to monitor performance.

The app template is written with Swift 4 and uses the latest version of Firebase.

User Bornagainfatkid says of the template:

“This is an awesome template, the documentation is very well written with video support. I was able to get this running in Xcode with minimal effort and posting to Firebase needed under an hour of just going over the documents. It does exactly what is listed in the description.”

3. iOS Image Editor

The beauty of the iOS Image Editor app template is that it gives developers two powerful photo editing templates for one, with both PhotoGram and PicStick templates in one bundle.

iOS Image Editor

Both apps feature tools like exposure, saturation, contrast, brightness and sharpness adjustment, filters, frames, stickers, focus and blur, image rotation, crop and resize, blemish removal, text and drawing features and more.

These Objective-C templates have AdMob and iAd implemented for easy monetisation, but if you don’t want to use ads, they can be disabled with one click.

4. Photo Collage Maker

Photo collages have become very popular over the past few years, so it’s no surprise that the Photo Collage Maker app template has made it onto our top ten list.

Photo Collage Maker

Written in Objective-C, this template will help you create a fabulous photo collage app easily and quickly that will allow users to drag and drop photos from their photo library, edit them, and then arrange them in one of a wide selection of collage styles. Users can also select their frame style, size, and colour, as well as adding stickers and text to their creation.

The template supports monetisation with AdMob.

5. Polaroyd

If you love the vintage look of Polaroid and want to create an app that allows users to replicate this effect in their photos, the Polaroyd app template may be just the thing for you.

Polaroyd

Created with Swift, this template allows the app's users to take photos with the built-in camera or upload them from their photo library and edit them with a range of adjustments and filters to create the Polaroid look.

Users can also add different Polaroid frames and captions to their images and share them on Facebook and Twitter, email or messenger. 

6. Photo Stickers App

The Photo Stickers App is a template written in Objective-C and is ideal for developers who want to create an app for adding stickers to photos.

Photo Stickers App

Developers can create a range of stickers for use in their app, and users of their app can drag and drop these stickers on photos they’ve either taken with the app’s built-in camera or selected from their photo library. Users can move, scale, or rotate their stickers.

Once the user has created their composition, they can share it on Facebook, Twitter, Instagram, WhatsApp, etc. The app supports AdMob and iAD for easy monetisation.

7. Photo Trivia Quiz

Developing your own photo quiz app has never been easier. With the Photo Trivia Quiz app template, you can create a wide range of photo-driven quizzes by creating your own categories, uploading your own photos, and creating questions for users to answer. 

Photo Trivia Quiz

You can also customise the parameters of the quiz. For example, users might need to fight against the clock so that the faster they answer questions, the more points they get. Or they might need to collect a set amount of points to unlock a new level of the quiz.

The template provides two versions—one for iPhones and the other for iPads—and supports a variety of ad providers like AdMob and Chartboost.

8. Gif Factory App

If you want to create an app that allows users to turn their photos or videos into a GIF sequence, then the Gif Factory App template is perfect for you. The app is designed to enable users to use photo sequences or video clips and turn them into animated GIFs quickly and easily.

Gif Factory App

Even if users aren’t interested in creating their own GIFs from scratch, they can use the app to play GIFs stored in their photo library and edit them as they wish. All GIFs can be shared via email, messaging, and social media.

The template, which is written in Swift, is fully AdMob integrated.

9. QuickTxt

The power of the QuickTxt app template is its simplicity and ease of use. The app template, which is written in Swift, targets developers who want to create a straightforward text app that allows users to add text to their images and share them quickly via Email, Facebook, Twitter, Instagram, WhatsApp, etc.

QuickTxt

Users can select their fonts, adjust text size and colour, move and scale photos, and apply a coloured background to their images.

10. Funny Face Maker

To round off our list, check out the Funny Face Maker app template. This app template helps developers create one of those incredibly silly apps that few of us can resist, maybe because they bring a bit of comic relief to our day by allowing us to make funny photos of ourselves that will keep family and friends endlessly amused.

Funny Face Maker

The template provides a huge selection of fun objects and effects for developers to select for inclusion in their app.

For the end user, the app is very easy to use. They just need to take a photo with their camera or select the photo they want to manipulate from their photo library, and then select the fun object or objects they want to use. Users can resize and move the object(s) as needed, and save the image. Finally, they can share on social media, by email or messenger.

Conclusion

These top 10 iOS photo app templates are just a small selection of the iOS photo app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

If you want to explore more iOS apps and templates, then check out some of our other posts on CodeCanyon app templates!

2017-11-24T12:18:59.000Z2017-11-24T12:18:59.000ZNona Blackman
Viewing all 1836 articles
Browse latest View live