Mobile Applications and Services FALL 2013 · Mobile Applications and Services FALL 2013 - iOS...
Transcript of Mobile Applications and Services FALL 2013 · Mobile Applications and Services FALL 2013 - iOS...
Navid Nikaein
Mobile Communication Department
Mobile Applications and Services FALL 2013
- iOS basics
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 C)
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
USB 2.0 GSM/GPRS/EDGE/UMTS/HSDPA/LTE Wifi 802.11 b/g/n BT Assisted GPS
Double Camera: 8 MP & 1.2MP HD Audio/VIDEO Power 3.8 V Weight 112g
©Navid Nikaein 2013 3
Primary Applications
Secondary Applications
Platform Components
iOS SDK / Tools
Language
Frameworks
Design Strategies
©Navid Nikaein 2013 4
Platform Component - iOS SDK
Tools: Xcode
Text editor, Debugger & Compiler
Interface Builder (UI) storyborad Creates user interface (xml)
Instruments (profiler ) Optimize the application
Dash Code Create web applications for Safari
iOS Simulator (Code-Build-Debug) Dtrace, NSZombies, Guard Mallloc
Reference Library
©Navid Nikaein 2013 5
.xib
.m, .h .nib
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 next 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 Smalltalk-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
Platform Component - iOS Frameworks Name Prefixes
Accelerate.framework cblas, vDSP
AddressBook.framework AB
AddressBookUI.framework AB
AssetsLibrary.framework AL
AudioToolbox.framework AU,Audio
AudioUnit.framework AU
AVFoundation.framework AV
CFNetwork.framework CF
CoreAudio.framework Audio
CoreData.framework NS
CoreFoundation.framework CF
CoreGraphics.framework CG
CoreLocation.framework CL
CoreMedia.framework CM
CoreMotion.framework CM
CoreTelephony.framework CT
CoreText.framework CT
CoreVideo.framework CV
EventKit.framework EK
©Navid Nikaein 2013 11
Name Prefixes
EventKitUI.framework EK
ExternalAccessory.framework EA
Foundation.framework NS
GameKit.framework GK
iAd.framework AD
ImageIO.framework CG
IOKit.framework N/A
MapKit.framework MK
MediaPlayer.framework MP
MessageUI.framework MF
MobileCoreServices.framework UT
OpenAL.framework AL
OpenGLES.framework EAGL, GL
QuartzCore.framework CA
QuickLook.framework QL
Security.framework CSSM, Sec
StoreKit.framework SK
SystemConfiguration.framework SC
UIKit.framework UI
iOS Frameworks: New
©Navid Nikaein 2013 12
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
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
©Navid Nikaein 2013 15
Encapsulate, manipulate, and process the data specific to an application
How your model is presented/viewed to the user (UI logic)
knows how to draw itself and can respond to user actions
MVC
All about managing the communication between objects
©Navid Nikaein 2013 16
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
Window: 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
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
iOS Architecture
iOS can be viewed as a set of layers
©Navid Nikaein 2013 28
HW
iOS Features
Cocoa touch UIkit Multitouch gestures Storyborad Document , printing
Networking Services Store Kit (in-app) Push notification Game Kit iAd Core location Map Kit Networking (BSD Socket) Accelerate
©Navid Nikaein 2013 29
Media Graphics Audio Camera & photo lib iPod media lib
Core services iOS simulator Inter-app messaging Messaging In-app SMS Cut, copy, paste Gyro + accelerometer Multitasking Addressbook Compass Accessories Quicklook
iOS – Core OS
Low level interface for operating system (kernel environment and drivers) Accelerate Framework Core Bluetooth External Accessory Framework Security Framework
Lib System Library Threading (POSIX threads) Networking (BSD sockets) File-system access Standard I/O Bonjour and DNS services Locale information Memory allocation Math Computation
Core OS
Core Service
Media
Cocoa Touch
iOS
©Navid Nikaein 2013 30
iOS – Core Service
Fundamental system services for applications Account Framework Address Book Framework Core Foundation Framework CFNetwork Framework Core Data Framework Core Location Framework Core Media Framework (low-level) Core Telephony Framework Event Kit Framework Foundation Framework Mobile Core Service Framework Newsstand Kit Framework Quick Look Framework Store Kit Framework System Configuration Framework
Core OS
Core Service
Media
Cocoa Touch
iOS
©Navid Nikaein 2013 31
iOS – Core Service
CF Network Framework BSD sockets Encrypted
connections(SSL / TLS ) Resolve DNS hosts Work with HTTP,
authenticating HTTP, HTTPS , FTP servers
Publish, resolve, and browse
Bonjour services
Core Data Framework SQLite lib Manage and edit data Validation and data
consistency Support for grouping,
filtering, and organizing data in memory
Core OS
Core Service
Media
Cocoa Touch
iOS
©Navid Nikaein 2013 32
Foundation Framework Collection data types Bundles Date and time
management Raw data block
management Preferences
management URL and stream
manipulation Threads and run loops Bonjour Communication port
management Internationalization Regular expression
matching Cache support
iOS – Media
Technologies for creating multimedia experience Assets Library Framework (retrieving photo/video) AV Foundation Framework Core Audio
Core audio Framework Audio toolbox Framework Audio unit Framework
Core Graphic Frameworks (Quartz 2D) Core Image framework Core MIDI framework Core Text Framework Core Video Framework Image I/O Framework GL Kit framework Media Player Framework Open AL Framework OpenGL ES (3D audio for game) Quartz Core Framework
Core OS
Core Service
Media
Cocoa Touch
iOS
©Navid Nikaein 2013 33
iOS – Media
AV Foundation Framework Media asset management Media editing Movie capture Movie playback Track management Metadata management for media Stereophonic panning Synchronization between sounds An Objective-C interface for
determining details about sound files, such as the data format, sample rate, and number of channels
Core OS
Core Service
Media
Cocoa Touch
iOS
©Navid Nikaein 2013 34
iOS – Cocoa Touch
Basic tools and infrastructure to implement graphical, event-driven applications in iOS Addressbook UI framework Addressbook framework Event Kit UI framework Game Kit framework iAd framework Map kit framework Message UI framework UIkit framework Twitter framework
Core OS
Core Service
Media
Cocoa Touch
iOS
©Navid Nikaein 2013 35
iOS – Cocoa Touch
UI kit framework Application management User interface management Graphics and windowing support Multitasking support Support for handling touch and motion-based events Representing the standard system views and controls Support for text and web content Cut, copy, and paste support Support for animating user-interface content PDF creation Support for using custom input/text views that behave
like the system keyboard
Other supports Accelerometer data 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
Core OS
Core Service
Media
Cocoa Touch
iOS
©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
OO Vocabulary
Class Defines the grouping of data and code Create instances
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
Object
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 Restrict access to some of the
object’s components
Polymorphism Different vars / functions
/objects, same interface
Inheritance Hierarchical organization,
share code, customize or extend behaviors
Specific behavior
Generic behavior
Memory management NSObject
UIControl
UIBotton UITextField
Superclass
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
.m & .mm – Contains the implementation .m: c and objective-C .mm: c++, c, and objective-C
@interface Class : superClass {
// member definitions
}
// public method definition
@end
@implementation Class
// public & private methods
@end
©Navid Nikaein 2013 46
A Quick Comparison
Java or C++ Syntax
Person* person = new Person();
int age = person.age();
person.setWeight(1.8);
person.setXandY(20.0f,1.0f);
delete person;
Objective-C Syntax
Person* person =[[Person alloc] init];
int age = [person age ];
[person setWeight:1.8];
[person setX:20.0f andY:1.0f];
[person release];
©Navid Nikaein 2013 47
A Quick Comparison C++ Syntax (.h)
Typedef struct { Float x; Float y;
} Point; Class Car {
Point position; float velocity; Int model; Char* vin;
Public: static const int viper =1; Car (int m); ~car(); Point position(); Void setPosition (Point P); };
Objective-C Syntax (.h) Typedef struct {
Float x; Float y;
} Point; @interface Car : NSObject {
Point position; float velocity; Int model; NSString* vin;
} + (int) viper; -(id) initWithModel: (int)m; -(void) dealloc; -(Point) position; - (void) setPosition:(Point)p; @end
©Navid Nikaein 2013 48
A Quick Comparison C++ Syntax (.cpp)
#include « Car.h»
Car::Car(int m) {
position.x=0.0f;
position.y=0.0f;
model = m;
Vin= « 295ZHGO45308 »
}
Car::~Car(){}
Point position () {return position};
Void setPosition (Point P) {
position =p;
}
Objective-C Syntax (.m) #import « Car.h» @implementation Car + (int) viper {return1}; - (id) initWithModel:(int)m { position.x=0.0f; position.y=0.0f; model = m; Vin= @« 295ZHGO45308 » } - (void) dealloc {[super dealloc]; } - (Point) position {return position}; - (void) setPosition:(Point)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
Weak typing is when we use “id” as the type of the variable “id” can be anything
MyClass * class;
NSObject * theObject;
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(:)
The default return and argument type for methods is id
- (void)setWidth:(int)newWidth height:(int)newHeight
©Navid Nikaein 2013 51
Calling methods
Two words with in a set of brackets, the object or class identifier and the method name
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
[identifier method]
©Navid Nikaein 2013 52
Class Methods
Equivalent to the “static” methods in C
The “alloc” method is an example:
To call the method we need to use a class
Automatic Reference counting (ARC)
[NSString alloc];
+(id)alloc;
©Navid Nikaein 2013 53
Instance Methods
They can only be used on instances of objects
Contact * me;
[me getFullName];
@interface Contact : superClass
{
}
-(NSString *)getFullName;
@end
©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
Property declaration is equivalent to:
@interface Contact {
NSString * name;
}
@property (retain )NSString * name;
@end
- (NSString *)name; // getter
- (void)setName:(NSString *)newName; //setter
©Navid Nikaein 2013 56
Declare properties
Properties are defined in the interface
They have to be “synthesized” in the implementation to be generated according to the property declaration
@property (attributes) type name;
@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
Methods are connected using the keyword “IBAction” as return type
IBOutlet id button;
-(IBAction)buttonPressed;
©Navid Nikaein 2013 59
Interface Builder
Interface Builder recognize actions using three prototypes:
We can connect objects and events from Interface Builder to the members and methods that we declare in Xcode
-(IBAction)actionName;
-(IBAction)actionName:(id)sender;
-(IBAction)actionName:(id)sender withEvent:(UIEvent *)event;
©Navid Nikaein 2013 60
Inheritance
Only one inheritance at a time
All the members and public methods are inherited
@interface MyObject : NSObject {
}
@end
©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 We use < > brackets to give a comma separated list of protocols
@protocol MyProtocol - (void) defineToBeConform; @end
©Navid Nikaein 2013 62
@interface MyObject : NSObject<MyProtocol> { } @end
Delegates
Not really part of Objective-C
Intensively used in the iOS (cocoa 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”
Note: the String in the example has to have the property attribute “retain” or the string will be destroyed by the pool.
NSString * aString = [[NSString alloc] init];
self.theString = aString;
[aString release];
@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
Method can return a value
Call method on classes, which is how you create an object.
id type means that the myObject variable can refer to any object id type is predefined as a pointer type
©Navid Nikaein 2013 66
[object method]; [object methodWithInput:input];
output = [object methodWithOutput]; output = [object methodWithInputAndOutput:input];
id myObject = [NSString string]; NSString* myString = [NSString string];
Calling Methods
Nested message
Multi-input methods Method name is writeToFile:atomically: which is splited up
into several segments
©Navid Nikaein 2013 67
[NSString stringWithFormat:[prefs format]];
-(BOOL)writeToFile:(NSString*)path atomically:(BOOL)useAuxiliaryFile; BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];
Accessors
Use accessors to get and set values, as all instance variables are private by default Setter Getter [] 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
©Navid Nikaein 2013 68
[photo setCaption:@"Day at the Beach"]; output = [photo caption];
photo.caption = @"Day at the Beach"; output = photo.caption;
Creating Objects
Automatic style
Manual style with nested methods Detail of init is unknown as a client of the class
Different version of init
©Navid Nikaein 2013 69
NSString* myString = [NSString string];
NSString* myString = [[NSString alloc] init];
NSNumber* value = [[NSNumber alloc] initWithFloat:1.0];
Basic Memory Management
Garbage collector
Manual MM
©Navid Nikaein 2013 70
// string1 will be released automatically NSString* string1 = [NSString string];
// must release this when done NSString* string2 = [[NSString alloc] init]; [string2 release];
Logging
Log in console
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
NSLog(@"The current date and time is:%@",[NSDate date]);
Calling Method on Nil
“nil” Object == Null Pointer in C
You call methods on “nil” without crashing or exceptions
Example: improving “dealloc” method
There's no chance of the variable pointing at random data where an object used to be
©Navid Nikaein 2013 72
- (void) dealloc { * self.caption = nil; self.photographer = nil; [super dealloc]; }