Skip to content

Commit

Permalink
Merge pull request #9 from CallumTodd7/master
Browse files Browse the repository at this point in the history
Surface sender peer
  • Loading branch information
insidegui authored Jul 8, 2020
2 parents a135dbd + 9ad42b4 commit 8dd6524
Show file tree
Hide file tree
Showing 16 changed files with 300 additions and 8,328 deletions.
1,231 changes: 42 additions & 1,189 deletions Documentation/MultipeerConfiguration/index.html

Large diffs are not rendered by default.

1,194 changes: 16 additions & 1,178 deletions Documentation/MultipeerConfiguration_Invitation/index.html

Large diffs are not rendered by default.

1,220 changes: 29 additions & 1,191 deletions Documentation/MultipeerConfiguration_Security/index.html

Large diffs are not rendered by default.

1,193 changes: 12 additions & 1,181 deletions Documentation/MultipeerDataSource/index.html

Large diffs are not rendered by default.

1,325 changes: 122 additions & 1,203 deletions Documentation/MultipeerTransceiver/index.html

Large diffs are not rendered by default.

1,213 changes: 29 additions & 1,184 deletions Documentation/Peer/index.html

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Documentation/all.css

Large diffs are not rendered by default.

1,187 changes: 8 additions & 1,179 deletions Documentation/index.html

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ let transceiver = MultipeerTransceiver()
transceiver.resume()

// Configure message receivers
transceiver.receive(SomeCodableThing.self) { payload in
print("Got my thing! \(payload)")
transceiver.receive(SomeCodableThing.self) { payload, sender in
print("Got my thing from \(sender.name)! \(payload)")
}

// Broadcast message to peers
Expand All @@ -45,4 +45,4 @@ let package = Package(
],
...
)
```
```
12 changes: 9 additions & 3 deletions Sources/MultipeerKit/Internal API/MockMultipeerConnection.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import Foundation
import MultipeerConnectivity.MCPeerID

final class MockMultipeerConnection: MultipeerProtocol {

var didReceiveData: ((Data, PeerName) -> Void)?
let localPeer: Peer = {
let underlyingPeer = MCPeerID(displayName: "MockPeer")
return try! Peer(peer: underlyingPeer, discoveryInfo: nil)
}()

var didReceiveData: ((Data, Peer) -> Void)?
var didFindPeer: ((Peer) -> Void)?
var didLosePeer: ((Peer) -> Void)?
var didConnectToPeer: ((Peer) -> Void)?
Expand All @@ -19,7 +25,7 @@ final class MockMultipeerConnection: MultipeerProtocol {
}

func broadcast(_ data: Data) throws {
didReceiveData?(data, "MockPeer")
didReceiveData?(data, localPeer)
}

func send(_ data: Data, to peers: [Peer]) throws {
Expand All @@ -31,7 +37,7 @@ final class MockMultipeerConnection: MultipeerProtocol {
}

func getLocalPeerId() -> String? {
return "MockId"
return localPeer.id
}

}
14 changes: 9 additions & 5 deletions Sources/MultipeerKit/Internal API/Models/MultipeerMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import Foundation

struct MultipeerMessage: Codable {
static let senderUserInfoKey = CodingUserInfoKey(rawValue: "sender")!

let type: String
let payload: Any?

Expand All @@ -40,17 +42,17 @@ struct MultipeerMessage: Codable {
case payload
}

private typealias MessageDecoder = (KeyedDecodingContainer<CodingKeys>) throws -> Any
private typealias MessageDecoder = (KeyedDecodingContainer<CodingKeys>, Peer) throws -> Any
private typealias MessageEncoder = (Any, inout KeyedEncodingContainer<CodingKeys>) throws -> Void

private static var decoders: [String: MessageDecoder] = [:]
private static var encoders: [String: MessageEncoder] = [:]

static func register<T: Codable>(_ type: T.Type, for typeName: String, closure: @escaping (T) -> Void) {
decoders[typeName] = { container in
static func register<T: Codable>(_ type: T.Type, for typeName: String, closure: @escaping (T, Peer) -> Void) {
decoders[typeName] = { container, peer in
let payload = try container.decode(T.self, forKey: .payload)

DispatchQueue.main.async { closure(payload) }
DispatchQueue.main.async { closure(payload, peer) }

return payload
}
Expand All @@ -67,9 +69,11 @@ struct MultipeerMessage: Codable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(String.self, forKey: .type)

let sender = decoder.userInfo[MultipeerMessage.senderUserInfoKey]! as! Peer

if let decode = Self.decoders[type] {
payload = try decode(container)
payload = try decode(container, sender)
} else {
payload = nil
}
Expand Down
8 changes: 6 additions & 2 deletions Sources/MultipeerKit/Internal API/MultipeerConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ final class MultipeerConnection: NSObject, MultipeerProtocol {
self.me = MCPeerID.fetchOrCreate(with: configuration)
}

var didReceiveData: ((Data, PeerName) -> Void)?
var didReceiveData: ((Data, Peer) -> Void)?
var didFindPeer: ((Peer) -> Void)?
var didLosePeer: ((Peer) -> Void)?
var didConnectToPeer: ((Peer) -> Void)?
Expand Down Expand Up @@ -145,7 +145,11 @@ extension MultipeerConnection: MCSessionDelegate {
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
os_log("%{public}@", log: log, type: .debug, #function)

didReceiveData?(data, peerID.displayName)
if let peer = try? Peer(peer: peerID, discoveryInfo: nil) {
didReceiveData?(data, peer)
} else {
os_log("Received data, but cannot create peer for %s", log: log, type: .error, #function, peerID.displayName)
}
}

func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
Expand Down
2 changes: 1 addition & 1 deletion Sources/MultipeerKit/Internal API/MultipeerProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ typealias PeerName = String

protocol MultipeerProtocol: AnyObject {

var didReceiveData: ((Data, PeerName) -> Void)? { get set }
var didReceiveData: ((Data, Peer) -> Void)? { get set }
var didFindPeer: ((Peer) -> Void)? { get set }
var didLosePeer: ((Peer) -> Void)? { get set }
var didConnectToPeer: ((Peer) -> Void)? { get set }
Expand Down
9 changes: 6 additions & 3 deletions Sources/MultipeerKit/Public API/MultipeerTransceiver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,13 @@ public final class MultipeerTransceiver {
/// - type: The `Codable` type to receive.
/// - closure: The closure that will be called whenever a payload of the specified type is received.
/// - payload: The payload decoded from the remote message.
/// - sender: The remote peer who sent the message.
///
/// MultipeerKit communicates data between peers as JSON-encoded payloads which originate with
/// `Codable` entities. You register a closure to handle each specific type of entity,
/// and this closure is automatically called by the framework when a remote peer sends
/// a message containing an entity that decodes to the specified type.
public func receive<T: Codable>(_ type: T.Type, using closure: @escaping (_ payload: T) -> Void) {
public func receive<T: Codable>(_ type: T.Type, using closure: @escaping (_ payload: T, _ sender: Peer) -> Void) {
MultipeerMessage.register(type, for: String(describing: type), closure: closure)
}

Expand Down Expand Up @@ -127,11 +128,13 @@ public final class MultipeerTransceiver {
}
}

private func handleDataReceived(_ data: Data, from peer: PeerName) {
private func handleDataReceived(_ data: Data, from peer: Peer) {
os_log("%{public}@", log: log, type: .debug, #function)

do {
let message = try JSONDecoder().decode(MultipeerMessage.self, from: data)
let decoder = JSONDecoder()
decoder.userInfo[MultipeerMessage.senderUserInfoKey] = peer
let message = try decoder.decode(MultipeerMessage.self, from: data)

os_log("Received message %@", log: self.log, type: .debug, String(describing: message))
} catch {
Expand Down
5 changes: 3 additions & 2 deletions Tests/MultipeerKitTests/MultipeerKitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ final class MultipeerKitTests: XCTestCase {

let expect = XCTestExpectation(description: "Receive payload")

mock.receive(TestPayload.self) { p in
XCTAssertEqual(p, tsPayload)
mock.receive(TestPayload.self) { payload, sender in
XCTAssertEqual(payload, tsPayload)
XCTAssertEqual(sender.id, mock.localPeerId!)

expect.fulfill()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {

let t = MultipeerTransceiver(configuration: config)

t.receive(ExamplePayload.self) { [weak self] payload in
t.receive(ExamplePayload.self) { [weak self] payload, peer in
print("Got payload: \(payload)")

self?.notify(with: payload)
self?.notify(with: payload, peer: peer)
}

return t
Expand All @@ -37,9 +37,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
MultipeerDataSource(transceiver: transceiver)
}()

private func notify(with payload: ExamplePayload) {
private func notify(with payload: ExamplePayload, peer: Peer) {
let content = UNMutableNotificationContent()
content.body = payload.message
content.body = "\"\(payload.message)\" from \(peer.name)"
let request = UNNotificationRequest(identifier: payload.message, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { _ in

Expand Down

0 comments on commit 8dd6524

Please sign in to comment.