SAP Technology News

iOS App Development: Auto Layout in iOS

Introduction to Auto Layout
Auto Layout in iOS is a system that enables you to define your app’s interface by creating a mathematical description of the relationships between the elements. You can define these relationships with respect to constraints either on individual elements or between sets of elements. You can use Auto Layout to create a dynamic and versatile interface that responds appropriately to variations in screen size, device orientation and localization.
Auto layout has become more and more important, particularly for more device screen sizes. Though Auto Layout has been available for a few years now, it has become a necessity in the current scenario, particularly for iPhone 6 or 6 Plus. Though it appears to be bit daunting to use this feature, Xcode has seen steady improvements in interface builder to enable integrating Auto Layout simpler. Starting from Xcode 6, you should learn how to use Auto Layout, wherein without using Auto Layout, it would be quite challenging to build an app that supports all screen sizes. When you use Auto Layout, you can get a stupendous control over the layout with a wide range of customization and yields the perfect interface.
Auto Layout is built into Interface Builder in Xcode 5 and is made available with apps, targeted at either iOS or OSX. If you are creating a new project, Auto Layout is enabled by default. However, if your existing project doesn’t use Auto Layout, you can adopt an auto layout.
A typical button example
Let’s assume you have a story board, where you need to place a button in the center of the view. Just run the app on both iPhone Retina (3.5 inch) and iPhone Retina (4-inch) simulators. You will notice that the button isn’t centered when running on a 3.5 inch device. Can you guess what went wrong with this?
When you don’t use Auto Layout, the UI controls (here, the button) we layout in the storyboard is at a fixed position. This implies, we “hard-code” the frame origin of the control. For instance, let’s assume that the “Click Me” button frame origin is set to (100, 185). Hence, irrespective of the screen size (3.5 inch or 4 inch) of the device you are using, iOS will draw the label in the specified position. This functionality thus explains why the “Click Me” button wasn’t displayed properly on a 3.5-inch phone, for which the screen height is different.
Picture1
What you can do with Auto Layout?
Using Auto Layout in Xcode 5, you can:
  • Add constraints when you are ready
  • Quickly add constraints with control-drag or menu options
  • Update constraints and frames separately
  • Specify placeholder constraints for dynamic views
  • See, understand, and resolve issues with conflicting constraints or ambiguous views
Auto Layout Concepts
The basic building block in Auto Layout is the constraint. Constraints specify rules for the layout of elements in your interface. For instance, you can create a constraint that specifies an element’s width or its horizontal distance from another element. You can add and remove constraints, or change the properties of constraints to modify the layout of your interface.
When calculating the runtime positions of elements in a user interface, the Auto Layout system takes into account all constraints at a single instance, and sets positions in such a manner that best suits all of the constraints.
The typical workflow for creating user interfaces commences by using Interface Builder to create, reposition, resize and customize your views and controls. Once you are fine with the positions and settings, you can jump start to add Auto Layout constraints to enable your interface to reach to changes in orientation, size and localization.
Adding Constraints
When you drag out an element from the object library and drop it on the Interface Builder canvas, it starts out unconstrained to make it easy to prototype your interface by dragging the elements around. If you build and run without adding any constraints to an element, you will understand that the Interface Builder fixes the element’s width and height and pins its position relative to the top left corner of the superview. This implies that resizing the window doesn’t move or resize the elements. In order to ensure that your interface reacts properly to changes in size or orientation, you need to start adding constraints.
There are numerous ways to add constraints, based on the level of precision you want and the number of constraints you want to incorporate at a time.
How to Use Auto Layout in Interface Builder?
First let us understand what Interface Builder is all about and get to know how Auto Layout can be applied:
Before we show you how to fix the alignment issue in the example, let’s have a brief walkthrough of the Interface Builder and get to know how Auto Layout can be applied.
As a first step, setup a project based on the single view application iOS app template. In the project options, click iPhone for the device family, save the project and then open the storyboard. You will notice a menu at the bottom-right corner, wherein the buttons in the menu are related to Auto Layout. You can use these buttons for alignment, sizing, spacing and resolving constraint issue. The overview of these buttons are as follows:
  • Align – Create alignment constraints, such as aligning the left edges of two views.
  • Pin – Create spacing constraints, such as defining the width of a UI control.
  • Issues – Resolve layout issues.
  • Resizing – Specify how resizing affects constraints.
  • Xcode Auto Layout Menu in Interface Builder
Picture2
Working with Constraints
Apart from the Auto Layout menu, Apple has made it flexible for developer to setup Auto Layout by using Control + drag. You need to just control and drag from any view to another view to set constraints between each other. Once you release the mouse, it displays a list of possible constraints for you to select them.
After you setup a constraint in a view, the constraint line is displayed in either orange or blue. The orange constraint lines denotes that there are insufficient constraints, indicating that you need to fix it.
If the constraint line is displayed in blue, it indicates that your view layout is being set up correctly and there is no confusion.
Sometimes, after you create the constraint, the Interface Builder outline view displays a disclosure arrow. The red arrow indicates that there are conflicts or ambiguities and once you click that arrow, you can view the list of issues, which are displayed on a scene-by-scene basis. Some of the core issues include missing constraints, conflicting constraints and misplaced views.
Apart from the size inspector view, the constraints also appear in the Interface Builder Outline under the corresponding view.
Conclusion
After reading this blog, you might have got an overview of what Auto Layout feature is all about and how constraints in the Interface Builder play a major role in positioning the button in a layout. Though not exhaustive in nature, the aim of this blog is to just kindle the right interest to get started using the Auto Layout feature, though my intention is to come out with much more exhaustive literature on how to use this feature with a typical implementation example in near future.
Request a Demo
To learn more about Innovapptive’s portfolio of SAP Certified Mobile Solutions , please contact us by clicking on the link. Alternatively, if you would like to discuss with an Innovapptive solution expert, you can reach out to us by emailing us at sales@innovapptive.com or you can reach a sales representative at (713) 275-1804.


Part 2: How to setup Push Notifications in iOS

Introduction
In the first part of the blog series on push notifications, you have been provided an overview of what push notifications are all about, basic pre-requisites for implementing push notifications in iOS, key takeaways and some of challenges pertaining to push notifications. This blog is a continuation of the earlier blog which focusses on the configuration aspects of push notifications.
As outlined in the first part of this blog series, Apple introduced push notifications to let applications respond to events, even if the applications aren’t running in the forefront. Push notifications notify an application about vital events and to enable the engagement of the users.
Pre-requisites
Before we start configuring push notifications, let’s recall some of the basic pre-requisites, already covered in my earlier blog.
Put it in a simplest manner, you need two things to get started with the process of sending push notifications:
  1. Requirement of a physical device (since iOS simulator doesn’t support push notifications)
  2. Requirement of a paid iOS developer account; only paid accounts can provision applications to run on a physical device.
I. Project Setup
  1. Click Single View Application template to open Xcode to create a new project, based on the single view application template.
Picture - 1
2.  In the Choose options for your new project: screen:
  • Type push in the Product Name box.
  • Type a company identifier and class prefix in the respective boxes.
  • Click iPhone from the Devices box.
Picture - 2
II. Registration
  1. Open TSPAppDelegate.m and update the application:didFinishLaunchingWithOptions: as shown below.
Here, you are calling registerForRemoteNotificationTypes: on the application object, passing in the notification types you are                                  interested. This ensures that the operating system now knows that the application is configured to receive push notifications.
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
               // Register for Remote Notifications
               [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |                                          UIRemoteNotificationTypeSound)];
               return YES;
               }
The operating system contacts the Apple’s servers and gets a “device token” to uniquely identify the device from which the application is running. This device token is used by your server infrastructure to send push notifications. This is accomplished by sending the device token along with the actual push notification to Apple’s servers. Apple servers take the charge of distributing the push notifications to the appropriate devices.
Make a note that the device token differs for each application and it can even alter over time for the same application. Apple therefore recommends asking for a device token every time the application is launched and send the device token to your backend to ensure that the device token is up to date.
The following methods tells your application whether the registration for remote notifications is successful or not:
  •  application:didRegisterForRemoteNotificationsWithDeviceToken:
  • application:didFailToRegisterForRemoteNotificationsWithError
As of now, implement these methods as shown below.
(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@”Did Register for Remote Notifications with Device Token (%@)”, deviceToken);
}
(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@”Did Fail to Register for Remote Notifications”);
NSLog(@”%@, %@”, error, error.localizedDescription);
Both methods are declared by the UIApplicationDelegate protocol. This protocol also declares another method, application:didReceiveRemoteNotification:, which is invoked when the application receives a remote notification.
The application:didReceiveRemoteNotification: method delivers you the payload of the push notification as an NSDictionaryobject. Your application needs to decide how it should respond to the push notification.
If you run your application, then the application:didFailToRegisterForRemoteNotificationsWithError: method will be invoked.
III. Configure SSL Certificate creation
To complete the next step, you need to sign into your iOS developer account at Apple’s iOS Dev Center.
The following are the steps to accomplish this:
  1. In the Certificates, Identifiers and Profiles screen, click Identifiers under the iOS Apps section.
Picture - 3
2.  Click the + button on the top right corner and type an App ID description to help you identify the App ID later.
Picture - 4
3.  Click Explicit App ID, instead of Wildcard App ID from the App ID Suffix box.
4.  If you want the application to receive remote notifications, type com.tutsplus.push (instead of com.tutsplus) in the Bundle ID box.
Picture - 5
5.  Under App Services, click Push Notifications. Click Continue to submit the form and finally click Submit to create the App ID.
Picture - 6
Picture - 7

6.  From the list of App IDs, select the one you just created and click Edit.
7.  Scroll down until you see the section that covers push notifications, where you can view two buttons labeled Create Certificate as shown below:
Picture - 8 IV. Create an SSL certificate
  1. Select Keychain Access on your development machine.
  2. From the Keychain Access menu, click Certificate Assistant > Request a Certificate From a Certificate Authority. Double-check to ensure that no key is selected in Keychain Access, when you select this option.
  3. In the Certificate Assistant screen, type the email address and a common name to help you identify the certificate later and click Saved to disk.
  4.  Click Continue and save the certificate signing request to your hard drive. This way you’ve created a certificate signing request as well as public and private keys. You can view the keys in the Keychain Access (as shown in the screen shot below).

Picture - 9

Picture - 10

Picture - 11
5.  Revert to the iOS Dev Center and click Create Certificate.
6.  Next click Continue, click Choose File to upload the certificate signing request and click Generate to generate the SSL certificate.
Picture - 12
7.  Now download the certificate and double click on it to install it in Keychain Access.
8.  Double-check that the certificate is added to Keychain Access and linked to the appropriate private key.
Picture - 13
V. Create a provisioning profile
Before you proceed to test your push notifications setup, you need to create a provisioning profile for your application.
  1. From the iOS Dev center, click Development in the Provisioning Profiles section.
  2. Click the + button on the top right corner and click iOS App Development under the Development section.
Picture - 14
3.  Click Continue and select your App ID from the list
4.  Select the certificates you want to include in the provisioning profile and click Continue.     
              Note: Make sure your test device is also included.
5.  Type an appropriate name for your provisioning profile and then click Generate.
Picture - 15
6.  Download the provisioning profile and drag it in Xcode to add it.
7.   Update your target’s building settings in Xcode to use the new provisioning profile.
8.   Build and run your application to ensure that everything is proper and works accordingly, as desired.
If you encounter any issues while running your application, double-check to ensure that the bundle identifier of your application                   matches with the App ID (bundle identifier is case sensitive).
If you have followed all the steps as outlined above, your application should generate a prompt message as follows:
Picture - 16
9.  If you tap OK, your application will ask the operating system for a device token. In case if it is successful, the application:
didRegisterForRemoteNotificationsWithDeviceToken: method of the UIApplicationDelegate protocol is invoked, handing you the device token. Since we have already included a log statement to this method, the device token should also be logged to the console in Xcode.
Push[2182:60b] Did Register for Remote Notifications with Device Token ()
}
VI. Ensure proper backend is in place
Now that you have successfully accomplished all the above steps, the final step is to make sure that you have a backend in place to ensure that your application can send the device token to it. This is required to test whether your push notifications you had send have successfully arrived or not. That backend can then connect with Apple’s servers to send push notifications. This is the simplest part of the configuration, especially when you are using a service like Parse or Urban Airship.
Conclusion
I hope this blog has provided you an overview of the configuration setup for successfully sending push notifications from your device. This configuration setup is not at all difficult as some developers perceive, though there are certain challenges involved in understanding the concepts of keys and properly generating the certificates.
Request a Demo
If you would like to request a demo of Innovapptive’s Native, HTML5 or Hybrid apps, please click on the link. Alternatively, if you would like to discuss with an Innovapptive solution expert, you can reach out to us by emailing us at sales@innovapptive.com or you can reach a sales representative at (713) 275-1804.


Part 1: Getting started with Push Notifications in iOS

Getting started with Push Notifications in iOS
This is the first part of the three part blog series of push notifications functionality in Apple devices that helps you in getting started with push notifications in iOS including the concepts of push notifications, its functionality,  its key takeaways and limitations. The second part of the blog series focuses on configuration aspects of push notifications, while the last part of the series talks about configuration aspects of push chat.
Introduction
Push notifications enables your application to notify a user of new messages or events, even when the user is not actively using your application. On Android devices, when a device receives a push notification, your application’s icon along with a message shows up in the status bus. A push notification is a short message that consists of the device token, a payload and a few other bits and bytes.
Thus push notification technology is quite common for smart phone users, though there might be certain variations from application to application or from one phone model to another one.
Why do you need push notifications?
In iOS, apps have limited functionality to process everything in the background. Apps are only allowed to perform a limited set of activities to ensure that the battery life is conserved. However, in certain instances, when something intruiging happens and  you wish to let the user know about this, even if they are currently using your app, then how will you go about it?
To take care of such instances, Apple provided a solution, wherein instead of your app continuously checking for events or doing background processing, you can write a server-side component to do this instead.
This implies that when an interesting event occurs, the server-side component can send a push notification, which can do three things:
  • Display a short text message
  • Play a short sound
  • Set a number in a badge on the app’s icon
This blog lets you understand how to make a simple app that uses Apple push notification service (APNS). The first step to accomplish this is to configure your app to receive push notifications and test message.
How push notifications work? (A brief overview)
Getting push notifications to work on your app is a bit tedious and a challenging process, though you may ultimately relish and enjoy your fruits of labour.
It consists of a series of stages, which is outlined in the following figure:
Blog picture.png

  1. The app enables push notifications, wherein the user has to confirm whether he intends to receive these notifications or not.
  2. Upon confirmation, the app receives a “device token”. You can assume this device token as the address that push notifications will be sent to.
  3. The app sends the device token to your server.
  4. If an interesting event occurs in your app, the server sends a push notification to the APNS.
  5. APNS sends the push notification to the user’s device.

Once the user’s device receives the push notification, it displays an alert, plays a sound and/or updates the app’s icon. The user has the flexibility to launch the app from the alert itself; the app has the information of the push notification and can handle it as it sees appropriately. Now a question might arise in your mind? Do we still need push notifications in the age of local notifications and multitasking?
Local notifications have certain limitations, wherein they are solely meant to scheduling timed events and unlimited background processing in only available to apps that process VOIP, navigation and background audio. However, if you still want to notify the users about external events, while the app is closed, you still require push notifications.
Pre-requisites for configuring push notifications:
 To configure push notifications on your app, you need to ensure the following requirements:
  • An iPhone or an iPad: You need to test push notifications on your device, as they do not work in the simulator.
  • An iOS Developer Program membership: You have to make a new App ID and provisioning profile for each app that uses push and at the same time, make an SSL certificate for the server. You can accomplish this at the iOS provisioning portal.
  • A server that is connected to the internet: Since push notifications are always sent by a server, you need to have a server that is connected to the internet. For development, purpose, use your Mac as the server and for production use, you need virtual private server (VPS) like Linode.
How does a push notification look like?
Payload, which is part of a push notification is the most important aspect that we would be interested, as it consists of the actual data you will be sending across.
Your server should provide this payload as a JSON dictionary. The payload for a simple push message will be displayed like this:
{
               “aps”:
               {
                               “alert”: “Hello, world!”,
                               “sound”: “default”
               }
}
There are myriad ways to configure the JSON payload like you can change the sound that is played, provide a localized text and you can even insert your own fields. Push notifications are intended to be small with payload size not exceeding 256 bytes.
Some key limitations
  • Push notifications are not reliable:
There also seems to be a possibility that push notifications might not be actually delivered, even if the APNS server accepts them. You cannot track the status of the push notification, once you have sent it to APNS. The delivery time may also vary – from seconds to even up to half an hour.
There might be some other instances like the user’s iPhone may not be able to receive push notifications all the time. They could be on a WIFI network that does not allow connections to be made to APNS, since the required ports may be blocked or the phone could be switched off. APNS attempts to deliver the last notification it received for that device when it reverts online, but it will only try for a limited period. Once it times out, the push notification will be lost forever!
  • They can be an expensive proposition:
Incorporating push functionality to your app is fairly easy and inexpensive if you own the data; however, if you a lot of users or data you need to poll, it may become a costly proposition.
  • Requirement of a certificate for APNS
In order to enable push notifications in your app, it needs to be signed with a provisioning profile that is configured for push.  Apart from that, your server needs to sign its communications to APNS with an SSL certificate.
The second part of this blog series outlines the functionality and procedures for configuring the push notifications on your iPhone or an  iPad.
Request a Demo
If you would like to request a demo of Innovapptive’s Native, HTML5 or Hybrid apps, please click on the link. Alternatively, if you would like to discuss with an Innovapptive solution expert, you can reach out to us by emailing us at sales@innovapptive.com or you can reach a sales representative at (713) 275-1804.


 
Return to top of pageCopyright ©SAP Mobility 2019 | Template design by Privacy Policy|Disclaimer*All trademarks and copyrights remain the property of their respective owners.