MultipeerConnectivity是iOS7推出的多点连接框架,多用于文件传输,类似于iOS设备的airTrop隔空投放,在没有联网的情况下也能聊天传文件。

使用方法,一个设备作为广播开放PeerID,另一个设备搜索广播的peerID,建立连接相互发送文件

1,首先每个设备都要创建一个PeerID用来标示自己

// MD1

lazy var me: MCPeerID = {

let peer: MCPeerID

peer = MCPeerID(displayName: UIDevice.current.name)

return peer

}()

2.创建连接需要MCSession,设置代理,实现代理方法

// MD2

lazy var session: MCSession = {

let s = MCSession(peer: me, securityIdentity: nil, encryptionPreference: .none)

s.delegate = self

return s

}()

// MD3

extension PeerService: MCSessionDelegate {

func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {

switch state {

case .connected:

print("Now connected to \(peerID.displayName)")

DispatchQueue.main.async {

self.didConnectToDevice?(peerID.displayName)

}

case .connecting:

print("Connecting to \(peerID.displayName)")

case .notConnected:

print("NOT connected to \(peerID.displayName)")

}

}

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {

}

func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {

}

func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {

NSLog("Started resource download: \(resourceName)")

}

func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {

NSLog("Finished resource download: \(resourceName)")

// MD12

guard let url = localURL else { return }

DispatchQueue.main.async {

self.didReceiveFile?(url)

}

}

}

3广播peerID

// MD4

lazy var advertiser: MCNearbyServiceAdvertiser = {

let a = MCNearbyServiceAdvertiser(peer: me, discoveryInfo: ["demo": "data"], serviceType: "MultipeerDemo")

a.delegate = self

return a

}()

func startAdvertising() {

// MD6

advertiser.startAdvertisingPeer()

}

4实现广播ID的代理方法

// MD5

extension PeerService: MCNearbyServiceAdvertiserDelegate {

func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {

// This is insecure! We should verify that the peer is valid and etc etc

invitationHandler(true, session)    //确认连接,把session赋给它

}

func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) {

NSLog("Woops! Advertising failed with error \(String(describing: error))")

}

}

5.作为搜索的peerID要创建browser实现代理方法

// MD7

lazy var browser: MCNearbyServiceBrowser = {

let b = MCNearbyServiceBrowser(peer: me, serviceType: "MultipeerDemo")

b.delegate = self

return b

}()

func startListening() {//开始搜索

// MD9

browser.startBrowsingForPeers()

}

// MD8

extension PeerService: MCNearbyServiceBrowserDelegate {

func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {

//搜到了peerID可以放入熟组中,选择想要连接的peerID连接,这里直接连接

browser.invitePeer(peer, to: session, withContext: nil, timeout: 10)

}

func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {

NSLog("Puke")

}

}

//发送图片

func sendPicture(with data: Data, completion: @escaping (Error?) -> Void) {

// MD11

guard let peer = session.connectedPeers.last else {

NSLog("No connected peers to send to")

return

}

guard let baseURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {

fatalError("No caches directory. WHAT?!")

}

let filename = UUID().uuidString + ".png"

let fileURL = baseURL.appendingPathComponent(filename)

do {

try data.write(to: fileURL, options: .atomicWrite)

session.sendResource(at: fileURL,

withName: filename,

toPeer: peer,

withCompletionHandler: completion)

} catch {

completion(error)

}

}

//发送字符串data

let srt = "hello"

if let data = srt.data(using: .utf8){

try! session.send(data, toPeers: [peerID], with: .reliable)

}

接收到数据后进行相应的处理得到想要的数据

iOSMultipeerConnectivity使用的更多相关文章

随机推荐

  1. Angular 彻底解决 Dropdown 在 Safari 上无法自动关闭的问题

    之前在 Safari 上用 focus 事件来实现 Dropdown 下拉菜单,结果在 iOS 上不兼容. 尝试了 MDN 和 stack over flow 上各种奇技淫巧,然而在 iOS 上全都败 ...

  2. Often Misused:Spring Remote Service 经常被误用:Spring远程服务

  3. SpringBoot2 配置多数据源,整合MybatisPlus增强插件

    本文源码:GitHub·点这里 || GitEE·点这里 一.项目案例简介 1.多数据简介 实际的项目中,经常会用到不同的数据库以满足项目的实际需求.随着业务的并发量的不断增加,一个项目使用多个数据库 ...

  4. VS2008 激活

    序列号:PYHYP-WXB3B-B2CCM-V9DX9-VDY8T 如果没有序列号输入框需要使用crackvs2008forwindows7工具进行修复

  5. asp.net core中使用cookie身份验证

    配置 在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务: services.AddAuth ...

  6. Class文件结构-属性表

    一.属性表整体结构 二.属性表具体结构

  7. [转]为何选择 Flink

    本文转自:https://www.ituring.com.cn/book/tupubarticle/23229 第 1 章 为何选择 Flink 人们对某件事的正确理解往往来自基于有效论据的结论.要获 ...

  8. QGIS练手 - 数据

    又熬夜了... 这篇博客可能会将QGIS数据管理部分和ArcGIS数据管理进行对比学习. 1. 本地数据文件与数据库(矢量) 1.1 文件 QGIS用的是shp文件.kml文件.geojson文件较多 ...

  9. Android 使用 aapt 命令查看 apk 包名

    一.aapt 是什么 aapt 即Android Asset Packaging Tool,在SDK的build-tools目录下.该工具可以查看,创建, 更新ZIP格式的文档附件(zip, jar, ...

  10. 基于Python和Xtrbackup的自动化备份与还原实现

    xtrabackup是一个MySQL备份还原的常用工具,实际使用过程应该都是shell或者python封装的自动化脚本,尤其是备份.对还原来说,对于基于完整和增量备份的还原,还原差异备份需要指定增量备 ...