<<

Mobile Applications and Services FALL 2013

- iOS basics Navid Nikaein Mobile Communication Department

This work is licensed under a CC attribution Share-Alike 3.0 Unported license. What do you need?

. Mac OS X 10.5 or above . Notions on OO programming (Objective ) . iOS SDK (Free, registration required) . iOS Dev License (Optional)  Student Program: Free  Individual Program: $99  Enterprise Program: $399 . An iPhone/iPod Touch/iPad (Optional)

©Navid Nikaein 2013 2 iOS Smart Mobile Devices

. iOS 7 . Multi Touch Display (1.136x640) . Storage 8-64 GB . Processor M7 /A7 64 bits, A6, A5 . Graphics Power VR . Memory 1GB DDR2 . Connectivity Secondary  USB 2.0 Applications  GSM/GPRS/EDGE/UMTS/HSDPA/LTE  Wifi 802.11 b/g/n  BT  Assisted GPS . Double Camera: 8 MP & 1.2MP Primary . HD Audio/VIDEO Applications . Power 3.8 V . Weight 112g

©Navid Nikaein 2013 3 Platform Components

. iOS SDK / Tools . Language . Frameworks . Design Strategies

©Navid Nikaein 2013 4 Platform Component - iOS SDK

. Tools: .m, .h .nib  Text editor, Debugger &  Interface Builder (UI)  storyborad .xib Creates user interface (xml)  (profiler ) Optimize the application  Dash Code Create web applications for  iOS Simulator (Code-Build-Debug) Dtrace, NSZombies, Guard Mallloc  Reference Library

©Navid Nikaein 2013 5 Xcode

©Navid Nikaein 2013 6 App Development Process

. Who are your audience ? . What is the purpose of your app? . What problem your app trying to solve? . What content your app incorporate?

©Navid Nikaein 2013 7 Next step

. After you have a concept for your app, designing a good user interface is the step to creating a successful app  Storyboard, views ,…  Define the interaction  Implementing the behaviours

©Navid Nikaein 2013 8 Platform Component - iOS Language

. Objective-C / C  Extension to (superset of) standard ANSI C with -style messaging designed to give C full OO programming capabilities  Primary language for Apple’s Cocoa API  C & GCC can be used for low-level programming

©Navid Nikaein 2013 9 A big Picture

©Navid Nikaein 2013 10 Platform Component - iOS Frameworks Name Prefixes Name Prefixes Accelerate.framework cblas, vDSP EventKitUI.framework EK AddressBook.framework AB ExternalAccessory.framework EA AddressBookUI.framework AB Foundation.framework NS AssetsLibrary.framework AL GameKit.framework GK AudioToolbox.framework AU,Audio iAd.framework AD AudioUnit.framework AU ImageIO.framework CG AVFoundation.framework AV IOKit.framework N/A CFNetwork.framework CF MapKit.framework MK CoreAudio.framework Audio MediaPlayer.framework MP CoreData.framework NS MessageUI.framework MF CoreFoundation.framework CF MobileCoreServices.framework UT CoreGraphics.framework CG OpenAL.framework AL CoreLocation.framework CL OpenGLES.framework EAGL, GL CoreMedia.framework CM QuartzCore.framework CA CoreMotion.framework CM QuickLook.framework QL CoreTelephony.framework CT Security.framework CSSM, Sec CoreText.framework CT StoreKit.framework SK CoreVideo.framework CV SystemConfiguration.framework SC EventKit.framework EK UIKit.framework UI

©Navid Nikaein 2013 11 iOS Frameworks: New

Name Prefixes Account.framework AC CoreBluetooth.framework CB CoreImage.framework CI Core.MIDI.framework MIDI GLKit.framework GLK GSS.framework gss Twiter.framework TW

See appendix B of iOS Technology Overview

©Navid Nikaein 2013 12 frameworks

©Navid Nikaein 2013 13 iOS Design Patterns and Techniques

. Model-view-controller  design pattern that governs the overall structure of your app . Delegation  Transfer information and data from one object to another . Target-Action  Translates user interactions with buttons and controls into code that your app can execute . Block-Objects  Implement callbacks and asynchronous code . Sandboxing  Protect the system and other apps

©Navid Nikaein 2013 14 Platform Component - iOS Design Strategy

. Cocoa version of Model-View-Controller (MVC)  Assigns objects in an application one of three roles: model, view, or controller  Defines the way objects communicate with each other  Separate and allow generic view and models  Controllers acts as a glue between view and model . MVC allows reusability and flexibility to your application How your model is presented/viewed to the user (UI logic)

knows how to draw itself and Encapsulate, manipulate, and process can respond to user actions the data specific to an application

©Navid Nikaein 2013 15 MVC

. All about managing the communication between objects

©Navid Nikaein 2013 16 MVCs working together

©Navid Nikaein 2013 17 MVC

. Model = manipulate and process data / algorithm / networking  Not aware of controller and view  To-one and to-many relationship with other model objects  Communicate generically using broadcast channel Key-value observing (listen to changes) Notification (NSNotificationCenter)  Communication example User actions in the view layer that create or modify data are communicated through a controller object and result in the creation or updating of a model object. When a model object changes (for example, new data is received over a network connection), it notifies a controller object, which updates the appropriate view objects

©Navid Nikaein 2013 18 MVC

. View = Display / Event capture / Visual interaction  Not aware of controller and model  Know how to draw itself and user can interact with it  Generic and provides consistency between applications  Communicate generically using Target – Action Delegate (Will, did, should)  Communication example View objects learn about changes in model data through the application’s controller objects User-initiated changes—for example, text entered in a text field— through controller objects to an application’s model objects.

©Navid Nikaein 2013 19 MVC

. Controller = coordination / delegation / dirty job  Know about view and model objects  Manage views, datas, and application logic and lifecycle  App –specific code  Communication: A controller object interprets user actions made in view objects and communicates new or changed data to the model layer. When model objects change, a controller object communicates that new model data to the view objects so that they can display it.

©Navid Nikaein 2013 20 Application Object and Delegation

. Application template comes with a few existing source code files that set up the app environment.  UIApplicationMain function creates the app object to work with iOS  create a run loop to deliver events to your app coordinates other high-level app behaviors  Called by main.m . UIApplicationMain creates two components  Application object: an instance of UIApplication  App Delegate : creates and keep track of the window where your app’s content is drawn Lifecycle: provides a place to respond to state transitions within the app:

©Navid Nikaein 2013 21 Target-Action

. Action  Piece of code that’s linked to some kind of event that can occur in your app  creating and implementing a method with an IBAction return type and a sender parameter  - (IBAction)restoreDefaults:(id)sender;  Sender points to the object that triggers the action . Outlet  provide a way to reference objects from your interface  @property (weak, nonatomic) IBOutlet UITextField *textField; . Control Event  provide a way for your code to receive messages from the user interface  Touch and drag events  Editing events  Value-changed events . Navigation controller  Manage the transition between the views  Navigation stack is LIFO, and the first item is always root view controller

©Navid Nikaein 2013 22 Sandbox

. Fine-grained controls that limit the app’s access  Hone of the app . App and its preferences and data are placed in sandbox at the install time

©Navid Nikaein 2013 23 Core Objects of an App

Image View

Text View

Button

©Navid Nikaein 2013 24 App States

. Not running  app has not been launched or was running but was terminated by the system . Inactive  running in the foreground but is currently not receiving events . Active  running in the foreground and is receiving events . Background  Background and executing code  Before being suspended  Background directly . Suspended  Background and not executing code

©Navid Nikaein 2013 25 State Transitions

. application:willFinishLaunchingWithOptions  first chance to execute code at launch time. . application:didFinishLaunchingWithOptions  perform any final initialization before your app is displayed to the user. . applicationDidBecomeActive  Lets your app know that it is about to become the foreground app. Use this method for any last minute preparation. . applicationWillResignActive  Lets you know that your app is transitioning away from being the foreground app. Use this method to put your app into a quiescent state. . applicationDidEnterBackground:  Lets you know that your app is now running in the background and may be suspended at any time. . applicationWillEnterForeground  Lets you know that your app is moving out of the background and back into the foreground, but that it is not yet active. . applicationWillTerminate  Lets you know that your app is being terminated. This method is not called if your app is suspended.

©Navid Nikaein 2013 26 App Launch Cycle

©Navid Nikaein 2013 27 iOS Architecture

. iOS can be viewed as a set of layers

HW

©Navid Nikaein 2013 28 iOS Features

. Media  Graphics . Cocoa touch  Audio  UIkit  Camera & photo lib  Multitouch gestures  iPod media lib  Storyborad  Document , printing . Core services  iOS simulator . Networking Services  Inter-app messaging  Store Kit (in-app)  Messaging  Push notification  In-app SMS  Game Kit  Cut, copy, paste  iAd  Gyro + accelerometer  Core location  Multitasking  Map Kit  Addressbook  Networking (BSD Socket)  Compass  Accelerate  Accessories  Quicklook

©Navid Nikaein 2013 29 iOS – Core OS

. Low level interface for (kernel environment and drivers)  Accelerate Framework iOS  Core Bluetooth  External Accessory Framework Cocoa Touch  Security Framework . Lib System Library Media  Threading (POSIX threads)  Networking (BSD sockets) Core Service  File-system access Core OS  Standard I/O  Bonjour and DNS services  Locale information  Memory allocation  Math Computation

©Navid Nikaein 2013 30 iOS – Core Service

. Fundamental system services for applications  Account Framework  Address Book Framework iOS  Core Foundation Framework  CFNetwork Framework Cocoa Touch  Framework  Core Location Framework Media  Core Media Framework (low-level)  Core Telephony Framework Core Service  Event Kit Framework  Foundation Framework Core OS  Mobile Core Service Framework  Newsstand Kit Framework  Quick Look Framework  Store Kit Framework  System Configuration Framework

©Navid Nikaein 2013 31 iOS – Core Service

. CF Network Framework . Foundation  BSD sockets Framework  Encrypted  Collection data types connections(SSL / TLS )  Bundles  Resolve DNS hosts  Date and time iOS  Work with HTTP, management authenticating HTTP,  Raw data block Cocoa Touch HTTPS , FTP servers management  Publish, resolve, and  Preferences browse management Media  Bonjour services  URL and stream . Core Data Framework manipulation Core Service  Threads and run loops  SQLite lib  Bonjour  Manage and edit data Core OS  Communication port  Validation and data management consistency  Internationalization  Support for grouping, filtering, and organizing  Regular expression data in memory matching  Cache support

©Navid Nikaein 2013 32 iOS – Media

. Technologies for creating multimedia experience  Assets Library Framework (retrieving photo/video)  AV Foundation Framework  Core Audio iOS  Core audio Framework  Audio toolbox Framework Cocoa Touch  Audio unit Framework  Core Graphic Frameworks (Quartz 2D)  Core Image framework Media  Core MIDI framework  Core Text Framework Core Service  Core Video Framework  Image I/O Framework Core OS  GL Kit framework  Media Player Framework  Open AL Framework  OpenGL ES (3D audio for game)  Quartz Core Framework

©Navid Nikaein 2013 33 iOS – Media

. AV Foundation Framework  Media asset management  Media editing iOS  Movie capture  Movie playback Cocoa Touch  Track management Media  Metadata management for media  Stereophonic panning Core Service  Synchronization between sounds Core OS  An Objective-C interface for determining details about sound files, such as the data format, sample rate, and number of channels

©Navid Nikaein 2013 34 iOS – Cocoa Touch

. Basic tools and infrastructure to implement graphical, event- driven applications in iOS iOS  Addressbook UI framework Cocoa Touch  Addressbook framework  Event Kit UI framework Media  Game Kit framework Core Service  iAd framework  Map kit framework Core OS  Message UI framework  UIkit framework  Twitter framework

©Navid Nikaein 2013 35 iOS – Cocoa Touch

. UI kit framework  Application management  User interface management  Graphics and windowing support  Multitasking support iOS  Support for handling touch and -based events  Representing the standard system views and controls  Support for text and web content Cocoa Touch  Cut, copy, and paste support  Support for animating user-interface content Media  PDF creation  Support for using custom input/text views that behave like the system keyboard Core Service . Other supports  Accelerometer data Core OS  The built-in camera (where present)  The user’s photo library  Device name and model information  Battery state information  Proximity sensor information  Remote-control information from attached headset

©Navid Nikaein 2013 36 Styles of Programming

. iOS defines three basic styles for applications:  Productivity style  Utility style  Immersive style

©Navid Nikaein 2013 37 Productivity Style

. Organization and manipulation of detailed information . Multiple screens and make use of system controls to handle the navigation from screen to screen . Typically rely on system views and controls (text fields, labels, and other data- oriented views) for their presentation and do little or no custom drawing

©Navid Nikaein 2013 38 Utility Style

. Perform a specific task that requires relatively little user input . A quick summary of information or a simple task on a small number of objects . Interface should be a visually appealing and uncluttered to make it easier to spot the needed information quickly . Use of appropriate graphics to have a pleasing visual appearance

©Navid Nikaein 2013 39 Immersive Application

. Offer a full-screen, visually rich environment that’s focused on the content and the user’s experience with that content . Commonly used for implementing games and multimedia-centric applications . Often present custom interfaces, and relies less on standard system views and controls . Typically use OpenGL ES to draw content, because it provides good performance for full-screen content at high frame rates

©Navid Nikaein 2013 40 OBJECTIVE-C

©Navid Nikaein 2013 41 OO Vocabulary

. Class  Defines the grouping of data and code  Create instances Object . Instance  A specific allocation of a class . Method  A “function” that an object knows how to perform . Instance Variable (or “ivar”)  A specific piece of data belonging to an object

©Navid Nikaein 2013 42 OO Vocabulary - Classes, Instance, and Object

. Classes declare state and behavior . State (data) is maintained using instance variables . Behavior is implemented using methods . Instance variables typically hidden  Accessible only using getter/setter methods

©Navid Nikaein 2013 43 OO Vocabulary

. Encapsulation Superclass

 Memory Restrict access to some of the NSObject object’s components management . Polymorphism Generic  Different vars / functions behavior UIControl /objects, same interface

. Inheritance Specific behavior UIBotton UITextField  Hierarchical organization, share code, customize or extend behaviors subclass

©Navid Nikaein 2013 44 Objective-C

. Invented in 1983 by Brad Cox and Tom Love after being introduced to Smalltalk. Released in 1986. . Is an object oriented language (like C++ or Java) . Follow ANSI C style coding with methods from Smalltalk . Almost everything is done at runtime!  Dynamic binding : map msg from one object to another  Dynamic typing : allow to capture/send msg to different obj  Dynamic linking : load , links, and bind shared libs at run time

©Navid Nikaein 2013 45 Files

. .h – Header files contain class, type, function, and constant declarations @interface Class : superClass { // member definitions } // public method definition @end . .m & .mm – Contains the implementation  .m: c and objective-C  .mm: c++, c, and objective-C @implementation Class // public & private methods @end

©Navid Nikaein 2013 46 A Quick Comparison

Java or C++ Syntax Objective-C Syntax

Person* person = new Person(); Person* person =[[Person alloc] init]; int age = person.age(); int age = [person age ]; person.setWeight(1.8); [person setWeight:1.8]; person.setXandY(20.0f,1.0f); [person setX:20.0f andY:1.0f]; delete person; [person release];

©Navid Nikaein 2013 47 A Quick Comparison C++ Syntax (.h) Objective-C Syntax (.h) Typedef struct { Typedef struct { Float x; Float x; Float y; Float y; } Point; } Point; Class Car { @interface Car : NSObject { Point position; Point position; float velocity; float velocity; Int model; Int model; Char* vin; NSString* vin; Public: } static const int viper =1; + (int) viper; Car (int m); -(id) initWithModel: (int)m; ~car(); -(void) dealloc; Point position(); -(Point) position; Void setPosition (Point P); - (void) setPosition:(Point)p; }; @end

©Navid Nikaein 2013 48 A Quick Comparison C++ Syntax (.cpp) Objective-C Syntax (.m)

#include « Car.h» #import « Car.h» @implementation Car Car::Car(int m) { + (int) viper {return1}; position.x=0.0f; - (id) initWithModel:(int)m { position.y=0.0f; position.x=0.0f; model = m; position.y=0.0f; model = m; Vin= « 295ZHGO45308 » Vin= @« 295ZHGO45308 » } } Car::~Car(){} - (void) dealloc {[super dealloc]; } Point position () {return position}; - (Point) position {return position}; - (void) setPosition:(Point)P{ Void setPosition (Point P) { position =p; position =p; } } @end

©Navid Nikaein 2013 49 Strong and Weak typing

. Strong typing is when we use a class name to define a

variable MyClass * class; NSObject * theObject; . Weak typing is when we use “id” as the type of the variable

 “id” can be anything id sender; id object;

©Navid Nikaein 2013 50 Method definition

. The following conventions are used in method declarations:  A “+” precedes declarations of class methods  A “-” precedes declarations of instance methods  Argument and return types are declared using the C syntax for typecasting  Arguments are declared after colons(:)

- (void)setWidth:(int)newWidth height:(int)newHeight  The default return and argument type for methods is id

©Navid Nikaein 2013 51 Calling methods

. Two words with in a set of brackets, the object or class identifier and the method name [identifier method] . Calling methods in Objective-C is like sending messages . Dynamic binding  The connection in between the message and the receiver will be done at runtime

©Navid Nikaein 2013 52 Class Methods

. Equivalent to the “static” methods in C . The “alloc” method is an example:

+(id)alloc; . To call the method we need to use a class

[NSString alloc];

. Automatic Reference counting (ARC)

©Navid Nikaein 2013 53 Instance Methods

. They can only be used on instances of objects

@interface Contact : superClass { } -(NSString *)getFullName; @end

Contact * me; [me getFullName];

©Navid Nikaein 2013 54 Member definition

. Instance variables  Members of the interface are defined in between the braces  Usually we do not access them directly

@interface Contact { NSString * name; } @end

©Navid Nikaein 2013 55 Member definition . We can add properties for the different members using the keyword “property”  Property: a combination of a getter and setter

@interface Contact { NSString * name; } @property (retain )NSString * name; @end

. Property declaration is equivalent to: - (NSString *)name; // getter - (void)setName:(NSString *)newName; //setter

©Navid Nikaein 2013 56 Declare properties

. Properties are defined in the interface

@property (attributes) type name; . They have to be “synthesized” in the implementation to be generated according to the property declaration

@implementation Contact @synthesize name; @end

©Navid Nikaein 2013 57 Declare properties

. The properties can have a comma separated list of attributes. . The possible attributes are:  getter=getterName  setter=setterName  readwrite / readonly  assign  retain  copy  nonatomic

©Navid Nikaein 2013 58 Interface Builder -- > view

. Members and methods can be connected with Interface Builder . Members are connected using the keyword “IBOutlet” in front of the type IBOutlet id ; . Methods are connected using the keyword “IBAction” as return type

-(IBAction)buttonPressed;

©Navid Nikaein 2013 59 Interface Builder

. Interface Builder recognize actions using three prototypes:

-(IBAction)actionName; -(IBAction)actionName:(id)sender; -(IBAction)actionName:(id)sender withEvent:(UIEvent *)event;

. We can connect objects and events from Interface Builder to the members and methods that we declare in Xcode

©Navid Nikaein 2013 60 Inheritance

. Only one inheritance at a time

@interface MyObject : NSObject { }

@end . All the members and public methods are inherited

©Navid Nikaein 2013 61 Protocols : multiple inheritance

. Protocols define a series of methods that classes, wanting to conform to it, have to define  a set of behavior that’s expected of an object in a given situation . A “protocol” is defined like an “interface” without implementation @protocol MyProtocol - (void) defineToBeConform; @end . We use < > brackets to give a comma separated list of protocols @interface MyObject : NSObject { } @end

©Navid Nikaein 2013 62 Delegates

. Not really part of Objective-C . Intensively used in the iOS ( touch) . A delegate is often a protocol . A delegate object is an object that acts on behalf of, or in coordination with, another object  Often is a responder object responding to a user event is delegated control of the user interface for that event, or is at least asked to interpret the event in an application  Example: UIAccelerometerDelegate . Original usage  Refers to one object relying upon another to provide a specified set of functionalities

©Navid Nikaein 2013 63 Memory Management

. iOS has a memory pool . Objects are reference counted . Two option: ARC enabled or disabled . The rule is: “We have to do a release for each alloc, create or copy that we use” NSString * aString = [[NSString alloc] init]; self.theString = aString; [aString release]; Note: the String in the example has to have the property attribute “retain” or the string will be destroyed by the

pool. @property (retain) NSString * theString;

©Navid Nikaein 2013 64 5 Very Important References

. developer.apple.com/library/ios  iOS technology Overview  iOS App Programming Guide  Your First iOS App  iOS App Development Workflow Guide  Cocoa Fundamentals Guide  Learning Objective-C: A Primer . Stanford course: iPhone application development  http://www.stanford.edu/class/cs193p/cgi-bin/drupal/downloads-2011- fall . developer.apple.com/technologies/  Developer tools  iOS . Next Session  Read NSObject and UIView documentation

©Navid Nikaein 2013 65 Calling Methods

. Calling method on an object

[object method]; [object methodWithInput:input]; . Method can return a value

output = [object methodWithOutput]; output = [object methodWithInputAndOutput:input]; . Call method on classes, which is how you create an object.

id myObject = [NSString string]; NSString* myString = [NSString string]; . id type means that the myObject variable can refer to any object  id type is predefined as a pointer type

©Navid Nikaein 2013 66 Calling Methods

. Nested message [NSString stringWithFormat:[prefs format]]; . Multi-input methods  Method name is writeToFile:atomically: which is splited up into several segments

-(BOOL)writeToFile:(NSString*)path atomically:(BOOL)useAuxiliaryFile; BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];

©Navid Nikaein 2013 67 Accessors

. Use accessors to get and set values, as all instance variables are private by default

 Setter [photo setCaption:@"Day at the Beach"];

 Getter output = [photo caption];  [] is actually sending a message to an object or a class . Dot Syntax  Only used for setters and getters and not for general purpose

methods photo.caption = @"Day at the Beach";

output = photo.caption;

©Navid Nikaein 2013 68 Creating Objects

. Automatic style NSString* NSString myString = [ string]; . Manual style with nested methods  Detail of init is unknown as a client of the class

NSString* myString = [[NSString alloc] init]; . Different version of init

NSNumber* value = [[NSNumber alloc] initWithFloat:1.0];

©Navid Nikaein 2013 69 Basic Memory Management

. Garbage collector

// string1 will be released automatically string NSString* string1 = [NSString ]; . Manual MM

// must release this when done NSString* string2 = [[NSString alloc] init]; [string2 release];

©Navid Nikaein 2013 70 Logging

. Log in console

NSLog(@"The current date and time is:%@",[NSDate date]); . NSLog calls the description method on the object, and prints the NSString which is returned. . You can override the description method in your class to return a custom string

©Navid Nikaein 2013 71 Calling Method on Nil

. “nil” Object == Null Pointer in C . You call methods on “nil” without crashing or exceptions . Example: improving “dealloc” method

- (void) dealloc { * self.caption = nil; self.photographer = nil; [super dealloc]; }

. There's no chance of the variable pointing at random data where an object used to be

©Navid Nikaein 2013 72 OBJECTIVE-C THROUGH AN EXAMPLE

©Navid Nikaein 2013 79 Walk Through Example

©Navid Nikaein 2013 80 Walk Through Example

©Navid Nikaein 2013 81 Walk Through Example

©Navid Nikaein 2013 82 Walk Through Example

©Navid Nikaein 2013 83 Walk Through Example

©Navid Nikaein 2013 84 Walk Through Example

©Navid Nikaein 2013 85 Walk Through Example

©Navid Nikaein 2013 86 Walk Through Example

©Navid Nikaein 2013 87 Walk Through Example

©Navid Nikaein 2013 88 Walk Through Example

©Navid Nikaein 2013 89 Walk Through Example

©Navid Nikaein 2013 90 Walk Through Example

©Navid Nikaein 2013 91 Walk Through Example

©Navid Nikaein 2013 92 Walk Through Example

©Navid Nikaein 2013 93 Walk Through Example

©Navid Nikaein 2013 94 Walk Through Example

©Navid Nikaein 2013 95 Walk Through Example

©Navid Nikaein 2013 96 Walk Through Example

©Navid Nikaein 2013 97 Walk Through Example

©Navid Nikaein 2013 98 Walk Through Example

©Navid Nikaein 2013 99 Walk Through Example

©Navid Nikaein 2013 100 Walk Through Example

©Navid Nikaein 2013 101