-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDevice.swift
64 lines (50 loc) · 2.03 KB
/
Device.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Device.swift
// MultipeerExample
//
// Created by Ben Gottlieb on 8/18/18.
// Copyright © 2018 Stand Alone, Inc. All rights reserved.
//
import Foundation
import MultipeerConnectivity
class Device: NSObject {
let peerID: MCPeerID
var session: MCSession?
var name: String
var state = MCSessionState.notConnected
var lastMessageReceived: Message?
init(peerID: MCPeerID) {
self.name = peerID.displayName
self.peerID = peerID
super.init()
}
func connect() {
if self.session != nil { return }
self.session = MCSession(peer: MPCManager.instance.localPeerID, securityIdentity: nil, encryptionPreference: .required)
self.session?.delegate = self
}
func disconnect() {
self.session?.disconnect()
self.session = nil
}
func invite(with browser: MCNearbyServiceBrowser) {
self.connect()
browser.invitePeer(self.peerID, to: self.session!, withContext: nil, timeout: 10)
}
}
extension Device: MCSessionDelegate {
public func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
self.state = state
NotificationCenter.default.post(name: MPCManager.Notifications.deviceDidChangeState, object: self)
}
static let messageReceivedNotification = Notification.Name("DeviceDidReceiveMessage")
public func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
if let message = try? JSONDecoder().decode(Message.self, from: data) {
self.lastMessageReceived = message
NotificationCenter.default.post(name: Device.messageReceivedNotification, object: message, userInfo: ["from": self])
}
}
public func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { }
public func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { }
public func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { }
}