SlideShare ist ein Scribd-Unternehmen logo
1 von 31
iPhone project
  Wireless Network

   Silvio Daminato
  February 28, 2011
Project: Simon says the color

• Kids   game: “Strega comanda colore” ported to iPhone
  • iPhone    asks for a color
  • player   takes a picture with that color in the center
• Simple    augmented reality
• File   handling
• Bluetooth

• Upload     of top scores
Single player

• Three    game modes

  • Practice

  • Time    attack

  • Best   out of 5

• Color    randomly chosen between 8 colors

• Player   has to take the picture within a timeout
Multiplayer

•A   player is the Witch

  • He/she   choose the color

  • He/she   sets the difficulty (timeout)

• Up   to six players

• Communication     over bluetooth

• Client-Server   architecture
Developing for iPhone


• http://developer.apple.com/
  • Sign  up as developer
  • Download of development and debugging tools
  • Manage profiles, certificates, devices
• http://developer.apple.com/programs/ios/university/
  • It allows to install and test apps on a iOS device
Tools

• Xcode

• Interface   Builder

• iOS   simulator

• Instruments

• ...
Objective C

• Object   oriented

• C-based

• Smalltalk   style: based on messages exchange

                C++                             Obj-C
A* a = new A;                     A* a = [[A alloc] init];
a -> doSomething(argument);       [a doSomething: argument];
delete a;                         [a release];
Delegation

• Widely   used in Cocoa Touch

• An object is delegated by the application to handle some kind
 of events

• Examples: UITableViewDelegate, UIAlertViewDelegate

•A delegate object has to implement specific methods with
 specic signatures
Delegation - example
    @interface MyViewController : UIViewController <UITableViewDelegate> {


    < MyViewController declarations >

}




@implementation ServerController
...

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

   < returns the number of rows in the section >
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

   < sets up and returns the cell >
}
...
@end
Using the camera

• Class   UIImagePickerController


  • Source    type UIImagePickerControllerSourceTypeCamera

• Delegate    protocol UIImagePickerControllerDelegate

  • Method     imagePickerController:didFinishPickingMediaWithInfo:   returns
   the image

  • Method     imagePickerControllerDidCancel:   is called when user
   cancels
Augmented reality



• Create   an UIView object or a UIView subclass object

• Assign   that object to cameraOverlayView property of the
 UIImagePickerController
Augmented reality



• Create   an UIView object or a UIView subclass object

• Assign   that object to cameraOverlayView property of the
 UIImagePickerController




                              That’s all.
Camera and augmented reality -
          example
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.delegate = self;
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
ipc.showsCameraControls = NO;
ipc.navigationBarHidden = YES;
ipc.wantsFullScreenLayout = YES;

OverlayView *overlay = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
ipc.cameraOverlayView = overlay;

[self presentModalViewController:ipc animated:YES];
Camera and augmented reality -
          example
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.delegate = self;
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
ipc.showsCameraControls = NO;
ipc.navigationBarHidden = YES;
ipc.wantsFullScreenLayout = YES;

OverlayView *overlay = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
ipc.cameraOverlayView = overlay;

[self presentModalViewController:ipc animated:YES];
Text le handling

• .plist   format

  • XML      with a specific format

  • Handling      is simple

• Set   up data, generate path of file, write to file

• Generate       path, read file

• Data     as NSDictionary, NSArray, NSString, ...
Text le handling - example
NSString *rstString = @"Voglio salvare questa stringa";
NSString *secondString = @"Voglio salvare anche questa!";
NSMutableArray *plistFileContent = [[NSMutableArray alloc]
                     initWithObjects:rstString, secondString, nil];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                    NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myle = [documentsDirectory
                    stringByAppendingPathComponent:@"myle.plist"];

[plistFileContent writeToFile:myle atomically:YES];



NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                       NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myle = [documentsDirectory
                       stringByAppendingPathComponent:@"myle.plist"];

NSArray *plistFileContent = [[NSArray alloc] initWithContentsOfFile:myle];
Peer-to-peer over Bluetooth

• Allows   to exchange information between two or more
 devices

• Ad-hoc   network between peers

• Communication   is through sessions (Objects that handle
 events related to it)

• Delegate   protocol: GKSessionDelegate

• Data   format is free
Peers
• Peers   are identified by peerID

• Every   peer has a state
 •   GKPeerStateAvailable
 •   GKPeerStateUnavailable
 •   GKPeerStateConnected
 •   GKPeerStateDisconnected
 •   GKPeerStateConnecting


• Method    session:peer:didChangeState:   called when a peer changes
 state
Discovering peers

• Every   session implements its specific service

•A   session looks for other peer depending on its Session Mode

 • Server
 • Client
 • Peer

• Toestablish a connection there must be at least a server that
 advertise its service and a client looking for it
Implementing a Server
• Initialize   the session: initWithSessionID:displayName:sessionMode:
• Session      mode GKSessionModeServer or GKSessionModePeer
• Set   property available = YES to advertise the service
• The   service has its own Id
• Method       session:didReceiveConnectionRequestFromPeer:   notifies a
  connection request
• Server   decides whether to accept the request or not
• When     the session is created session:peer:didChangeState: method is
  called
Implementing a Server - example
- (void) initSession {
  
   GKSession *session = [[GKSession alloc] initWithSessionID:@"Servizio"
                                displayName:@"Server"
                                sessionMode:GKSessionModeServer];
  
   session.delegate = self;
  
   [session setDataReceiveHandler: self withContext:nil];
  
   session.available = YES;
}

- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {
  
   if (![session isAvailable]) {
  
   
     [session denyConnectionFromPeer:peerID];
  
   } else {
  
   
     session.available = NO;
  
   
     if (connections_count == max_connections) {
  
   
     
    [session denyConnectionFromPeer: peerID];
  
   
     } else {
  
   
     
    [session acceptConnectionFromPeer: peerID];
  
   
     
    connections_count ++;
  
   
     }
  
   
     session.available = YES;
  
   }
}
Implementing a Server - example


- (void) session:(GKSession *)session peer:(NSString *)peerID didChangeState:
(GKPeerConnectionState)state {

        switch (state) {
      case GKPeerStateConnected:

        
    
     NSLog(@"Peer %@ connected!", peerID);

        
    
     connections_count ++;

        
    
     break;
      case GKPeerStateDisconnected:

        
    
     NSLog(@"Peer %@ disconnected!", peerID);

        
    
     connections_count --;

        
    
     break;
   }
}
Connecting to a service
• Initialize   the session: initWithSessionID:displayName:sessionMode:
• Session      mode GKSessionModeClient or GKSessionModePeer
• Set   property available = YES to look for the service
• Only   service with the same sessionID are found
• Method       session:peer:didChangeState:   called when a server has been
  found
• Method       connectToPeer:withTimeout:   to request connection
• Method       session:peer:didChangeState:   called when the session has
  been created
Connecting to a service -
                  example
- (GKSession *) initSession {
  
  GKSession *session = [[GKSession alloc] initWithSessionID:@"Servizio"
                               displayName:@"Client"
                               sessionMode:GKSessionModeClient];
  
  session.delegate = self;
  
  [session setDataReceiveHandler: self withContext:nil];
  
  session.available = YES;
  
  return session;
}

- (void) session:(GKSession *)session peer:(NSString *)peerID didChangeState:
(GKPeerConnectionState)state {

        switch (state) {
           case GKPeerStateAvailable:

        
    
     NSLog(@"Trovato servizio!");

        
    
     [session connectToPeer:peerID withTimeout:5.0];

        
    
     break;
           case GKPeerStateConnected:

        
    
     NSLog(@"Connessione avvenuta!");

        
    
     session.available = NO;

        
    
     break;
           case GKPeerStateDisconnected:

        
    
     NSLog(@"Disconnesso");

        
    
     break;
}
Exchanging data

• Connected   peers can exchange data

• Method   sendDataToAllPeers:WithDataMode:error:   sends to all peers

• Method   sendData:toPeers:WithDataMode:error:   sends to some peers

• Dataformat is not fixed, but they have to be encapsulated in
 an NSData object
Exchanging data - 2
• Two   alternative dataModes:
 •   GKSendDataReliable

     • Datais retransmitted if it doesn’t reach destination
     • Messages are received in the same order they were sent
 •   GKSendDataUnreliable

     • Data   is sent only once
• Method   receiveData:fromPeer:inSession:context:   to receive data
• Method   setDataReceiveHandler:withContext:   sets the object that
 handles received data
Exchanging data - example
NSString *chosenColor = @"yellow";
NSString *level = @"Easy";

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                    chosenColor, @"Color", level, @"Level", nil];
 
  
   
    
    
     
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:dict forKey:@"Dictionary"];
[archiver nishEncoding];

[session sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil];



- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void
*)context {

        NSDictionary *gameInfo;

        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

        gameInfo = [unarchiver decodeObjectForKey:@"Dictionary"];

        [unarchiver nishDecoding];


        NSString * response = [gameInfo objectForKey:@"Response"];

        [self checkResponse:response peerID:peer];
}
Disconnecting peers

• End   a session: disconnectFromAllPeers

• Disconnect    a peer: disconnectPeerFromAllPeers:

• Ifa peer is non responsive for a period of time
  (disconnectionTimeout) it is automatically disconnected

• Method    session:peer:didChangeState:   called when a peer
  disconnects
Peer picker

• It   is possible to create your own GUI

• Object                   provides the interface to discover
            GKPeerPickerController
  and connect to other peers

• Delegate    protocol GKPeerPickerControllerDelegate
Help and documentation

• Xcode   menu bar ➙ Help ➙ Developer documentation

• http://developer.apple.com/library/ios/navigation/

• http://www.google.com/

  • http://stackoverflow.com/

  • http://www.iphonedevsdk.com/forum/
References


• “Simon says the color”, S. Daminato, A. Giavatto, Progetto di
 Reti Wireless 2009/2010

• http://developer.apple.com/library/ios/navigation/

• “Game    Kit Programming Guide”, Apple Inc.

Weitere ähnliche Inhalte

Was ist angesagt?

«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​
FDConf
 
09 Application Design
09 Application Design09 Application Design
09 Application Design
Ranjan Kumar
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
IndicThreads
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
Justin Cataldo
 
Nio
NioNio
Nio
nextlib
 

Was ist angesagt? (20)

The Future of the Web
The Future of the WebThe Future of the Web
The Future of the Web
 
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
GradleFX
GradleFXGradleFX
GradleFX
 
Intro to ColdBox MVC at Japan CFUG
Intro to ColdBox MVC at Japan CFUGIntro to ColdBox MVC at Japan CFUG
Intro to ColdBox MVC at Japan CFUG
 
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
 
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
Orion Context Broker NGSI-v2 Overview for Developers That Already Know NGSI-v...
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​
 
09 Application Design
09 Application Design09 Application Design
09 Application Design
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jquery
 
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark BrocatoSenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...
 
Even faster django
Even faster djangoEven faster django
Even faster django
 
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD MessagesEWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
 
Nio
NioNio
Nio
 

Andere mochten auch

Star chart data
Star chart dataStar chart data
Star chart data
thompsonw
 
Final Evaluation
Final Evaluation Final Evaluation
Final Evaluation
ellieyoungman
 
Photos planning production
 Photos planning production Photos planning production
Photos planning production
ellieyoungman
 
Personal Learning
Personal Learning Personal Learning
Personal Learning
ellieyoungman
 
Texas star chart
Texas star chartTexas star chart
Texas star chart
annmariedev
 
Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...
Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...
Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...
Salvatore [Sasa'] Barresi
 
Double page spreads
Double page spreadsDouble page spreads
Double page spreads
ellieyoungman
 
1 s tarchart
1 s tarchart1 s tarchart
1 s tarchart
ccoleman3
 
Barresi salvatore, amore e senso per la vita 2010
Barresi salvatore, amore e senso per la vita 2010Barresi salvatore, amore e senso per la vita 2010
Barresi salvatore, amore e senso per la vita 2010
Salvatore [Sasa'] Barresi
 
Technlogoy Action Plan
Technlogoy Action PlanTechnlogoy Action Plan
Technlogoy Action Plan
Rubberman
 
第十章 休閒生活
第十章 休閒生活第十章 休閒生活
第十章 休閒生活
Fuhan Hu
 
Literatura seculos-escuros-1213883452645977-8
Literatura seculos-escuros-1213883452645977-8Literatura seculos-escuros-1213883452645977-8
Literatura seculos-escuros-1213883452645977-8
agarridog
 
Nya verktyg och kommunikation
Nya verktyg och kommunikationNya verktyg och kommunikation
Nya verktyg och kommunikation
Anders EklĂśf
 
Star ChartPresentation
Star ChartPresentationStar ChartPresentation
Star ChartPresentation
Rubberman
 
生涯規劃 養一
生涯規劃 養一生涯規劃 養一
生涯規劃 養一
Fuhan Hu
 

Andere mochten auch (20)

Star chart data
Star chart dataStar chart data
Star chart data
 
Final Evaluation
Final Evaluation Final Evaluation
Final Evaluation
 
Photos planning production
 Photos planning production Photos planning production
Photos planning production
 
Personal Learning
Personal Learning Personal Learning
Personal Learning
 
Texas star chart
Texas star chartTexas star chart
Texas star chart
 
Frinton on sea 2011 sistema educativo
Frinton on sea 2011 sistema educativoFrinton on sea 2011 sistema educativo
Frinton on sea 2011 sistema educativo
 
Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...
Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...
Con l'aiuto della madonna di capocolonna, crotone rialzati! (vers.02) s. barr...
 
Double page spreads
Double page spreadsDouble page spreads
Double page spreads
 
1 s tarchart
1 s tarchart1 s tarchart
1 s tarchart
 
Configuring policies in v c ops
Configuring policies in v c opsConfiguring policies in v c ops
Configuring policies in v c ops
 
Consciousness: The Brain Is Aware
Consciousness: The Brain Is AwareConsciousness: The Brain Is Aware
Consciousness: The Brain Is Aware
 
Route object creation white paper
Route object creation white paper Route object creation white paper
Route object creation white paper
 
Barresi salvatore, amore e senso per la vita 2010
Barresi salvatore, amore e senso per la vita 2010Barresi salvatore, amore e senso per la vita 2010
Barresi salvatore, amore e senso per la vita 2010
 
Texas campus s ta r chart summary
Texas campus s ta r chart summaryTexas campus s ta r chart summary
Texas campus s ta r chart summary
 
Technlogoy Action Plan
Technlogoy Action PlanTechnlogoy Action Plan
Technlogoy Action Plan
 
第十章 休閒生活
第十章 休閒生活第十章 休閒生活
第十章 休閒生活
 
Literatura seculos-escuros-1213883452645977-8
Literatura seculos-escuros-1213883452645977-8Literatura seculos-escuros-1213883452645977-8
Literatura seculos-escuros-1213883452645977-8
 
Nya verktyg och kommunikation
Nya verktyg och kommunikationNya verktyg och kommunikation
Nya verktyg och kommunikation
 
Star ChartPresentation
Star ChartPresentationStar ChartPresentation
Star ChartPresentation
 
生涯規劃 養一
生涯規劃 養一生涯規劃 養一
生涯規劃 養一
 

Ähnlich wie iPhone project - Wireless networks seminar

MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS Topics
Petr Dvorak
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
Petr Dvorak
 
A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...
A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...
A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...
DataLeader.io
 
Implementing New Web
Implementing New WebImplementing New Web
Implementing New Web
Julian Viereck
 

Ähnlich wie iPhone project - Wireless networks seminar (20)

Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS Topics
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows Phone
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
 
Introduction to VIPER Architecture
Introduction to VIPER ArchitectureIntroduction to VIPER Architecture
Introduction to VIPER Architecture
 
A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...
A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...
A Microsoft Silverlight User Group Starter Kit Made Available for Everyone to...
 
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James WilliamsSF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris Kellogg
 
The MEAN stack
The MEAN stack The MEAN stack
The MEAN stack
 
Multipeer Connectivity
Multipeer ConnectivityMultipeer Connectivity
Multipeer Connectivity
 
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
Cassandra Summit 2014: Highly Scalable Web Application in the Cloud with Cass...
 
Converting Your Mobile App to the Mobile Cloud
Converting Your Mobile App to the Mobile CloudConverting Your Mobile App to the Mobile Cloud
Converting Your Mobile App to the Mobile Cloud
 
Implementing New Web
Implementing New WebImplementing New Web
Implementing New Web
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIs
 
Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013
Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013
Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
 

KĂźrzlich hochgeladen

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

KĂźrzlich hochgeladen (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

iPhone project - Wireless networks seminar

  • 1. iPhone project Wireless Network Silvio Daminato February 28, 2011
  • 2. Project: Simon says the color • Kids game: “Strega comanda colore” ported to iPhone • iPhone asks for a color • player takes a picture with that color in the center • Simple augmented reality • File handling • Bluetooth • Upload of top scores
  • 3. Single player • Three game modes • Practice • Time attack • Best out of 5 • Color randomly chosen between 8 colors • Player has to take the picture within a timeout
  • 4. Multiplayer •A player is the Witch • He/she choose the color • He/she sets the difculty (timeout) • Up to six players • Communication over bluetooth • Client-Server architecture
  • 5. Developing for iPhone • http://developer.apple.com/ • Sign up as developer • Download of development and debugging tools • Manage proles, certicates, devices • http://developer.apple.com/programs/ios/university/ • It allows to install and test apps on a iOS device
  • 6. Tools • Xcode • Interface Builder • iOS simulator • Instruments • ...
  • 7. Objective C • Object oriented • C-based • Smalltalk style: based on messages exchange C++ Obj-C A* a = new A; A* a = [[A alloc] init]; a -> doSomething(argument); [a doSomething: argument]; delete a; [a release];
  • 8. Delegation • Widely used in Cocoa Touch • An object is delegated by the application to handle some kind of events • Examples: UITableViewDelegate, UIAlertViewDelegate •A delegate object has to implement specic methods with specic signatures
  • 9. Delegation - example @interface MyViewController : UIViewController <UITableViewDelegate> { < MyViewController declarations > } @implementation ServerController ... - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { < returns the number of rows in the section > } - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { < sets up and returns the cell > } ... @end
  • 10. Using the camera • Class UIImagePickerController • Source type UIImagePickerControllerSourceTypeCamera • Delegate protocol UIImagePickerControllerDelegate • Method imagePickerController:didFinishPickingMediaWithInfo: returns the image • Method imagePickerControllerDidCancel: is called when user cancels
  • 11. Augmented reality • Create an UIView object or a UIView subclass object • Assign that object to cameraOverlayView property of the UIImagePickerController
  • 12. Augmented reality • Create an UIView object or a UIView subclass object • Assign that object to cameraOverlayView property of the UIImagePickerController That’s all.
  • 13. Camera and augmented reality - example UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; ipc.delegate = self; ipc.sourceType = UIImagePickerControllerSourceTypeCamera; ipc.showsCameraControls = NO; ipc.navigationBarHidden = YES; ipc.wantsFullScreenLayout = YES; OverlayView *overlay = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; ipc.cameraOverlayView = overlay; [self presentModalViewController:ipc animated:YES];
  • 14. Camera and augmented reality - example UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; ipc.delegate = self; ipc.sourceType = UIImagePickerControllerSourceTypeCamera; ipc.showsCameraControls = NO; ipc.navigationBarHidden = YES; ipc.wantsFullScreenLayout = YES; OverlayView *overlay = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; ipc.cameraOverlayView = overlay; [self presentModalViewController:ipc animated:YES];
  • 15. Text le handling • .plist format • XML with a specic format • Handling is simple • Set up data, generate path of le, write to le • Generate path, read le • Data as NSDictionary, NSArray, NSString, ...
  • 16. Text le handling - example NSString *rstString = @"Voglio salvare questa stringa"; NSString *secondString = @"Voglio salvare anche questa!"; NSMutableArray *plistFileContent = [[NSMutableArray alloc] initWithObjects:rstString, secondString, nil]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *myle = [documentsDirectory stringByAppendingPathComponent:@"myle.plist"]; [plistFileContent writeToFile:myle atomically:YES]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *myle = [documentsDirectory stringByAppendingPathComponent:@"myle.plist"]; NSArray *plistFileContent = [[NSArray alloc] initWithContentsOfFile:myle];
  • 17. Peer-to-peer over Bluetooth • Allows to exchange information between two or more devices • Ad-hoc network between peers • Communication is through sessions (Objects that handle events related to it) • Delegate protocol: GKSessionDelegate • Data format is free
  • 18. Peers • Peers are identied by peerID • Every peer has a state • GKPeerStateAvailable • GKPeerStateUnavailable • GKPeerStateConnected • GKPeerStateDisconnected • GKPeerStateConnecting • Method session:peer:didChangeState: called when a peer changes state
  • 19. Discovering peers • Every session implements its specic service •A session looks for other peer depending on its Session Mode • Server • Client • Peer • Toestablish a connection there must be at least a server that advertise its service and a client looking for it
  • 20. Implementing a Server • Initialize the session: initWithSessionID:displayName:sessionMode: • Session mode GKSessionModeServer or GKSessionModePeer • Set property available = YES to advertise the service • The service has its own Id • Method session:didReceiveConnectionRequestFromPeer: noties a connection request • Server decides whether to accept the request or not • When the session is created session:peer:didChangeState: method is called
  • 21. Implementing a Server - example - (void) initSession { GKSession *session = [[GKSession alloc] initWithSessionID:@"Servizio" displayName:@"Server" sessionMode:GKSessionModeServer]; session.delegate = self; [session setDataReceiveHandler: self withContext:nil]; session.available = YES; } - (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID { if (![session isAvailable]) { [session denyConnectionFromPeer:peerID]; } else { session.available = NO; if (connections_count == max_connections) { [session denyConnectionFromPeer: peerID]; } else { [session acceptConnectionFromPeer: peerID]; connections_count ++; } session.available = YES; } }
  • 22. Implementing a Server - example - (void) session:(GKSession *)session peer:(NSString *)peerID didChangeState: (GKPeerConnectionState)state { switch (state) { case GKPeerStateConnected: NSLog(@"Peer %@ connected!", peerID); connections_count ++; break; case GKPeerStateDisconnected: NSLog(@"Peer %@ disconnected!", peerID); connections_count --; break; } }
  • 23. Connecting to a service • Initialize the session: initWithSessionID:displayName:sessionMode: • Session mode GKSessionModeClient or GKSessionModePeer • Set property available = YES to look for the service • Only service with the same sessionID are found • Method session:peer:didChangeState: called when a server has been found • Method connectToPeer:withTimeout: to request connection • Method session:peer:didChangeState: called when the session has been created
  • 24. Connecting to a service - example - (GKSession *) initSession { GKSession *session = [[GKSession alloc] initWithSessionID:@"Servizio" displayName:@"Client" sessionMode:GKSessionModeClient]; session.delegate = self; [session setDataReceiveHandler: self withContext:nil]; session.available = YES; return session; } - (void) session:(GKSession *)session peer:(NSString *)peerID didChangeState: (GKPeerConnectionState)state { switch (state) { case GKPeerStateAvailable: NSLog(@"Trovato servizio!"); [session connectToPeer:peerID withTimeout:5.0]; break; case GKPeerStateConnected: NSLog(@"Connessione avvenuta!"); session.available = NO; break; case GKPeerStateDisconnected: NSLog(@"Disconnesso"); break; }
  • 25. Exchanging data • Connected peers can exchange data • Method sendDataToAllPeers:WithDataMode:error: sends to all peers • Method sendData:toPeers:WithDataMode:error: sends to some peers • Dataformat is not xed, but they have to be encapsulated in an NSData object
  • 26. Exchanging data - 2 • Two alternative dataModes: • GKSendDataReliable • Datais retransmitted if it doesn’t reach destination • Messages are received in the same order they were sent • GKSendDataUnreliable • Data is sent only once • Method receiveData:fromPeer:inSession:context: to receive data • Method setDataReceiveHandler:withContext: sets the object that handles received data
  • 27. Exchanging data - example NSString *chosenColor = @"yellow"; NSString *level = @"Easy"; NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: chosenColor, @"Color", level, @"Level", nil]; NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver encodeObject:dict forKey:@"Dictionary"]; [archiver nishEncoding]; [session sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil]; - (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context { NSDictionary *gameInfo; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; gameInfo = [unarchiver decodeObjectForKey:@"Dictionary"]; [unarchiver nishDecoding]; NSString * response = [gameInfo objectForKey:@"Response"]; [self checkResponse:response peerID:peer]; }
  • 28. Disconnecting peers • End a session: disconnectFromAllPeers • Disconnect a peer: disconnectPeerFromAllPeers: • Ifa peer is non responsive for a period of time (disconnectionTimeout) it is automatically disconnected • Method session:peer:didChangeState: called when a peer disconnects
  • 29. Peer picker • It is possible to create your own GUI • Object provides the interface to discover GKPeerPickerController and connect to other peers • Delegate protocol GKPeerPickerControllerDelegate
  • 30. Help and documentation • Xcode menu bar ➙ Help ➙ Developer documentation • http://developer.apple.com/library/ios/navigation/ • http://www.google.com/ • http://stackoverflow.com/ • http://www.iphonedevsdk.com/forum/
  • 31. References • “Simon says the color”, S. Daminato, A. Giavatto, Progetto di Reti Wireless 2009/2010 • http://developer.apple.com/library/ios/navigation/ • “Game Kit Programming Guide”, Apple Inc.

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n