UMANG SOFTWARE TECHNOLOGIES

Posts tagged ‘iOS tutorials’

Creating your first iOS App

We are going to create a basic iOS 7 application which will give us the basics that every iOS developer needs to know.

In our app the first page will have 2 buttons “ Fire” and “Water”. On click of “fire” button it will take us to another page that will contain a button “Fire Message” that will give us an alert message on click of that button. Coming back to our home page, if we click on “Water” button it will take us to another page that contains a text field, button and an image displayed. When the user enters his/her name in the text filed and clicks on the “Water message” button, an alert message will be displayed which will contain his/her name in the alert.

Let’s get started!

iOSApp_1

We need to first create a new project. Click on the Xcode icon.The welcome window will appear, Click “Create a new Xcode project” (or choose File > New > Project).

 

Once we create a project, Xcode opens a new window and displays a dialog in which you can choose a template.

Xcode includes several built-in app templates that you can use to develop common styles of iOS apps, such as games, apps with tab-based navigation, and table-view-based apps. Most of these templates have pre – configured interface and source code files for you to start working with.

  1. In the iOS section at the left of the dialog, select Application.
  2. In the main area of the dialog, click Single View Application and then click Next.

iOSApp_2

In the dialog that appears next, name your app and choose additional options for your project and click Next.

Let’s take a look at the various options.

  • Product Name: The product name will be the name of your application.
  • Organization Name: The organization name can be your own name or the name of your company. Xcode uses the organization name for various purposes, such as adding a copyright notice to each source file.
  • Company Identifier: The company identifier is a unique string, which Xcode uses (together with the product name) to create the application’s bundle identifier. Apple recommends adopting the reverse-domain naming convention in an attempt to make this unique. Note that the domain that you use has no tie to the DNS system or Internet domain names.
  • Bundle Identifier: Even though you cannot specify the bundle identifier when creating a new Xcode project, you can change it once you’ve created your project. By default, the bundle identifier is the combination of the company identifier and the product name. Keep in mind that spaces in the product name are replaced with dashes in the bundle identifier, because the bundle identifier mustn’t contain white space.
  • Class Prefix: When creating custom classes in your project, it’s important that the class names don’t collide with existing class names. By specifying a class prefix, Xcode will prefix new classes with this custom class prefix to make sure that naming collisions are averted. A common approach is to use your initials or a combination that refers to your company or organization.
  • Devices: In the current version of Xcode (5.1 at the time of writing), the devices drop down menu contains three options, iPad, iPhone, and Universal. This configuration option tells Xcode which devices your project targets. By selecting the last option, Universal, your project targets both the iPad and iPhone device family. The iPod Touch is a member of the iPhone device family as you might have guessed.

iOSApp_3

In the next step, Xcode asks where you want to save your new project. You may have noticed the little checkbox at the bottom of the window labeled Create a git repository on My Mac. The gray text below the checkbox reads Xcode will place your project under version control. Choose a location for your project and click Create.

Xcode opens your new project in a window (called the workspace window), which should look similar to this:

iOSApp_4

Exploring Xcode’s User Interface

Toolbar
The toolbar at the top contains the buttons and menus that you’ll find yourself using frequently.

iOSApp_5

It displays information about your project’s state. Example, it will tell you when a build is successful or not.

The two segmented controls on the right of the toolbar can be used to customize Xcode’s user interface. Fiddle around with the various controls to find out how each of them changes Xcode’s user interface.

Navigator
The main purpose of the left sidebar is for navigation and it’s often referred to as Xcode’s navigator.

iOSApp_6

The navigator has different tabs with the Project Navigator which is at the far left. The selection in the left sidebar determines what is shown in Xcode’s main view, the workspace of the project.

Main View or Workspace
The main view or workspace is the area where you’ll spend most of your time. It’s Xcode’s workhorse and displays whatever is selected in the navigator.

Inspector
While the the left sidebar controls what’s being displayed in Xcode’s main view, the contents of the right sidebar reflects what’s being displayed or selected in the main view.

The right sidebar, also known as the inspector, adapts itself to whatever the user selects in the main view.

Enough of theory, let’s get started!

Open the Project Navigator and select the file named Main.storyboard. A file with a .storyboard extension is a user interface file. In this file, we create the user interface of the application.

The storyboard contains one item, a view controller with the white view.

The lower half of the right sidebar contains a section with four tabs. The third tab is represented by an image of a three dimensional box. This box is how objects are commonly displayed in Xcode.

Click on the tab with the box icon and scroll through the list that appears. The list is referred to as the Object Library and contains various user interface elements, such as buttons, sliders, and switches.

 

Let’s add a buttons to our scene

  1. In the Object library, find the Button object.
  2. Drag a Button object from the list to your scene.

Let’s add 2 buttons in our scene.

 iOSApp_7

We can now double click on the button and rename it to “Fire” or in our Object inspector we can change the text value and do the same for the other button and name it was “Water”.

We now drag a “ View Controller” from the object library and place it in our storyboard. On Click of the “Fire” button we want to move to another page. So let’s connect the button to the new view controller added which is known as a segue. Segues that manages the transition between view controllers. To create a segue from the button to the next page that we want to display, we have to press the “Ctrl” and mouse click on the page(View controller).

iOSApp_8

When you mouse click, you will get a small pop-up menu shows up of the various segues that you can create. Let’s select the Push Segue which provides transition from one viewController to another.

iOSApp_9

Similarly, we add another view controller in our storyboard and create segue for to it and select Push segue as done previously.

Now, let’s go ahead and embed a navigation controller to our storyboard so that the user can move forward and backward in our app. To do this, you need to first select the root view controller( i.e the first page the user sees when app is viewed).

iOSApp_10

Then we go to Editor-> Embed In-> Navigation Controller.

iOSApp_11

Below is the screenshot of the navigation controller that was added.iOSApp_12

We will now create a new file so that we can add the code for the “Fire View controller”. Right click on your project and select New File.

iOSApp_13

A dialog will appear, in the iOS section at the left of the dialog, select Cocoa Touch. In the main area of the dialog, click Objective –C class and then click Next.

iOSApp_14

We then give a class name and subclass as “UIViewController”. If Checkbox “Also create XIB file” is checked then uncheck it and click on Next.

iOSApp_15

It will then ask where to save the new files created and then we click on Create. We can then see the two files that are created that is .h and .m files. Here we will be writing our code for the “Fire view Controller” logic that we will be using. iOSApp_16Below is a screenshot of the two files that we had just created.

Now, we need to connect our UI to our controller. In order to do that, we go to the storyboard and select the Fire View controller. Go to the right panel and select the 3rd icon. It will have a custom class property-> Class. Here we enter the name of the class we just created for “fire”. Many developers do forget to do this step which is the most important.

iOSApp_17

We will now create IBAction, so that when the user clicks on the “Fire message” button he gets an alert message.

Select the “Fire View Controller” from the storyboard and click on the bow like icon on the right top.iOSApp_18

On doing this you will get a view of the storyboard and the implementation file viewed together as shown in the snapshot given below. We need to create an IBAction for our “Fire message” button so that when the user clicks the button he gets an alert message. We first select the “Fire message” button and then press the Ctrl and drag your mouse to the implementation file at the interface section and left-click.

iOSApp_19

When you left click on the mouse, a small popup will appear, where you will need to specify the details of the button action that we are creating. The “Connection” parameter has to be “Action”, then we can give a name for the action say “clickedFireMessage” and the Event as “Touch Up Inside” and click on connect. We have now created an event action prototype.iOSApp_20

 

We’ve added an action to the view controller, but the action doesn’t do much. What we have done is declare an action.

What we need to do is implement the action and we do that in the view controller’s implementation file. That’s right. The file with the .m extension is the implementation file.

Did you expect it to be empty? Xcode has given us some boilerplate code that’s common for view controllers. The nice thing about Objective-C is that it has very readable method names. Developers often complain that the method names are long, but the advantage is that you know what a method does just by looking at its name.

We will now write some code in our event action. Before that we need to add the “UIAlertViewDelegate” protocol to your controller as shown below in order to handle the button events.

iOSApp_21

In the action event we just now declared, we will show a simple alert message. Below code displays an alert message, on click of the “Fire message” button.iOSApp_22

Above you are creating and initializing your instance of the UIAlertView class. The initWithTitle: and message: parameters are self-explanatory and easily understood after seeing an alert displayed. The delegate: parameter refers to which class should receive delegate notification messages for the UIAlertViewDelegate . The cancelButton: parameter is the default button to be displayed along with the alert, and the otherButtonTitles: parameter is used to display one or multiple additional options that the user may select.

After creating an alert object, the [fireMessageAlertView show] call actually shows our message by popping our new UIAlertView onto the screen. Now, let’s build and run our application.

iOSApp_23

iOSApp_24

Let’s now implement the water view controller. First we drag and drop a textField from our object library and insert a place holder for it. To insert a place holder, we select the text field and on the right side property window, we have a “Place holder”.

iOSApp_25

We then drag a button and name it “water message” and drag a Image view from the object Library.

iOSApp_26

Inorder to display an image in our ImageView, we first need to add an image in our project. To do this, we right-click on our project name as shown in screenshot below and click Add Files to “Sample Example”iOSApp_27

A file browser window will appear, allowing you to select the image files on your Mac. Select the files and click Add. A confirmation window will appear; check the checkbox for “Copy items into destination group’s folder”. Click Add again.

Once you’ve added the images to the project, you can access them either in code or in Interface Builder.

We will add our image to the imageView through the interface builder.

Select the imageView on the storyboard and in the object inspector-> Image, we select the image from the combo box, the image will automatically get shown in our storyboard.

iOSApp_28

We will now create an IBOutlet for the textField, so that we can display the name of the person in our alert message on click of the “Water message” button.

In a similar fashion how we had created IBAction previously we create IBOutlets. We select the textfield and press the Ctrl key and then drag the mouse to the .h file as shown in the below snapshot.

iOSApp_28

Then, we left click the mouse which will give us a small popup to create our IBOutlet. For connection parameter we select “Outlet” as we want to create an outlet and not an action. We then specify the name of the textField and click on Connect.iOSApp_30

We will now create an IBAction for our “Water Message” button as done previously for “Fire Message” button.

iOSApp_31

We include 2 delegates for our water view controller implementation file.

iOSApp_32Below is the implementation for our action on clicking the “Water message button”.

iOSApp_33

Let’s build and run! When our app launches Click “Water” button on our first view controller and it will take us to the water view controller. Type your name in the textfield. Oh! What happened! Hitting return or touching anywhere on the screen does not dismiss the keyboard.

iOSApp_34

UIResponder is a superclass of UIView, which our text field inherits from. When an object has ‘firstresponder’ status, you can think of it as ‘having focus’ – it must respond to touches and other events. For our text field, that involved bringing up a keyboard (handled for us automatically). By resigning first responder status, we are essentially saying “we’re done, we won’t be responding to input any more” – so our keyboard goes away.

Select the file WaterViewController.m and edit it. Add the below two functions to our implementation file.

iOSApp_35

iOSApp_36

That’s it, You have successfully created your first iOS application!

 

Diving into the iOS world!

Now developing an iOS app is not hard. In fact, there are numerous tools that make developing your own iOS app easy and fun. Armed with a little knowledge and these tools, you too can learn to code iOS apps. I can say “Programming iOS is now programmer friendly”.

I believe that the best way to learn anything is by taking action and failing as fast as possible. Instead of reading or watching videos non-stop, put that knowledge into action so you can actually identify the gaps in your knowledge.

Learning iOS programming is no different. The best way to start is to open up Xcode and try to build a simple sample that provide with the basics that you need to know before starting to program in iOS.

From there, you learn how to layout UI Elements on the screen and how to respond to user interactions. Then learn how to introduce a second view into your app and how to navigate between the two views.

What we need to know before programming in iOS

In order to program in iOS we need to have prior knowledge of Objective-C that is an object-oriented programming language used primarily to develop iOS and Mac apps. However, it’s a general purpose programming language. To build sophisticated apps, you’ll need some libraries that do the heavy lifting for you.

Cocoa is a set of Objective-C frameworks (libraries) created by Apple that enable you to develop apps for the Mac. Cocoa Touch is based on Cocoa, but is used specifically for developing mobile apps that look and feel like the familiar apps on your iPhone or iPod Touch. Cocoa Touch provides all the core user interface components you’ll need to develop graphical, event-based iOS apps. UIKit provides the basic tools you need to implement graphical, event-driven applications in iOS.

The iOS SDK is a set of Objective-C frameworks (libraries) and tools that allow you to create apps for iPhone, iPod Touch, and iPad devices. It also includes an iOS Simulator so you can run your apps on your Mac during development.

Xcode is the IDE used for Mac and iOS programming. It was created by Apple, and included in the iOS SDK.

Core Data is a set of design tools and APIs for persisting data in iPhone apps. The data can be manipulated using higher level objects representing entities and their relationships.

Core Animation adds that “wow!” factor to your iPhone app. It’s not just cool, it also improves the user experience to set your app apart from the crowd. Most of the work required to draw each frame of an animation is done for you. All you have to do is configure a few animation parameters (such as the start and end points) and tell Core Animation to start. Core Animation does the rest, handing most of the actual drawing work off to the onboard graphics hardware to accelerate the rendering. This automatic graphics acceleration results in high frame rates and smooth animations without burdening the CPU and slowing down your app.

CocoaPods is the dependency manager for Objective-C projects. It has thousands of libraries and can help you scale your projects elegantly. They are open source and easily available. CocoaPods will make developing projects much easier.

Model-View-Controller

The Model-View-Controller (MVC) design pattern assigns objects in an application one of three roles: model, view, or controller. The pattern defines not only the roles objects play in the application, it defines the way objects communicate with each other. Each of the three types of objects is separated from the others by abstract boundaries and communicates with objects of the other types across those boundaries. The collection of objects of a certain MVC type in an application is sometimes referred to as a layer—for example, model layer.

MVC is central to a good design for a Cocoa application. The benefits of adopting this pattern are numerous. Many objects in these applications tend to be more reusable, and their interfaces tend to be better defined. Applications having an MVC design are also more easily extensible than other applications. Moreover, many Cocoa technologies and architectures are based on MVC and require that your custom objects play one of the MVC roles.

MVC

What is a Storyboard?

A storyboard is the visual representation of all the screens in an application. It also tells you about the transitions between various screens. It is represented as scenes and segues.

A scene refers to a single view or view controller. Each scene has a dock to make outlet and action connections between the view and its view controller.

A segue manages the transition between two scenes. A segue is established by pressing ctrl key and dragging from one scene to the other. Pushing a view controller to the navigation stack and presenting a modal view controller on the click of a button can be done easily with the help of segue thereby reducing the need for coding.

The entire application flow can be seen in the storyboard file.

Autolayout:

It’s not hard to design a user interface for a screen that is always guaranteed to be the same size, but if the screen’s frame can change, the positions and sizes of your UI elements also have to adapt to fit into these new dimensions.

When you position a button in the center of the view and run the app on another screen size, it doesn’t look good. The button is not centered properly.

What’s wrong? How can you make it right? The answer is Auto Layout. Auto Layout is a constraint-based layout system. It allows developers to create an adaptive interface that responds appropriately to changes in screen size and device orientation.

Auto Layout is a fantastic tool. It does things that earlier technologies could never dream of. It is a new way to define dynamic GUIs. With Auto Layout you arrange your app’s UI using relations between UI elements. These relations are called constraints.

Auto Layout is a system that lets you lay out your app’s user interface by creating a mathematical description of the relationships between the elements. You define these relationships in terms of constraints either on individual elements, or between sets of elements. Using Auto Layout, you can create a dynamic and versatile interface that responds appropriately to changes in screen size, device orientation, and localization.

Memory management

Automatic Reference Counting (ARC) is a memory management enhancement that was introduced in the iOS 5 sdk where the burden of keeping track of an object’s reference count is lifted from the programmer to the compiler.In traditional Objective-C, the programmer would send retain and release messages to objects in order to mark objects for deallocation or to prevent deallocation. Under ARC, the compiler does this automatically by examining the source code and then adding the retain and release messages in the compiled code. ARC provides a significant performance increase. Starting from Xcode 4.2 and the introduction of the new LLMV compiler, is now possible to use “Automatic Reference Counting” (ARC).

What is different about the language?

Using square brackets to call methods is a little wack, but you’ll get over that in about 20 minutes. Honestly, the syntax is a little bumpy for a day or two, tops…after that, there’s a lot to like about Objective-C.

The ease of creating UI components wherein you just drag and drop the components on the storyboard and also when placing the components in the view controller there is a helper which is indicated with blue lines in order to indicate the correct positioning of the component.

Apple documentation makes life lots easier and guides you in the right direction

Not to forget, the auto complete feature in Xcode makes it a great experience to program in iOS. The predefined functions, properties, Delegate methods or functions, etc are self explanatory and can easily be understood.

In iOS, the platform does not change quite often therefore programmers do not have to change the code to adapt to the new platform.

With the inclusion of ARC, Objective C has replaced Java as my all time favorite language as well.

Challenges faced when programming in the iOS world

  • Adapting to keyboard

The first challenge is the shortcut keys used in the iOS world. One needs to get accustomed to the shortcut keys like a simple example will be the “select all” generally we use “Ctrl+A” but in the iOS world it is “Cmd +A”.

  • iOS Application Compatibility

There are various Apple products available in the market including iPhone 4, 4S, 5, 5S, 5Cand iPad (1st, 2nd 3rd Generation, the iPad mini series and the iPad Air!), and it is necessary for an excellent iOS platform app to be compatible with all these products. Testing your application becomes highly important.

  • Apple App Store Approval

Before you start developing an iOS based application, it is mandatory for you to learn about the guidelines outlined by the App Store; you must conform to all the listed rules and regulations, so that your app gets accepted in the App Store. It will help you save time and aid you through various investment challenges.

  • Uniqueness

Last to mention, but not the least important: one of the basic challenges is actually developing the application that would not get lost among thousands of similar apps already available in the App store, i.e. something that will catch and win users attention.

 

References:

https://www.cocoacontrols.com/
http://www.pragmaticstudio.com/iphone-roadmap
https://developer.apple.com/library/ios/documentation/general/conceptual/devpedia-cocoacore/MVC.html
http://www.sitepoint.com/ios-application-development-storyboards/

Introduction to Auto Layout

Tag Cloud