点对点蓝牙通讯服务类
博客专区 > 泊竹 的博客 > 博客详情
点对点蓝牙通讯服务类
泊竹 发表于4年前
点对点蓝牙通讯服务类
  • 发表于 4年前
  • 阅读 347
  • 收藏 8
  • 点赞 2
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

摘要: 这个类写成了单例,封装了点对点蓝牙通讯的相关功能,可以直接使用。封装了设备搜索,建立链接,收发通讯等处理过程。内部更细节的处理可以扩展。
//
//  LocalChatCenter.h
//  TestLocalChat
//
//  Created by 孙俊 on 14-4-6.
//  Copyright (c) 2014年 yipinapp. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol LocalChatCenterDelegate <NSObject>

@optional
//连接相关
- (void)isConnection;
- (void)isUnConnection;

//数据传输相关
- (void)receiveData:(NSData *)data UserName:(NSString *)userName;

@end

@interface LocalChatCenter : NSObject

@property (nonatomic, weak) id<LocalChatCenterDelegate>     delegate;
@property (nonatomic, assign, readonly) BOOL                isConnected;

+ (LocalChatCenter *)shareInstance;

- (void)startConnection;
- (void)stopConnection;

- (void)sendData:(NSData *)data;

@end

//
//  LocalChatCenter.m
//  TestLocalChat
//
//  Created by 孙俊 on 14-4-6.
//  Copyright (c) 2014年 yipinapp. All rights reserved.
//

#define D_SessionID_My      @"TestChat"

#import "LocalChatCenter.h"
#import <GameKit/GameKit.h>

static LocalChatCenter *localChatCenter = nil;

@interface LocalChatCenter()<GKPeerPickerControllerDelegate, GKSessionDelegate>

@property (nonatomic, strong) GKPeerPickerController    *peerPicker;
@property (nonatomic, strong) GKSession                 *session;
@property (nonatomic, strong) NSString                  *myPeerId;
@property (nonatomic, assign) BOOL                       isConnected;

@end

@implementation LocalChatCenter

+ (LocalChatCenter *)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        localChatCenter = [[LocalChatCenter alloc] init];
    });
    
    return localChatCenter;
}

#pragma mark 通讯连接相关方法
//启动联机
- (void)startConnection
{
    if (self.isConnected == NO) {
        
        self.peerPicker = [[GKPeerPickerController alloc] init];
        self.peerPicker.connectionTypesMask = GKPeerPickerConnectionTypeNearby | GKPeerPickerConnectionTypeOnline;
        self.peerPicker.delegate = self;
        [self.peerPicker show];
    }
}

//设置会话属性回调
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type
{
    if (self.session != nil) {
        return self.session;
    }
    
    self.session = [[GKSession alloc] initWithSessionID:D_SessionID_My
                                            displayName:nil
                                            sessionMode:GKSessionModePeer];
    self.session.delegate = self;
    return self.session;
}

//联机成功回调
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
    self.session = session;
    [self.session setDataReceiveHandler:self withContext:nil];
    self.myPeerId = peerID;
    self.isConnected = YES;
    [picker dismiss];
}

//取消联机
- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker
{
    //此处可以进行取消联机后的处理,可以什么都不做。
}

//停止联机
- (void)stopConnection
{
    if (self.isConnected == YES) {
        
        [self.session disconnectFromAllPeers];
        self.session = nil;
        self.myPeerId = nil;
        self.isConnected = NO;
    }
}

//设备的联机状态改变回调
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state
{
    NSString *peerName = [session displayNameForPeer:peerID];
    if (peerName == nil) {
        peerName = peerID;
    }
    switch (state) {
        case GKPeerStateConnected:
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                                message:[NSString stringWithFormat:@"%@进入会话",peerName]
                                                               delegate:nil
                                                      cancelButtonTitle:@"知道了"
                                                      otherButtonTitles: nil];
            [alertView show];
            
            if ([self.delegate respondsToSelector:@selector(isConnection)]) {
                
                [self.delegate isConnection];
            }
        }
            break;
        case GKPeerStateDisconnected:
        {
            self.isConnected = NO;
            [self stopConnection];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                                message:[NSString stringWithFormat:@"会话结束"]
                                                               delegate:nil
                                                      cancelButtonTitle:@"知道了"
                                                      otherButtonTitles: nil];
            [alertView show];
            
            if ([self.delegate respondsToSelector:@selector(isUnConnection)]) {
                
                [self.delegate isUnConnection];
            }
        }
            break;
            
        default:
            break;
    }
}

- (void)hidePicker
{
    if (self.peerPicker.isVisible) {
        
        [self.peerPicker dismiss];
    }
}

//收到其它设备的连接请求回调
- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID
{
    [session acceptConnectionFromPeer:peerID error:nil];
}

//和其他设备连接发生错误回调
- (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error
{
    
}

//GKSession内部发生错误回调
- (void)session:(GKSession *)session didFailWithError:(NSError *)error
{
    
}

#pragma mark 收发信息相关方法
//发送消息
- (void)sendData:(NSData *)data
{
    [self startConnection];
    NSError *error;
    BOOL sendOk = [self.session sendDataToAllPeers:data
                                      withDataMode:GKSendDataReliable
                                             error:&error];
    if (sendOk == NO) {
        NSLog(@"传送信息失败,原因如下/n%@", error);
    }
}

//接收消息
- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context
{
    if ([self.delegate respondsToSelector:@selector(receiveData: UserName:)]) {
        
        NSString *userName = [session displayNameForPeer:peer];
        if (userName == nil || userName.length == 0) {
            
            userName = peer;
        }
        
        [self.delegate receiveData:data UserName:userName];
    }
}

@end


标签: IOS 蓝牙 通讯
共有 人打赏支持
粉丝 91
博文 67
码字总数 13285
×
泊竹
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: