はじめに
MCBrowserViewControllerを使わないパターンでのMultipeerConnectivity適用に必要なデレゲートメソッドたちです。
- iOS 13.5
- Swift 5.2
準備編
class xxxxxController {
let displayName: String!
let serviceType: String!
var peerID: MCPeerID!
var session: MCSession!
var browser: MCNearbyServiceBrowser!
var advertiser: MCNearbyServiceAdvertiser!
func setup() {
displayName = "displayName"
serviceType = "serviceType"
peerID = MCPeerID(displayName: displayName)
session = MCSession(peer: peerID)
session.delegate = self
browser = MCNearbyServiceBrowser(peer: peerID, serviceType: serviceType)
browser.delegate = self
browser.startBrowsingForPeers()
advertiser = MCNearbyServiceAdvertiser(peer: peerID, discoveryInfo: nil, serviceType: serviceType)
advertiser.delegate = self
advertiser.startAdvertisingPeer()
}
}
SessionDelegate編
extension xxxxxController: MCSessionDelegate {
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
}
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) {
}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
}
}
sendメソッドたち
func send(_ data: Data, toPeers peerIDs: [MCPeerID], with mode: MCSessionSendDataMode) throws
func startStream(withName streamName: String, toPeer peerID: MCPeerID) throws -> OutputStream
func sendResource(at resourceURL: URL, withName resourceName: String, toPeer peerID: MCPeerID, withCompletionHandler completionHandler: ((Error?) -> Void)? = nil) -> Progress?
MCNearbyServiceBrowserDelegate編
extension xxxxxController: MCNearbyServiceBrowserDelegate {
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
}
func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) {
}
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
browser.invitePeer(peerID, to: session, withContext: nil, timeout: 0)
}
}
MCNearbyServiceAdvertiserDelegate編
extension xxxxxController: MCNearbyServiceAdvertiserDelegate {
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {
invitationHandler(true, session)
invitationHandler(false, nil)
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) {
}
}