SlideShare a Scribd company logo
1 of 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
 specific 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 file 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 file handling - example
NSString *firstString = @"Voglio salvare questa stringa";
NSString *secondString = @"Voglio salvare anche questa!";
NSMutableArray *plistFileContent = [[NSMutableArray alloc]
                     initWithObjects:firstString, secondString, nil];

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

[plistFileContent writeToFile:myfile atomically:YES];



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

NSArray *plistFileContent = [[NSArray alloc] initWithContentsOfFile:myfile];
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 finishEncoding];

[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 finishDecoding];


        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.

More Related Content

What's hot

The Future of the Web
The Future of the WebThe Future of the Web
The Future of the WebRay Nicholus
 
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...Fermin Galan
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
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...Fermin Galan
 
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...Luciano Mammino
 
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 2017Codemotion
 
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...Fermin Galan
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​FDConf
 
09 Application Design
09 Application Design09 Application Design
09 Application DesignRanjan 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 FrameworkIndicThreads
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jqueryUmar Ali
 
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 BrocatoSencha
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
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...Codemotion
 
Even faster django
Even faster djangoEven faster django
Even faster djangoGage Tseng
 
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 MessagesRob Tweed
 

What's hot (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
 

Viewers also liked

Star chart data
Star chart dataStar chart data
Star chart datathompsonw
 
Photos planning production
 Photos planning production Photos planning production
Photos planning productionellieyoungman
 
Texas star chart
Texas star chartTexas star chart
Texas star chartannmariedev
 
Frinton on sea 2011 sistema educativo
Frinton on sea 2011 sistema educativoFrinton on sea 2011 sistema educativo
Frinton on sea 2011 sistema educativofrintonarcos
 
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
 
1 s tarchart
1 s tarchart1 s tarchart
1 s tarchartccoleman3
 
Configuring policies in v c ops
Configuring policies in v c opsConfiguring policies in v c ops
Configuring policies in v c opsSunny Dua
 
Route object creation white paper
Route object creation white paper Route object creation white paper
Route object creation white paper peterehiwe
 
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 2010Salvatore [Sasa'] Barresi
 
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 summarylctipton
 
Technlogoy Action Plan
Technlogoy Action PlanTechnlogoy Action Plan
Technlogoy Action PlanRubberman
 
第十章 休閒生活
第十章 休閒生活第十章 休閒生活
第十章 休閒生活Fuhan Hu
 
Literatura seculos-escuros-1213883452645977-8
Literatura seculos-escuros-1213883452645977-8Literatura seculos-escuros-1213883452645977-8
Literatura seculos-escuros-1213883452645977-8agarridog
 
Nya verktyg och kommunikation
Nya verktyg och kommunikationNya verktyg och kommunikation
Nya verktyg och kommunikationAnders Eklöf
 
Star ChartPresentation
Star ChartPresentationStar ChartPresentation
Star ChartPresentationRubberman
 
生涯規劃 養一
生涯規劃 養一生涯規劃 養一
生涯規劃 養一Fuhan Hu
 

Viewers also liked (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
 
生涯規劃 養一
生涯規劃 養一生涯規劃 養一
生涯規劃 養一
 

Similar to iPhone project - Wireless networks seminar

Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)Jorge Maroto
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsPetr Dvorak
 
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 APIsSubhransu Behera
 
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 SessionDavid Gómez García
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneVincent Hoogendoorn
 
(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++Amazon Web Services
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical StuffPetr Dvorak
 
Introduction to VIPER Architecture
Introduction to VIPER ArchitectureIntroduction to VIPER Architecture
Introduction to VIPER ArchitectureHendy Christianto
 
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
 
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 WilliamsPhilip Stehlik
 
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 KelloggStreamNative
 
Multipeer Connectivity
Multipeer ConnectivityMultipeer Connectivity
Multipeer Connectivitywaynehartman
 
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...DataStax Academy
 
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 CloudRoger Brinkley
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIsJulian Viereck
 
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 2013Amazon Web Services
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to GriffonJames Williams
 

Similar to 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
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

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 difficulty (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 profiles, certificates, 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 specific methods with specific 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 file 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, ...
  • 16. Text file handling - example NSString *firstString = @"Voglio salvare questa stringa"; NSString *secondString = @"Voglio salvare anche questa!"; NSMutableArray *plistFileContent = [[NSMutableArray alloc] initWithObjects:firstString, secondString, nil]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *myfile = [documentsDirectory stringByAppendingPathComponent:@"myfile.plist"]; [plistFileContent writeToFile:myfile atomically:YES]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *myfile = [documentsDirectory stringByAppendingPathComponent:@"myfile.plist"]; NSArray *plistFileContent = [[NSArray alloc] initWithContentsOfFile:myfile];
  • 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 identified 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 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
  • 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: notifies 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 fixed, 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 finishEncoding]; [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 finishDecoding]; 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.

Editor's Notes

  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