iOS Development-gamekit Bluetooth development

Source: Internet
Author: User

Bluetooth 4.0
蓝牙4.0是2012年最新蓝牙版本,是3.0的升级版本;较3.0版本更省电、成本低、3毫秒低延迟、超长有效连接距离、AES-128加密等;通常用在蓝牙耳机、蓝牙音箱等设备上。蓝牙技术联盟(Bluetooth SIG)2010年7月7日宣布,正式采纳蓝牙4.0核心规范(Bluetooth Core Specification Version 4.0 ),并启动对应的认证计划。会员厂商可以提交其产品进行测试,通过后将获得蓝牙4.0标准认证。 该技术拥有极低的运行和待机功耗,使用一粒纽扣电池甚至可连续工作数年之久。
Implementation of Bluetooth in iOS

4 frames are available in iOS for Bluetooth connectivity
Gamekit.framework (simple to use)
Can only be used for connections between iOS devices, more games (such as Gobang), expiring from IOS7

Multipeerconnectivity.framework
Can only be used for connections between iOS devices, introduced from IOS7, primarily for file sharing (sandbox-only files)

Externalaccessory.framework
Can be used for third-party Bluetooth device interaction, but Bluetooth devices must be certified by Apple MFI (less domestically)

Corebluetooth.framework (nowadays popular)
Can be used for third-party Bluetooth device interaction and must support Bluetooth 4.0
Hardware is at least 4s and the system is at least iOS6
Bluetooth 4.0 is known for its low power consumption and is commonly called ble (bluetooth lower energy)
At present, the use of more cases: sports hand bad, embedded devices, smart home

Introduction to the Gamekit framework

With the Gamekit framework, you can add peer connections to the game, also known as a pair-or point-to-point connection, peer to peer.
By using the peer-network connection API in the Gamekit framework, you can create a peer network between gamers and exchange data between game/app instances.
Gamekit Framework can use Bluetooth to create a network between players, players do not even need to connect to the Internet, you can play against each other.

Peering network connection via Bluetooth

Presents a gkpeerpickercontroller for both players and provides a standard user interface to connect two devices
Viewcontrooler follows the Gkpeerpickercontrollerdelegate protocol to process information from the Gkpeerpickercontroller (peer selector)
After establishing a connection, use the Gksession class to send data to the peer device
Write code in the ReceiveData:fromPeer:inSession:context proxy method to process the received data

//发送数据方法[_peerSession sendDataToAllPeers:data withDataMode:GKSendDataReliable error:&error];//接收数据方法- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context;

If you want to send a custom object over the network, you need to use the Nskeyedarchiver method to archive the custom object before sending the archived NSData
Custom objects need to comply with the Nscoding protocol and implement appropriate archiving and recovery methods
After receiving the data, use the Nskeyedunarchiver method to recover the data

Bluetooth development steps for Gamekit
//Show list of Bluetooth devices that can be connected  gkpeerpickercontroller *PPC = [[ Gkpeerpickercontroller alloc] init];pp c.delegate  =  Self ; [PPC show]; //monitor Bluetooth Connection in Proxy method -(void ) Peerpickercontroller :(Gkpeerpickercontroller *) Picker Didconnectpeer: (nsstring  *) PeerID toSession: ( Gksession *) session {nslog  (@ "Connect to Device:%@" , Peerid); //turn off the Bluetooth device display interface  [Picker dismiss]; //set the listener after receiving the Bluetooth data  [Session Setdatareceivehandler:self  withcontext:nil ]; //Save session  self  .session  = Session;} 
Processing received Bluetooth data-(void) Receivedata: (NSData*) Data frompeer:(nsstring *)peer insession: (gksession *)session Context:(void *)context {} UsegksessionSend data to other devices//Send data to the specified connection device-(BOOL) SendData: (NSData*) Data topeers:(nsarray *)peers Withdatamode:(gksenddatamode)mode Error:(nserror *)error;Send data to all connected devices-(BOOL) Senddatatoallpeers: (NSData*) Data withdatamode:(gksenddatamode)mode error:(nserror *) error;
Gamekit's Bluetooth development note

Can only be used for connections between iOS devices

Can only be used for connections between the same application

Better not to use Bluetooth to send larger data

Gamekit Bluetooth Development Example
#Import "ViewController.h"#include <GameKit/GameKit.h>@interfaceViewcontroller () <uinavigationcontrollerdelegate, Uiimagepickercontrollerdelegate, Gkpeerpickercontrollerdelegate>/** * Connect * *-(ibaction) connect;/** * Select picture * /-(ibaction) Selectedphoto;/** * * Send * *-(ibaction) send;@property(Weak, nonatomic) Iboutlet Uiimageview *customiv;/** * Session * *@property(Nonatomic, Strong) Gksession *session;@end@implementationviewcontroller-(void) Viewdidload {[SuperViewdidload];additional setup after loading the view, typically from a nib.}-(ibaction) Connect {//1. Create a controller that chooses a different Bluetooth deviceGkpeerpickercontroller *PEERPK = [[Gkpeerpickercontroller alloc] init];//2. Become the agent for the controllerPeerpk.delegate = self;//3. Show Bluetooth controller[PEERPK show];} #pragma mark-gkpeerpickercontrollerdelegate//4. Implementing the Dialing Method/** * When the Bluetooth device connection is successful, the controller that will call * * @param Picker Trigger time * @param Peerid The ID of the Bluetooth device connected * @param ses Sion connect a Bluetooth session (available communication), you can transfer data as soon as you get the session */- (void) Peerpickercontroller: (Gkpeerpickercontroller *) Picker Didconnectpeer: (NSString *) Peerid toSession: (GKSession *) session{NSLog (@"%@", Peerid);//1. Save SessionSelf.session = session;//2. Set the listener to receive the data passed over    /* Handler: Who will handle the received data withcontext: Passing Data */[Self.session setdatareceivehandler:self Withcontext:nil];//2. Turn off display of the Bluetooth device controller[Picker dismiss];}/** * The data passed by the other device will be called * * * @param data passing through * @param The ID of the peer passing data device * @param Session sessions * @param The data passed when the context registers for monitoring */- (void) Receivedata: (NSData *) data frompeer: (NSString *) Peer insession: (Gksession *) session Context: (void*) context{//NSLog (@ "%s", __func__);    //1. Convert the passed data to a picture (note: Because the picture is sent, it needs to be converted to a picture)UIImage *image = [UIImage imagewithdata:data]; Self.customIV.image = image;} - (void) Peerpickercontrollerdidcancel: (Gkpeerpickercontroller *) picker{}-(ibaction) Send {//Use the session to send picture data    //1. Remove the picture from the Customimageview and convert it to binaryUIImage *image = self.customIV.image; NSData *data = uiimagepngrepresentation (image);/ * gksenddatareliable, data security transmission mode, slow gksenddataunreliable, data insecure send mode, fast * /    / * Data: datareliable: Whether to send data securely (mode of sending data) error: Whether to listen for send error * /[Self.session senddatatoallpeers:data withdatamode:gksenddatareliable error:nil];} -(Ibaction) selectedphoto{//1. Create a picture selection controllerUiimagepickercontroller *IMAGEPK = [[Uiimagepickercontroller alloc] init];//2. Determine if the gallery is available to open    if([Uiimagepickercontroller Issourcetypeavailable:uiimagepickercontrollersourcetypesavedphotosalbum]) {//3. Set the type of open galleryImagepk.sourcetype = Uiimagepickercontrollersourcetypesavedphotosalbum; Imagepk.delegate = self;//4. Open Picture Selection Controller[Self presentviewcontroller:imagepk animated:yes completion:nil]; }} #pragma mark-uiimagepickercontrollerdelegate-(void) Imagepickercontroller: (Uiimagepickercontroller *) Picker Didfinishpickingmediawithinfo: (NSDictionary *) info{//NSLog (@ "%@", info);Self.customIV.image = Info[uiimagepickercontrolleroriginalimage]; [Picker Dismissviewcontrolleranimated:yes completion:nil];}@end
Scan peripheral Devices

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

iOS Development-gamekit Bluetooth development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.