iPhone开发应用中关于GameKit蓝牙实例讲解是本文要介绍的内容,主要是来了解并学习GameKit蓝牙实例。介绍一下这个实例实现的是两个带有蓝牙设备的touch之间的一个小游戏,在界面上有个可以响应事件的UIView(之前说过)可以点击,然后看谁新达到WINNING_TAP_COUNT (游戏中一常量可以自己设置)谁先达到谁就赢了,然后通知对方。还要引入GameKit.framework框架
头文件BlueToothViewController.h:
[pre]

    //

  1. //  // BlueToothViewController.h
  2. // BlueTooth  //
  3. // Created by mingchun liu on 09-11-24.  // Copyright sdie 2009. All rights reserved.
  4. //
  5. #import <UIKit/UIKit.h> #import
    <GameKit/GameKit.h>
  6. #define START_GAME_KEY @"startgame"
  7. #define END_GAME_KEY @"endgame"  #define TAP_COUNT_KEY @"taps"
  8. #define WINNING_TAP_COUNT 50
  9. #define AMIPHD_P2P_SESSION_ID @"amiphdp2p2"//这个是蓝牙协议
  10. @interface BlueToothViewController : UIViewController<GKPeerPickerControllerDelegate,GKSessionDelegate>{          BOOL actingAsHost;//是否提供服务,客户端还是服务器端
  11. int playerTapCount;//记录玩家点击次数          int opponentTapCount;//对方点击次数
  12. IBOutlet UILabel *playerTapCountLabel;//显示玩家点击次数          IBOutlet UILabel *opponentTapCountLabel;//显示对手点击次数
  13. NSString *opponentID;//对方标识符          GKSession *gkSession;
  14. IBOutlet UILabel *startQuitButton;//开始退出按钮
  15. }
  16. @property BOOL actingAsHost;  @property int playerTapCount;
  17. @property int opponentTapCount;  @property (nonatomic,retain) GKSession *gkSession;
  18. @property (nonatomic,retain) NSString *opponentID;
  19. @property (nonatomic,retain)UILabel *playerTapCountLabel;
  20. @property (nonatomic,retain)UILabel *opponentTapCountLabel;
  21. @property (nonatomic,retain)UILabel *startQuitButton;
  22. -(IBAction) handleStartQuitTapped;//处理开始退出操作  -(IBAction) handleTapViewTapped;//处理点击UIView的操作
  23. -(void) updateTapCountLabels;//更新显示  -(void) initGame;//初始化游戏
  24. -(void) hostGame;  -(void) joinGame;//加入游戏
  25. -(void) endGame;//结束游戏  -(void) showEndGameAlert;//弹出结束游戏对话框
  26. @end
  27. #import "BlueToothViewController.h"
  28. @implementation BlueToothViewController
  29. @synthesize actingAsHost;  @synthesize playerTapCount;
  30. @synthesize opponentID;  @synthesize playerTapCountLabel;
  31. @synthesize opponentTapCountLabel;
  32. @synthesize startQuitButton;  @synthesize gkSession;
  33. @synthesize opponentTapCount;
  34. -(IBAction) handleStartQuitTapped {//建立链接操作,弹出链接窗口显示在线          if (! opponentID) {//如果对手ID为空就建立服务端提供服务
  35. actingAsHost =
    YES;                  GKPeerPickerController *peerPickerController =[[GKPeerPickerController alloc] init];
  36. peerPickerController.delegate =
    self;  peerPickerController.connectionTypesMask =
  37. GKPeerPickerConnectionTypeNearby;                  [peerPickerController show];
  38. }  }
  39. -(IBAction) handleTapViewTapped {//点击操作          playerTapCount++;
  40. [self updateTapCountLabels];          // did we just win?
  41. BOOL playerWins =
    playerTapCount >= WINNING_TAP_COUNT;//当点击达到一定次数时          // send tap count to peer
  42. NSMutableData *message = [[NSMutableData alloc] init];//传的数据类型为nsdata类型的          NSKeyedArchiver *archiver =
  43. [[NSKeyedArchiver
    alloc] initForWritingWithMutableData:message];          [archiver
    encodeInt:playerTapCount forKey: TAP_COUNT_KEY];
  44. if (playerWins)                  [archiver encodeBool:YES forKey:END_GAME_KEY];
  45. [archiver finishEncoding];//打包传数据          GKSendDataMode
    sendMode =
  46. playerWins
    ? GKSendDataReliable :
    GKSendDataUnreliable;//判断用可靠的链接还是不可靠的链接          [gkSession
    sendDataToAllPeers: message withDataMode:sendMode error:NULL];//发送数据
  47. [archiver release];          [message release];
  48. // also end game locally          if (playerWins)
  49. [self endGame];  }
  50. -(void) updateTapCountLabels {
  51. playerTapCountLabel.text =          [NSString stringWithFormat:@"%d", playerTapCount];
  52. opponentTapCountLabel.text =          [NSString stringWithFormat:@"%d", opponentTapCount];
  53. }  -(void) initGame {
  54. ;  ;
  55. }  -(void) hostGame {
  56. [self initGame];          NSMutableData *message = [[NSMutableData alloc] init];
  57. NSKeyedArchiver *archiver
    = [[NSKeyedArchiver
    alloc]                                                                  
    initForWritingWithMutableData:message];
  58. [archiver encodeBool:YES forKey:START_GAME_KEY];          [archiver finishEncoding];
  59. NSError *sendErr =
    nil;          [gkSession sendDataToAllPeers: message
  60. withDataMode:GKSendDataReliable error:&sendErr];          if (sendErr)
  61. NSLog (@"send greeting failed: %@", sendErr);          // change state of startQuitButton
  62. startQuitButton.text = @"Quit";          [message release];
  63. [archiver release];          [self updateTapCountLabels];
  64. }  -(void) joinGame {
  65. [self initGame];  startQuitButton.text = @"Quit";
  66. [self updateTapCountLabels];  }
  67. //一下是代理方法
  68. -(GKSession *) peerPickerController: (GKPeerPickerController*) controller
  69. sessionForConnectionType: (GKPeerPickerConnectionType) type {          if (!gkSession) {//如果没有链接时建立连接
  70. gkSession = [[GKSession alloc]                                           initWithSessionID:AMIPHD_P2P_SESSION_ID//根据此值判断用的是什么链接
  71. displayName:nil//在线用户名                                          
    sessionMode:GKSessionModePeer];
  72. gkSession.delegate =
    self;          }
  73. return gkSession;  }
  74. - (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
  75. {//当picker接收到数据后将其释放掉,否则进入不了界面          [picker dismiss];
  76. picker.delegate =
    nil;          [picker autorelease];
  77. }  - (void)session:(GKSession *)session
  78. didReceiveConnectionRequestFromPeer:(NSString *)peerID {//已接受连接请求的代理方法  actingAsHost =
    NO;//设为客户端
  79. }
  80. - (void)session:(GKSession *)session peer:(NSString *)peerID  didChangeState:(GKPeerConnectionState)state {//状态改变时触发的代理方法
  81. switch (state)          {
  82. case GKPeerStateConnected:                          [session setDataReceiveHandler: self withContext: nil];
  83. opponentID = peerID;//改变opponentID的值                          actingAsHost ? [self hostGame] : [self joinGame];//
  84. break;          }
  85. }
  86. -
    (void) receiveData: (NSData*) data fromPeer: (NSString*)
    peerID                     inSession: (GKSession*) session context:
    (void*) context {//接受数据时的代理操作
  87. NSKeyedUnarchiver *unarchiver =          [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  88. if ([unarchiver containsValueForKey:TAP_COUNT_KEY]) {  opponentTapCount = [unarchiver decodeIntForKey:TAP_COUNT_KEY];
  89. [self updateTapCountLabels];          }
  90. if ([unarchiver containsValueForKey:END_GAME_KEY]) {                  [self endGame];
  91. }          if ([unarchiver containsValueForKey:START_GAME_KEY]) {
  92. [self joinGame];          }
  93. [unarchiver release];  }
  94. //以上是代理方法
  95. -(void) showEndGameAlert {          BOOL playerWins =
    playerTapCount> opponentTapCount;
  96. UIAlertView *endGameAlert
    = [[UIAlertView
    alloc]                                                                  
    initWithTitle: playerWins ? @"Victory!" : @"Defeat!"
  97. message: playerWins ? @"Your thumbs have emerged
    supreme!":                                                                  
    @"Your thumbs have been laid low"
  98. delegate:nil                                                                  
    cancelButtonTitle:@"OK"
  99. otherButtonTitles:nil];          [endGameAlert show];
  100. [endGameAlert release];  }
  101. -(void) endGame {  opponentID =
    nil;
  102. startQuitButton.text = @"Find";          [gkSession disconnectFromAllPeers];
  103. [self showEndGameAlert];  }
  104. /*
  105. // The designated initializer. Override to perform setup
    that is required before the view is loaded.  -
    (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
    *)nibBundleOrNil {
  106. if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {          // Custom initialization
  107. }      return self;
  108. }  */
  109. /*
  110. // Implement loadView to create a view hierarchy programmatically, without using a nib.  - (void)loadView {
  111. }  */
  112. /*
  113. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  - (void)viewDidLoad {
  114. [super viewDidLoad];  }
  115. */
  116. /*  // Override to allow orientations other than the default portrait orientation.
  117. -

    (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {      // Return YES for supported orientations

  118. return (interfaceOrientation == UIInterfaceOrientationPortrait);  }
  119. */
  120. - (void)didReceiveMemoryWarning {          // Releases the view if it doesn't have a superview.
  121. [super didReceiveMemoryWarning];
  122. // Release any cached data, images, etc that aren't in use.  }
  123. - (void)viewDidUnload {
  124. // Release any retained subviews of the main view.          // e.g.
    self.myOutlet = nil;
  125. }
  126. - (void)dealloc {          [opponentID release];
  127. [playerTapCountLabel release];          [opponentTapCountLabel release];
  128. [startQuitButton release];          [gkSession release];
  129. [super dealloc];  }

[/pre]小结:iPhone开发GameKit蓝牙实例讲解的内容介绍完 ,希望通过本文的学习能对你有所帮助!

[ios2]蓝牙通信【转】的更多相关文章

  1. Android学习笔记之蓝牙通信...

    PS:最近同学问我蓝牙的事,因此自己也就脑补了一下蓝牙... 学习内容: 1.如何实现蓝牙通信技术...   蓝牙通信其实是手机里很常用的一种通信方式,现在的手机中是必然存在蓝牙的,蓝牙通信也是有一部 ...

  2. BLE蓝牙通信指令交互过程配对与绑定

    最简单一次蓝牙通信需要以上相关步骤,包括discovery device,connect,pairing,bond等4个主要部分.BLE中主从机建立连接,到配对和绑定的过程如下图:

  3. Android -传统蓝牙通信聊天

    概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设备.蓝牙连接.通信等. 详细 代码下载:http://www.demodashi.com/demo/10676.html 原文地址: Andr ...

  4. Android BLE设备蓝牙通信框架BluetoothKit

    BluetoothKit是一款功能强大的Android蓝牙通信框架,支持低功耗蓝牙设备的连接通信.蓝牙广播扫描及Beacon解析. 关于该项目的详细文档请关注:https://github.com/d ...

  5. Android - 传统蓝牙通信聊天

    Android -传统蓝牙通信聊天 技术:java+Android4.4+jdk1.8 运行环境:Android4.4.Android7.0 概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设 ...

  6. Android 串口蓝牙通信开发Java版本

    Android串口BLE蓝牙通信Java版 0. 导语 Qt on Android 蓝牙通信开发 我们都知道,在物联网中,BLE蓝牙是通信设备的关键设备.在传统的物联网应用中,无线WIFI.蓝牙和Zi ...

  7. PC蓝牙通信C#代码实现

    PC蓝牙通信C#代码实现 这篇文章主要为大家详细介绍了PC蓝牙通信C#代码实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 本文实例为大家分享了C#实现PC蓝牙通信代码,供大家参考,具体内容如下 ...

  8. Android蓝牙通信总结

    这篇文章要达到的目标: 1.介绍在Android系统上实现蓝牙通信的过程中涉及到的概念. 2.在android系统上实现蓝牙通信的步骤. 3.在代码实现上的考虑. 4.例子代码实现(手持设备和蓝牙串口 ...

  9. Qt on Android 蓝牙通信开发

    版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...

随机推荐

  1. 使用Vim或Codeblocks格式化代码

    在网上的代码,有很多的代码都是丢失缩进的,几行还好,手动改改,多了呢,不敢想象,没有缩进的代码.别说排错,就是阅读都是困难的,还好,有两个常用工具可以轻松的解决问题. (一)Vim(简单方便,可将代码 ...

  2. C#中抽象类和接口的区别

    原文:C#中抽象类和接口的区别 大家在编程时都容易把抽象类和接口搞混,下面为大家从概念上讲解抽象类和接口的区别: 一.抽象类: 含有abstract修饰符的class即为抽象类,抽象类是特殊的类,只是 ...

  3. 探秘IntelliJ IDEA 13测试版新功能——调试器显示本地变量

    IntelliJ IDEA在业界被公认为最好的Java开发平台之一,JetBrains公司将在12月正式发布IntelliJ IDEA 13版本. 现在,小编将和大家一起探秘密IntelliJ IDE ...

  4. JSON数据转换方法 parse()和stringify()

    将对象转换成JSON格式的文本数据 var str = JSON.stringify(data); 将对象转换成JSON对象的方法 var data = JSON.parse(str);

  5. Knockout应用开发指南

    Knockout应用开发指南 第一章:入门 2011-11-21 14:20 by 汤姆大叔, 20799 阅读, 17 评论, 收藏, 编辑 1    Knockout简介 (Introductio ...

  6. C#发送邮件三种方法(Localhost,SMTP,SSL-SMTP)

    原文:C#发送邮件三种方法(Localhost,SMTP,SSL-SMTP) 最近公司由于一个R&I项目的需要,用户要求在购买产品或出货等一些环节,需要发送邮件提醒或者说每周一让系统自动采集数 ...

  7. 18. Scrum敏捷软件开发

      1)柯维定律 2)如何组件敏捷团队? 团队5~9个人,Mike带过最多的是14个人.个人建议,别超过10个.否则沟通的成本直线上升.(团队的午餐,两个匹萨就够了). 引入特性团队(针对于传统的组件 ...

  8. 领域驱动设计(DDD)

    领域驱动设计(DDD)实现之路 2004年,当Eric Evans的那本<领域驱动设计——软件核心复杂性应对之道>(后文简称<领域驱动设计>)出版时,我还在念高中,接触到领域驱 ...

  9. java入门学习(十二)运算语句 if switch

    这两天在网上做兼职,耽误了些博客见谅哈 欢迎来我的博客:www.taomaipin.com java中的运算语句而且频繁用到的无法就是条件语句和循环语句,包括if,for,while,switch,b ...

  10. NET系列文章

    NET系列文章 由于博主今后一段时间可能会很忙(准备出书:<.NET框架设计—模式.配置.工具>,外加换了新工作),所以博客会很少更新: 在最近一年左右时间里,博主各种.NET技术类型的文 ...