【IOS】蓝牙通信示例

iPhone开发 应用中关于 GameKit蓝 牙实例讲解是本文要介绍的内容,主要是来了解并学习 GameKit蓝牙 实例。介绍一下这个实例实现的是两个带有 蓝牙 设备的touch之间的一个小游戏,在界面上有个可以响应事件的UIView(之前说过)可以点击,然后看谁新达到WINNING_TAP_COUNT (游戏中一常量可以自己设置)谁先达到谁就赢了,然后通知对方。还要引入GameKit.framework框架 
头文件BlueToothViewController.h:
[pre]
  1. //  
  2. //  // BlueToothViewController.h  
  3. // BlueTooth  //  
  4. // Created by mingchun liu on 09-11-24.  // Copyright sdie 2009. All rights reserved.  
  5. //  
  6. #import <UIKit/UIKit.h> #import <GameKit/GameKit.h>

  7. #define START_GAME_KEY @"startgame"  
  8. #define END_GAME_KEY @"endgame"  #define TAP_COUNT_KEY @"taps"  
  9. #define WINNING_TAP_COUNT 50  
  10. #define AMIPHD_P2P_SESSION_ID @"amiphdp2p2"//这个是蓝牙协议  
  11. @interface BlueToothViewController : UIViewController<GKPeerPickerControllerDelegate,GKSessionDelegate>{          BOOL actingAsHost;//是否提供服务,客户端还是服务器端  
  12.         int playerTapCount;//记录玩家点击次数          int opponentTapCount;//对方点击次数  
  13.         IBOutlet UILabel *playerTapCountLabel;//显示玩家点击次数          IBOutlet UILabel *opponentTapCountLabel;//显示对手点击次数  
  14.         NSString *opponentID;//对方标识符          GKSession *gkSession;  

  15.         IBOutlet UILabel *startQuitButton;//开始退出按钮  
  16. }  
  17. @property BOOL actingAsHost;  @property int playerTapCount;  
  18. @property int opponentTapCount;  @property (nonatomic,retain) GKSession *gkSession;  

  19. @property (nonatomic,retain) NSString *opponentID;  

  20. @property (nonatomic,retain)UILabel *playerTapCountLabel;  
  21. @property (nonatomic,retain)UILabel *opponentTapCountLabel;  
  22. @property (nonatomic,retain)UILabel *startQuitButton;  
  23. -(IBAction) handleStartQuitTapped;//处理开始退出操作  -(IBAction) handleTapViewTapped;//处理点击UIView的操作  
  24. -(void) updateTapCountLabels;//更新显示  -(void) initGame;//初始化游戏  
  25. -(void) hostGame;  -(void) joinGame;//加入游戏  
  26. -(void) endGame;//结束游戏  -(void) showEndGameAlert;//弹出结束游戏对话框  
  27. @end  
  28. #import "BlueToothViewController.h"  
  29. @implementation BlueToothViewController  
  30. @synthesize actingAsHost;  @synthesize playerTapCount;  
  31. @synthesize opponentID;  @synthesize playerTapCountLabel;  
  32. @synthesize opponentTapCountLabel;  
  33. @synthesize startQuitButton;  @synthesize gkSession;  
  34. @synthesize opponentTapCount;  
  35. -(IBAction) handleStartQuitTapped {//建立链接操作,弹出链接窗口显示在线          if (! opponentID) {//如果对手ID为空就建立服务端提供服务  
  36. actingAsHost = YES;                  GKPeerPickerController *peerPickerController =[[GKPeerPickerController alloc] init];  
  37. peerPickerController.delegate = self;  peerPickerController.connectionTypesMask =  
  38. GKPeerPickerConnectionTypeNearby;                  [peerPickerController show];  
  39.         }  }  
  40. -(IBAction) handleTapViewTapped {//点击操作          playerTapCount++;  
  41.         [self updateTapCountLabels];          // did we just win?  
  42.         BOOL playerWins = playerTapCount >= WINNING_TAP_COUNT;//当点击达到一定次数时          // send tap count to peer  
  43.         NSMutableData *message = [[NSMutableData alloc] init];//传的数据类型为nsdata类型的          NSKeyedArchiver *archiver =  
  44.         [[NSKeyedArchiver alloc] initForWritingWithMutableData:message];          [archiver encodeInt:playerTapCount forKey: TAP_COUNT_KEY];  
  45.         if (playerWins)                  [archiver encodeBool:YES forKey:END_GAME_KEY];  
  46.         [archiver finishEncoding];//打包传数据          GKSendDataMode sendMode =  
  47. playerWins ? GKSendDataReliable : GKSendDataUnreliable;//判断用可靠的链接还是不可靠的链接          [gkSession sendDataToAllPeers: message withDataMode:sendMode error:NULL];//发送数据  
  48.         [archiver release];          [message release];  
  49.         // also end game locally          if (playerWins)  
  50.                 [self endGame];  }  

  51. -(void) updateTapCountLabels {  
  52. playerTapCountLabel.text =          [NSString stringWithFormat:@"%d", playerTapCount];  
  53. opponentTapCountLabel.text =          [NSString stringWithFormat:@"%d", opponentTapCount];  
  54. }  -(void) initGame {  
  55. playerTapCount = 0;  opponentTapCount = 0;  
  56. }  -(void) hostGame {  
  57.         [self initGame];          NSMutableData *message = [[NSMutableData alloc] init];  
  58.         NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]                                                                   initForWritingWithMutableData:message];  
  59.         [archiver encodeBool:YES forKey:START_GAME_KEY];          [archiver finishEncoding];  
  60.         NSError *sendErr = nil;          [gkSession sendDataToAllPeers: message  
  61.                                          withDataMode:GKSendDataReliable error:&sendErr];          if (sendErr)  
  62.                 NSLog (@"send greeting failed: %@", sendErr);          // change state of startQuitButton  
  63. startQuitButton.text = @"Quit";          [message release];  
  64.         [archiver release];          [self updateTapCountLabels];  
  65. }  -(void) joinGame {  
  66.         [self initGame];  startQuitButton.text = @"Quit";  
  67.         [self updateTapCountLabels];  }  

  68. //一下是代理方法  

  69. -(GKSession *) peerPickerController: (GKPeerPickerController*) controller  
  70.                   sessionForConnectionType: (GKPeerPickerConnectionType) type {          if (!gkSession) {//如果没有链接时建立连接  
  71. gkSession = [[GKSession alloc]                                           initWithSessionID:AMIPHD_P2P_SESSION_ID//根据此值判断用的是什么链接  
  72.                                          displayName:nil//在线用户名                                           sessionMode:GKSessionModePeer];  
  73. gkSession.delegate = self;          }  
  74.         return gkSession;  }  

  75. - (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session  
  76. {//当picker接收到数据后将其释放掉,否则进入不了界面          [picker dismiss];  
  77. picker.delegate = nil;          [picker autorelease];  
  78. }  - (void)session:(GKSession *)session  
  79. didReceiveConnectionRequestFromPeer:(NSString *)peerID {//已接受连接请求的代理方法  actingAsHost = NO;//设为客户端  
  80. }  
  81. - (void)session:(GKSession *)session peer:(NSString *)peerID  didChangeState:(GKPeerConnectionState)state {//状态改变时触发的代理方法  
  82.         switch (state)          {  
  83.                 case GKPeerStateConnected:                          [session setDataReceiveHandler: self withContext: nil];  
  84. opponentID = peerID;//改变opponentID的值                          actingAsHost ? [self hostGame] : [self joinGame];//  
  85.                         break;          }  
  86. }  
  87. - (void) receiveData: (NSData*) data fromPeer: (NSString*) peerID                     inSession: (GKSession*) session context: (void*) context {//接受数据时的代理操作  
  88.         NSKeyedUnarchiver *unarchiver =          [[NSKeyedUnarchiver alloc] initForReadingWithData:data];  
  89.         if ([unarchiver containsValueForKey:TAP_COUNT_KEY]) {  opponentTapCount = [unarchiver decodeIntForKey:TAP_COUNT_KEY];  
  90.                 [self updateTapCountLabels];          }  
  91.         if ([unarchiver containsValueForKey:END_GAME_KEY]) {                  [self endGame];  
  92.         }          if ([unarchiver containsValueForKey:START_GAME_KEY]) {  
  93.                 [self joinGame];          }  
  94.         [unarchiver release];  }  
  95. //以上是代理方法  
  96. -(void) showEndGameAlert {          BOOL playerWins = playerTapCount> opponentTapCount;  
  97.         UIAlertView *endGameAlert = [[UIAlertView alloc]                                                                   initWithTitle: playerWins ? @"Victory!" : @"Defeat!"  
  98.                                                                  message: playerWins ? @"Your thumbs have emerged supreme!":                                                                   @"Your thumbs have been laid low"  
  99.                                                                  delegate:nil                                                                   cancelButtonTitle:@"OK"  
  100.                                                                  otherButtonTitles:nil];          [endGameAlert show];  
  101.         [endGameAlert release];  }  
  102. -(void) endGame {  opponentID = nil;  
  103. startQuitButton.text = @"Find";          [gkSession disconnectFromAllPeers];  
  104.         [self showEndGameAlert];  }  

  105. /*  
  106. // The designated initializer. Override to perform setup that is required before the view is loaded.  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {  
  107.     if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {          // Custom initialization  
  108.     }      return self;  
  109. }  */  

  110. /*  
  111. // Implement loadView to create a view hierarchy programmatically, without using a nib.  - (void)loadView {  
  112. }  */  

  113. /*  
  114. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  - (void)viewDidLoad {  
  115.     [super viewDidLoad];  }  
  116. */  
  117. /*  // Override to allow orientations other than the default portrait orientation.  
  118. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {      // Return YES for supported orientations  
  119.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  }  
  120. */  
  121. - (void)didReceiveMemoryWarning {          // Releases the view if it doesn't have a superview.  
  122.     [super didReceiveMemoryWarning];  
  123.         // Release any cached data, images, etc that aren't in use.  }  

  124. - (void)viewDidUnload {  
  125.         // Release any retained subviews of the main view.          // e.g. self.myOutlet = nil;  
  126. }  
  127. - (void)dealloc {          [opponentID release];  
  128.         [playerTapCountLabel release];          [opponentTapCountLabel release];  

  129.         [startQuitButton release];          [gkSession release];  
  130.     [super dealloc];  }
[/pre]小结: iPhone开发 GameKit蓝牙 实例讲解的内容介绍完 ,希望通过本文的学习能对你有所帮助!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值