How to build a iPhone app Tutorial

how to build a iphone app on windows and how to build iphone app with html5/css/javascript and how to build iphone apps on windows free
Dr.KiranArora Profile Pic
Published Date:27-10-2017
Your Website URL(Optional)
Getting Started with iOS The mobile industry is the fastest growing domain among other IT domains. iOS plays a key role in the mobile industry; nowadays, even the key IT players are incorporating mobility in the enterprise way. This title will help you understand the basics of iOS development and its implementation from the perspective of enterprises. To get started with iOS development, we will need the following things: • A Mac system • Xcode • The iOS SDK Basically, iOS development is based on the Objective-C language. Objective-C is an extension of the C programming language; this includes the OOP (object-oriented programming) concept and adds small-talk style messaging to C. Xcode is built to help you build great apps for iPad, iPhone, and Mac. Xcode is an IDE (Integrated Development Environment) for iOS. Started with iOS You can download Xcode from the Apple store as shown in the following screenshot: The Xcode option It is free; after downloading Xcode, it automatically appears in the launch pad. Xcode provides different features such as coding, design, a user interface, and testing for you. In this chapter, we will cover the following topics: • Interface and implementation classes • Types of methods in iOS • Datatypes • Arrays • Property and synthesize • Delegates • Building a simple app 8 1 Interface and implementation In Objective-C, there are two types of files that represent a single class: one is the interface implementation interface file and the other one is the file. In the file, the declaration of a method and variable is done; in theimplementation file, we define this method and use the declared variable. Code snippets for interface and implementation The following is the code snippet for theinterface class: interface MyClass:NSObject // declare class variables here // class methods and instance methods are declared here end TheMyClass.h file is an interface class.NSObject is a root class of all the classes, and it is a must to import theNSObject class. Theend keyword indicates that our interface block is completed. The following is ourimplementation class named asMyClass.m: implementation MyClass // class methods are defined here end Types of methods in iOS The methods that we declare in theinterface l fi e are den fi ed in the implementation l fi e. Methods are declared in the following way: -(returnType)methodName:(typeName) variable1 :(typeName)variable2; There are two methods in iOS: one is the class method and the other is the instance method. In the class method, we do not have to create an object; we can directly access these methods using their class names. The class method is indicated by the + symbol. We can find static methods in languages such as Java and C++, and we will find class methods in languages such as Objective-C and Ruby. The difference between the static and class methods is that they have different language concepts. 9 Started with iOS The principal differences are: • Static methods are shared between all instances (this doesn't exist in Objective-C). • The class method is a method on a class. In languages such as Objective-C and Ruby, a class itself is an instance of another class (metaclass). Using + before a method declaration means that the method will be defined on the class. Technically, it's just an instance method on a different object. The syntax for the class method is as follows: +(void)classMethod; In the instance method, we have to create an object. We can't access the instance method without creating an object. Memory is allocated for an object. Thealloc keyword is used to allocate memory. The following syntax is used for the instance method: -(void)InstanceMethod; Creating objects An object is created in theimplementation file as follows: MyClass object= MyClass allocinit ; object InstanceMethod; Here, we used thealloc andinit keywords. Thealloc keyword is used to allocate memory to the object, and theinit keyword is used to initialize that object. Important datatypes Like any other programming language, iOS also has different datatypes such asint, float,double,char, andid. Datatypes are used to specify the kind of data that is being stored in a variable. There are four important datatypes in iOS: • NSString: This is used to represent a string • NSInteger: This is used to declare an integer • CGFloat: This is used to declare float values • BOOL: This is used to declare a Boolean (yes or no) value 10 1 Array Array is a collection of homogeneous datatypes with contiguous memory allocation. In iOS, arrays are of two types: • NSArray • NSMutableArray NSArray NSArray is an immutable array. In Objective-C, by default, arrays are immutable, that is, as the name indicates, it's object can't be changed or removed after the initialization of the array: NSArray xyz = NSArray alloc init; Xyz = "Harry", "Tom", "jack"; NSMutableArray NSMutableArray is a subclass ofNSArray. This is a modifiable array, and its object can be removed or modified after the initialization of array: NSMutableArray xyz = NSMutableArray alloc init; Xyz = "Harry", "Tom", "jack"; The concept of String is the same as in C. String also has two types:NSMutableString andNSString. Consider the following example for theNSString type: NSString myName = "Jack"; Property and Synthesize The properties of an object are defined to let other objects use or change their state. However, in object-oriented programming, it's not possible to access the internal state of an object directly from outside the class (except public accessors). Instead, accessor methods (getters and setters) are used to interact with the objects. The goal of theproperty is to make it easier to create and congure pr fi operties by automatically generating these accessor methods: • property: This method implements the setter/getter methods in our code automatically; we don't have to write the code manually. 11 Started with iOS • synthesize: This method synthesizes the properties with the given attributes, and the compiler will generate the setter and getter methods for our variables. However, now we do not usesynthesize; instead of synthesize, we use an underscore (_) or theself keyword. Let's understand these methods with a code snippet. This is the interface file: import Foundation/Foundation.h interface MyClass : NSObject property void methodname; end This is the implementation file: import "MyClass.h" implementation Class synthesize methodname = _methodname; end In Objective-C, every object holds a reference count. When an object is created, its reference count increases by one; when it releases the object, the reference count decreases by one. When the reference count reaches zero, it deallocates the memory by itself. The attributes ofproperty is as follows: • atomic: By default, every property is atomic. It will ensure that a whole value is always returned by the getter method or set by the setter method. Only a single thread can access a variable to get or set a value at a time. So, atomic is also thread-safe. • nonatomic: Innonatomic, there is no guarantee that the value returned from a variable is the same one that the setter method sets. At the same time, more than one single thread can access a variable at a time. • strong: Thestrong attribute owns the object. The compiler will ensure that any object that we assign to this property will not be destroyed as long as we (or any other object) point to it with a strong reference. • weak: In aweak reference, we don't want to have control over the object's lifetime. The object we are referencing weakly only lives on because at least one other object holds a strong reference to it. • retain: This specifies that retain should be invoked on the object upon assignment. It takes ownership of an object. • assign: This specifies that the setter uses simple assignment. It uses an attribute of the scalar type, such asfloat orint. • copy: This copies an object during assignment and increases the retain count by one. 12 1 Consider the following simple example using the attributes: property (nonatomic, assign) float radius; property (atomic, strong) NSString name; Delegates A delegate is a tool through which one object can communicate with another; in turn, the objects can stay connected to each other. It is a method by which one object can act on behalf of another object. The delegating object keeps a reference to the other object and, at the appropriate time, sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or that is to be handled. Consider the following example of how to use a delegate. Let's define the FirstViewController.h interface file as follows: import "SecondViewController.h" interface FirstViewController : UIViewController SecondViewControllerDelegate IBOutlet UITextField userNameTextField; property (nonatomic, strong) UITextField userNameTextField; -(IBAction)goNext:(id)sender; end Now, let's define the FirstViewController.m implementation file: import "FirstViewController.h" interface FirstViewController () end implementation FirstViewController synthesize userNameTextField; -(void)goNext:(id)sender SecondViewController secondVC = SecondViewController alloc init; 13 Started with iOS secondVC.delegate = self; self.navigationController pushViewController:secondVC animated:YES; -(void)done:(NSString)name NSLog("BACK in firstVC"); userNameTextField.text = name; end Next, we will define the SecondViewController.h interface file as follows: import "FirstViewController.h" protocol SecondViewControllerDelegate NSObject -(void)done:(NSString)someText; end interface SecondViewController : UIViewController IBOutlet UITextField someText; IBOutlet UIButton returnButton; id delegate; property (assign, nonatomic) id SecondViewControllerDelegate delegate; property (strong, nonatomic) UITextField someText; -(IBAction)goBack:(id)sender; end Now, we will define the SecondViewController.m implementation file as follows: import "SecondViewController.h" interface SecondViewController () end implementation SecondViewController synthesize someText; synthesize delegate = _delegate; 14 1 -(void)goBack:(id)sender self.delegate done:someText.text; FirstViewController firstVC = FirstViewController allocinit; self.navigationController pushViewController:firstVC animated:YES; end Building our first iPhone app Let's make our first iPhone app by performing the following steps: 1. Open Xcode; you will see the following screen. In the panel on the right-hand side, you can see your existing projects. You can open your project directly by selecting from the list of projects; for a new project, on the other hand, select Create a new Xcode project. 15 Started with iOS 2. There are eight templates provided by Xcode. In the panel on the left-hand side, you can see there are two options: iOS and OS X. iOS is for Apple touch devices, and OS X is for desktop devices. Initially, choose Single View Application. Then, click on NEXT, as shown in the following screenshot: 3. Now, it is time to give a name to your project and choose iPhone from the Devices dropdown. Then, click on Next. The following screenshot will appear: Downloading the example code You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visithttp://www. and register to have the files e-mailed directly to you. 16 1 4. Save your project in the directory of your choice: 17 Started with iOS 5. Now, your editor will look like the following screenshot. In the left-hand-side panel, there is a declaration of classes. Select the storyboard from the left-hand-side panel. Storyboard provides the view to your application. This is your storyboard. At present, it is an empty view controller. Storyboard has many areas, such as the navigation area, editor area, utility area, and debug area, that are described as follows: ° Navigation area: In this pane, there are various navigators that we can switch between using the Navigator selector bar. The three navigators that we will use a lot are the Project, Search, and Issue navigators. ° Editor area: The editor area is where we'll probably be spending most of our time This is where all the coding happens. 18 1 ° Utility area: The Xcode utility area comprises two panes: the Inspector pane and the Library pane. The Inspector pane will give us details about the file. However, when we are looking at the storyboard, the Inspector pane will show us the different attributes that you can modify for a selected element. The Library pane won't be very useful until we look at a storyboard. When we use the Interface Builder part of Xcode, we can drag UI elements from the Library pane onto the editor area to add them to our user interface. ° Debug area: The debug area will show us the console output and the state of various variables when you run your application. In the following screenshot, we can see an arrow before the view; this indicates that the view is a starting view of the application. When the application launches, this view will launch first: 19 Started with iOS 6. On the right-hand side, a lot of components, such as button, label, and text fields, are present (we will learn about these components in the upcoming chapters). Drag-and-drop a button from the right-hand-side panel as shown in the following screenshot. Rename it by double-clicking on it; give it any name. For example, name itHello. This is all our UI part. Now, let's move on to the coding section. 7. Go toViewController.h and write the following method in it. The.h file is an interface file of our project where we declare the property and method. If we want to declare variables, then they are declared under the braces of the interface; the property and methods are defined outside the braces: interface ViewController : UIViewController Int x; property (nonatomic, strong) NSStringrecipeName; Coming back to our program, we have to describe one method,showMessage, where we describe the UIAlertview function; this appears as a pop-up window with a message. 20 1 The following screenshot shows the editor area with the preceding code snippet: Let's understand the code line by line: ° import UIKit/UIKit.h: This is a header file that we import in our code.UIKit is a framework that contains all the inbuilt library files for the UI part. TheUIKit header file imports all the other header files available in theUIKit framework; after importing this header file, we don't have to import otherUIHeader files such as UIViewController.h,UIView.h, orUIButton.h manually. ° interface ViewController: UIViewController: This is an interface for theViewController.h class. It inherits the UIViewController class, which is used to handle the flow of our screen or view. ° (IBAction)showMessage: This is a method that we created manually. When we want to perform some action on tapping a button, we will useIBAction. This is a kind of return type in iOS. Here, the name of the method isshowMessage (we can give any name).IBAction tells the UI Builder that the method can be used as a selector (event receiver). ° end: This code indicates that our interface part is over. 21 Started with iOS 8. Now, go toViewController.m and describe the method that is defined in the.h file. This is also called an implementation file. The following screenshot illustrates the code used in the implementation file: Once again, let's understand the code line by line: ° import "ViewController.h": This imports our.h class (interface class). ° implementation ViewController: From this snippet, our implementation of the method starts. The method that we declare in the interface file will be implemented here. It also contains some inbuilt methods such as–(void)viewDidLoad,-(void) didRecieveMemoryWarning, and so on. We can code inside these methods as needed. If we choose the Empty application template, then these inbuilt methods won't be provided. ° UIAlertView: Alert views are the pop-up views or messages that appear over the current view. We can use this by making an object of it. Here,Alert is an object.alloc is a keyword use to allocated memory for an object. ° Alert show: This snippet is used to display the pop up over the screen. 22 1 Now we have to connect this button to the method that we declare. Without connecting the button, it won't work. Use the following steps to connect the button. 9. Right-click on the button. A black pop-up window will appear. Select Touch Up Inside and connect it to View Controller, as shown in the following screenshot. After releasing the mouse, select showMessage from the pop up. 23 Started with iOS 10. Now, your button is connected to theAlert method. This is the time to execute your project. Run your project and click on the Hello button. Your output will look like the following screenshot: Summary In this chapter, we learned the basics of iOS, such as methods, arrays, properties, delegates, and so on. After this chapter, we will also be able to use Xcode, and we can make simple apps using the UI component. In the next chapter, we will learn more about components. 24 Exploring More UI Components UI Elements is the visual part that we can see in our applications. These elements respond to user interactions such as buttons, text fields, and other labels. Some UI elements are used to make our graphical application; examples include images, pickers, Map kit, and many more. Xcode helps you to build many interfaces using an interface builder. TheUIKit framework provides the classes needed to construct and manage an application's components or user interface. TheUIKit framework is responsible for handlingUIComponents, managing views and windows, and creating connections between components and code. UI elements can be used in two ways: • By dragging-and-dropping them from the interface builder • By programmatically adding the components to the view We will cover the following topics in this chapter: • Adding UI components programmatically • Some featured UI components • Understanding the anatomy of Table view • Scroll view and its usage • Navigation controller Adding UI components programmatically As mentioned in the introduction, we can add the components through coding. Let's begin with some simple examples. More UI Components Adding a view In Xcode, on the left-hand panel, you can find the AppDelegate.m file as shown in point 1 of the following screenshot. Navigate to the file. There is a lot of code, but we will focus on only one function,application:didFinishLaunchingWithOptions, as shown in point 2 of the following screenshot: Just add the following code in the function (didFinishLaunching) to make it look similar to following: - (BOOL)application:(UIApplication )application didFinishLaunchingWit hOptions:(NSDictionary )launchOptions self.window = UIWindow alloc initWithFrame:UIScreen mainScreen bounds; UIView view = UIView alloc initWithFrame:self.window.bounds; view setBackgroundColor:UIColor blueColor; self.window addSubview:view; self.window makeKeyAndVisible; return YES; 26

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.