Mobile Applications and Services

barbarousmonthΚινητά – Ασύρματες Τεχνολογίες

10 Δεκ 2013 (πριν από 3 χρόνια και 7 μήνες)

115 εμφανίσεις

Navid Nikaein

Mobile Communication Department

Mobile Applications and Services

FALL 2010



-

Introduction to
iPhone

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)


Xcode

tools (Free)


iOS

SDK:


Student Program: Free


Individual Program: $99


Enterprise Program: $399


An
iPhone
/iPod Touch/
iPad

(Optional)

©Navid Nikaein 2010

2

iOS

Smart Mobile Devices


iOS

4.0


Multi Touch Display (960x640)


Storage 16
-
32 GB


Processor ARM Apple A4@ 1GHz


Graphics Power VR


Memory 512 MB DRAM


Connectivity


USB 2.0


GSM/GPRS/EDGE/UMTS/HSDPA


Wifi

802.11 b/g/n



BT


Assisted GPS


Camera


Audio Codec


Power 3.7 V


Weight 137g

©Navid Nikaein 2010

3

Primary

Applications

Secondary

Applications

iOS

Features

Supported Features


Multitasking APIs


Background audio


Voice over IP


Background location


Push notifications


Local notifications


Task finishing


Fast app switching


Switching application


Game Center


Unsupported Features


Adobe flash


According to S. Jobs “in
-
secure, buggy, battery
-
intensive, incompatible with
touch
-
screen”


Native
-
HTML5 video


Canvas for 2D graphics


Java


No HTML5 support in Safari


©Navid Nikaein 2010

4

Platform Components


iOS

SDK / Tools


Language


Frameworks


Design Strategies

©Navid Nikaein 2010

5

Platform Component
-

iOS

SDK


5 Tools:


Xcode



Text editor, Debugger & Compiler


Interface Builder


Creates user interface (xml)


Instruments


Optimize the application


Dash Code


Create web applications for Safari


iPhone

Simulator (Code
-
Build
-
Debug)


Dtrace
,
NSZombies
, Guard
Mallloc


Reference

Library

©Navid Nikaein 2010

6

.
xib

.m

.nib

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 2010

7

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 2010

8

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

Platform Component
-

iOS

Design Strategy


Model
-
View
-
Controller (MVC)


Assigns one of the following roll to objects in an application


Defines the way objects communicate with each other


MVC allows reusability and flexibility to your application

©Navid Nikaein 2010

9

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

What to Remember

Before

Progamming



Small Screen


Low resources


Limited RAM


Limited Battery life


Applications should save
execution time


Multi Touch Events


Sandbox


Establish

a Mobile
Mindset


Design


Memory


Responsiveness


Power


Security

©Navid Nikaein 2010

10

iOS

Architecture


iOS

can be viewed as a
set of layers

©Navid Nikaein 2010

11

HW

iOS



Core OS


Low level interface for operating
system (kernel environment and
drivers)


Accelerate Framework


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 2010

12

iOS



Core Service


Fundamental system services for
applications


Address Book Framework


Core Foundation Framework


CFNetwork Framework


Core Data Framework


Core Foundation Framwork


Core Location Framework


Core Media Framework (low
-
level)


Core Telephony Framework


Event Kit Framework


Foundation Framework


Mobile Core Service Framework


Quick Look Framework


Store Kit Framework


System Configuration Framework

Core OS

Core Service

Media

Cocoa Touch

iOS

©Navid Nikaein 2010

13

iOS



Core Service


CF Network Framework


Use BSD sockets


Create encrypted connections using
SSL or TLS


Resolve DNS hosts


Work with HTTP, authenticating
HTTP, and HTTPS servers


Work with FTP servers


Publish, resolve, and browse Bonjour
services


Core Data Framework


SQLite

lib


Manage and edit data


Support for
validaton

and data
consistancy



Support for grouping, filtering, and
organizing data in
memeory



Core Foundation Framework


Collection data types (arrays, sets,
and so on)


Bundles


String management


Date and time management


Raw data block management


Preferences management


URL and stream manipulation


Threads and run loops


Port and socket communication

Core OS

Core Service

Media

Cocoa Touch

iOS

©Navid Nikaein 2010

14


Foundation Framework


Collection data types
(arrays, sets, and so on)


Bundles


String management


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


XML libraries


Libxml2


libxslt

iOS



Media


Technologies for
creating

multimedia

experience



Assets Library Framework (photo)


AV Foundation Framework


Core Audio


Core audio Framework



Audio toolbox Framework


Audio unit Framework


Core Graphic Frameworks


Interface for Quartz 2D


Core

Text

Framework


Core

Video

Framework


Image I/O 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 2010

15

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 2010

16

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


UI kit
framework

Core OS

Core Service

Media

Cocoa Touch

iOS

©Navid Nikaein 2010

17

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 2010

18

Styles of Programming


iPhone

OS defines three basic styles for applications:


Productivity style


Utility style


Immersive style

©Navid Nikaein 2010

19

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 2010

20

Utility Style


Perform a targeted 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 2010

21

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 2010

22

OBJECTIVE
-
C

©Navid Nikaein 2010

23

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 2010

24

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 2010

25

OO Vocabulary


Encapsulation


keep implementation
private and separate from
interface


Polymorphism



different 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 2010

26

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


Dynamic typing


Dynamic linking

©Navid Nikaein 2010

27

Files


.
h



Contains the interface of the objects






.m & .mm


Contains the implementation



@interface Class :
superClass

{


// member definitions

}

// public method definition

@end

@implementation Class

// public & private methods

@end

©Navid Nikaein 2010

28

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 2010

29

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 2010

30

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 2010

31

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

[
NSString

alloc
];

+(
id)alloc
;

©Navid Nikaein 2010

32

Instance Methods


They can only be used on instances of objects


Contact * me;

[me
getFullName
];

@interface Contact

{

}

-
(
NSString

*)
getFullName
;

@end

©Navid Nikaein 2010

33

Member definition


Members of the interface are defined in between the
braces




@interface Contact {


NSString

* name;

}

@end

©Navid Nikaein 2010

34

Member definition


We can add properties for the different members using
the keyword “property”






Property declaration is equivalent to:



@interface Contact {


NSString

* name;

}

@property (retain )
NSString

* name;

@end

-

(
NSString

*)name; // getter

-

(void)
setName
:(
NSString

*)
newName
; //setter

©Navid Nikaein 2010

35

Declare properties


Properties are defined in the interface



They have to be “synthesized” in the implementation


@property (
attributes
) type name;

@implementation Contact

@synthesize name;

@end

©Navid Nikaein 2010

36

Declare properties


The properties can have a coma separated list of
attributes.


The possible attributes are:


getter=
getterName


setter=
setterName


readwrite

/
readonly


assign


retain


copy


nonatomic

©Navid Nikaein 2010

37

Interface Builder


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 2010

38

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 2010

39

Inheritance


Only one inheritance at a time




All the members and public methods are inherited

@interface
MyObject

:
NSObject

{

}

@end

©Navid Nikaein 2010

40

Protocols


Protocols define a series of methods that classes wanting
to conform to it have to define


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 2010

41

@interface
MyObject

:
NSObject
<
MyProtocol
> {

}

@end

Delegates


Not really part of Objective
-
C


Intensively used in the SDK


A delegate is often a protocol


A delegate object is an object that acts on behalf of, or in
coordination with, another object


Example:
UIAccelerometerDelegate

©Navid Nikaein 2010

42

Memory Management


iPhone

has a memory pool


Objects are reference counted


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 2010

43

OBJECTIVE
-
C THROUGH AN
EXAMPLE

©Navid Nikaein 2010

44

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 2010

45

[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 2010

46

[
NSString

stringWithFormat
:[
prefs

format]];

-
(
BOOL
)
writeToFile
:(
NSString
*)path a
tomically
:(
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 2010

47

[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 2010

48

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 2010

49

// string1 will be released automatically

NSString
* string1 = [
NSString

string
];

// must release this when done

NSString
* string2 = [[
NSString

alloc
] init];

[string2
release
];

Designing a Class Interface


Class interface is defined in the
ClassName.h

with instance variables and public
methods










By default a method returns an “id” object, but it’s better to add specific types for
the return values


The implementation is in the
ClassName.m
, and contains the actual code for these
methods


Private methods

©Navid Nikaein 2010

50

#import <Cocoa/
Cocoa.h
>

@interface

Photo :
NSObject

{

NSString
*

caption;

NSString
*

photographer;

}

// instance method getter: leave out the get prefix

-

(
NSString
*) caption;

-

(
NSString
*) photographer;

// instance method setters: no return value

-

(void)
setCaption
: (
NSString
*)input;

-

(void)
setPhotographer
: (
NSString
*)input;

@end


Class implementation


The getter and setter

©Navid Nikaein 2010

51

#import "
Photo.h
"

@implementation

Photo

-

(
NSString
*) caption {

return

caption;

}

-

(
NSString
*) photographer {

return

photographer;

}

-

(void)
setCaption
: (
NSString
*)input {

[caption
autorelease
]; // reference to the
existing object, not using GC,

caption = [input
retain
]; // new input object

}

-

(void)
setPhotographer
: (
NSString
*)input {

[photographer
autorelease
]; // release later

photographer = [input
retain
];

}

@end


Class implementation


Init




Dealloc





The “
dealloc
” method is not called on objects if
garbage collection is enabled, instead, you implement
the
finalize

method.

©Navid Nikaein 2010

52

-

(id)
init

{

if ( self = [
super init
] ) { //
superclass

own’s

init


[self
setCaption
:@"Default Caption"];


[self
setPhotographer
:@"Default Photographer"];

}

return self;

}

-

(void)
dealloc

{

[caption
release
]; //send release to caption instance

[photographer
release
];

[
super
dealloc
]; //
superclass

own’s

cleanup

}

Memory Management 2


Reference counting


Keep track of your references, and the runtime does the actual freeing of
memory







In practice, you create an object for two reasons


To keep it as an instance variable


To use temporarily for single use inside a function


Real work is about managing local references inside a function


Rule: if you create an object with “
alloc
” or “copy”, send it a
“release” or “
autorelease
” message at the end of the function

©Navid Nikaein 2010

53

NSNumber
* value1 = [[
NSNumber

alloc
]
initWithFloat:8.75]; [self
setTotal
:value1];

NSNumber
* value2 = [
NSNumber

numberWithFloat
:14.78];
[self
setTotal
:value2];

// only release value1, not value2


[value1
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 2010

54

NSLog
(@"The current date and time is:
%@
",[
NSDate

date]);

Properties


Properties are a features allowing to
automatically generate
accessors







Implementation of the class







Note:
Accessors

will only be generated if they
don't already exist


It is possible to specify @synthesize for a
property


Then implement your custom getter or setter if
you want


The compiler will fill in whichever method is
missing

©Navid Nikaein 2010

55

#import <Cocoa/
Cocoa.h
>

@interface Photo :
NSObject

{

NSString
* caption;

NSString
* photographer;

}

@property

(retain)
NSString
*
caption
;

@property

(retain)
NSString
*
photographer
;

@end

#import "
Photo.h
"

@implementation Photo

@synthesize

caption;

@synthesize

photographer;

-

(void)
dealloc

{

[caption
release
];

[photographer
release
];

[super
dealloc
];

}

@end

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 2010

56

-

(void)
dealloc

{ *

self
.caption

=
nil
;

self
.photographer

=
nil
;

[super
dealloc
];

}

Categories


Add methods to an existing class or built
-
in objects without
subclassing

it or needing
to know any of the details of how it's implemented


There is no
superclass

declaration, and name of “category” in
paranthesis





Implementation




Usage




Note: Categories cannot add instance variable, but they can override
exisiting

methods in classes


Becarefull
: Category affects all instances of that class throughout the application

©Navid Nikaein 2010

57

#import <Cocoa/
Cocoa.h
>

@interface

NSString

(
Utilities
)

-

(BOOL)
isURL
;

@end

#import "
NSString
-
Utilities.h
"

@implementation

NSString

(
Utilities
)

-

(BOOL)
isURL

{

if ( [self
hasPrefix
:@"http://"] )
return
YES
;

else return
NO
;

}

@end


NSString
* string1 = @"http://pixar.com/";

if ( [string1
isURL
] )
NSLog

(@"string1 is a URL");