SlideShare a Scribd company logo
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 Web
Ray 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 Gears
dion
 
GradleFX
GradleFXGradleFX
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
Ortus Solutions, Corp
 
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 2017
Codemotion
 
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 Framework
IndicThreads
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
Xebia IT Architects
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jquery
Umar 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 Brocato
Sencha
 
#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 django
Gage 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 Messages
Rob 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 educativo
frintonarcos
 
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 ops
Sunny Dua
 
Consciousness: The Brain Is Aware
Consciousness: The Brain Is AwareConsciousness: The Brain Is Aware
Consciousness: The Brain Is Aware
Ruth Danielle Gascon
 
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 summary
lctipton
 
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
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
Damien Krotkine
 
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 APIs
Subhransu 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 Session
David Gómez García
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows Phone
Vincent 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 Architecture
Hendy 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 Williams
Philip 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 Kellogg
StreamNative
 
The MEAN stack
The MEAN stack The MEAN stack
The MEAN stack
Nattaya Mairittha
 
Multipeer Connectivity
Multipeer ConnectivityMultipeer Connectivity
Multipeer Connectivity
waynehartman
 
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 Cloud
Roger Brinkley
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIs
Julian 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 2013
Amazon Web Services
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
James 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

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 

Recently uploaded (20)

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 

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