最近在做一个五子棋的项目 , 关于联机对战 我的思路是 进场通讯
引入#import <MultipeerConnectivity/MultipeerConnectivity.h>
其中 MCAdvertiserAssistant 和 MCBrowserViewController 是成对出现的, 会提示系统的UI . 我不是很喜欢, 每次断线重连的时候, 都会弹出提示, 感觉非常的不友好!
推荐使用MCNearbyServiceAdvertiser 和 MCNearbyServiceBrowser
/*引入 广播 和 搜索服务*/
@property (nonatomic, strong) MCNearbyServiceBrowser *nearbyServiceBrowser;
@property (nonatomic, strong) MCNearbyServiceAdvertiser *nearbyServiceAdveriser;
// 创建 mc 需要用到的对象, 全局化 避免重复创建
- (void)createMCsession
{
_peerID = [[MCPeerID alloc] initWithDisplayName:[UIDevice currentDevice].name];
//为用户建立连接
_session = [[MCSession alloc]initWithPeer:_peerID];
self.session.delegate = self;
// _advertiser = [[nearbyServiceBrowser alloc]initWithServiceType:@"rsp-receiver" discoveryInfo:nil session:_session];
_nearbyServiceAdveriser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:_peerID discoveryInfo:nil serviceType:@"summer"];
_nearbyServiceAdveriser.delegate = self;
_nearbyServiceBrowser = [[MCNearbyServiceBrowser alloc]initWithPeer:_peerID serviceType:@"summer"];
//设置代理
_nearbyServiceBrowser.delegate = self;
}
开启服务
- (void)startServe
{
AppDelegateShowToast(@"开启搜索");
if (_peerID == nil) {
[self createMCsession];
}else{
[_nearbyServiceAdveriser stopAdvertisingPeer];
[_nearbyServiceBrowser stopBrowsingForPeers];
}
//开始广播
[_nearbyServiceAdveriser startAdvertisingPeer];
//设置发现服务(接收方)
[_nearbyServiceBrowser startBrowsingForPeers];
}