2024年4月29日发(作者:小度在家)
iPhone 掌握蓝牙通信编程初体验
/a2010/0114/837/
【IT168技术】iPhone OS 3.0的最佳功能是GameKit框架,这个框架包括了允许基于蓝牙网络进行通信的API,你可以更轻松地创建
点到点的游戏和应用程序。与其它移动平台不一样,在iPhone中使用蓝牙作为一个通信信道比预期的要容易得多,因此,本文将向你展
示如何构建一个简单的应用程序,实现iPhone和iPod之间的相互通信。
注意:如果要测试本文所介绍的内容,需要两部iPhone(3G或3GS),或使用iPhone OS 3.0或更高版本的iPod设备(二代或更新版
本)。
创建一个项目
使用Xcode,创建一个新的基于视图的应用程序项目,取名为Bluetooth。访问蓝牙的各种API位于GameKit框架中,因此,你需
要将这个框架添加到刚刚创建的项目中,在Xcode的框架组上点右键,选择“添加”*“现有框架”,选择GameKit框架,如图1所示。
图 1 添加GameKit框架
在BluetoothViewController.h文件中,声明下面的对象,outlet和行为:
1 #import
2
3 #import
4
5 @interface BluetoothViewController : UIViewController {
6
7 GKSession *currentSession;
8
9 IBOutlet UITextField *txtMessage;
10
11 IBOutlet UIButton *connect;
12
13 IBOutlet UIButton *disconnect;
14
15 }
16
17 @property (nonatomic, retain) GKSession *currentSession;
18
19 @property (nonatomic, retain) UITextField *txtMessage;
20
21 @property (nonatomic, retain) UIButton *connect;
22
23 @property (nonatomic, retain) UIButton *disconnect;
24
25 -(IBAction) btnSend:(id) sender;
26
27 -(IBAction) btnConnect:(id) sender;
28
29 -(IBAction) btnDisconnect:(id) sender;
30
31 @end
32
33
GKSession对象用于表现两个蓝牙设备之间连接的一个会话,你也可以使用它在两个设备之间发送和接收数据。
在BluetoothViewController.m文件中,添加下面的代码:
1 #import "BluetoothViewController.h"
2
3 #import
4
5 @implementation BluetoothViewController
6
7 @synthesize currentSession;
8
9 @synthesize txtMessage;
10
11 @synthesize connect;
12
发布者:admin,转转请注明出处:http://www.yc00.com/num/1714374108a2434542.html
评论列表(0条)