Permalink
Browse files

ConnectedColors example project

  • Loading branch information...
ralfebert committed Jul 25, 2018
1 parent 85cb480 commit 59012ca711c08bc155daf07010e87ff9b3b39ddd
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
BF362D852108C80300F7397B /* ColorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF362D842108C80300F7397B /* ColorService.swift */; };
BF6F13F81E4E58C90018D56E /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF6F13F71E4E58C90018D56E /* AppDelegate.swift */; };
BF6F13FA1E4E58C90018D56E /* ColorSwitchViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF6F13F91E4E58C90018D56E /* ColorSwitchViewController.swift */; };
BF6F13FD1E4E58C90018D56E /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = BF6F13FB1E4E58C90018D56E /* Main.storyboard */; };
@@ -15,6 +16,7 @@
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
BF362D842108C80300F7397B /* ColorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorService.swift; sourceTree = "<group>"; };
BF6F13F41E4E58C90018D56E /* ConnectedColors.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ConnectedColors.app; sourceTree = BUILT_PRODUCTS_DIR; };
BF6F13F71E4E58C90018D56E /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
BF6F13F91E4E58C90018D56E /* ColorSwitchViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorSwitchViewController.swift; sourceTree = "<group>"; };
@@ -56,6 +58,7 @@
children = (
BF6F13F71E4E58C90018D56E /* AppDelegate.swift */,
BF6F13F91E4E58C90018D56E /* ColorSwitchViewController.swift */,
BF362D842108C80300F7397B /* ColorService.swift */,
BF6F13FB1E4E58C90018D56E /* Main.storyboard */,
BF6F13FE1E4E58C90018D56E /* Assets.xcassets */,
BF6F14001E4E58C90018D56E /* LaunchScreen.storyboard */,
@@ -137,6 +140,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
BF362D852108C80300F7397B /* ColorService.swift in Sources */,
BF6F13FA1E4E58C90018D56E /* ColorSwitchViewController.swift in Sources */,
BF6F13F81E4E58C90018D56E /* AppDelegate.swift in Sources */,
);
@@ -0,0 +1,120 @@
import Foundation
import MultipeerConnectivity
protocol ColorServiceDelegate {
func connectedDevicesChanged(manager : ColorService, connectedDevices: [String])
func colorChanged(manager : ColorService, colorString: String)
}
class ColorService : NSObject {
// Service type must be a unique string, at most 15 characters long
// and can contain only ASCII lowercase letters, numbers and hyphens.
private let ColorServiceType = "example-color"
private let myPeerId = MCPeerID(displayName: UIDevice.current.name)
private let serviceAdvertiser : MCNearbyServiceAdvertiser
private let serviceBrowser : MCNearbyServiceBrowser
var delegate : ColorServiceDelegate?
lazy var session : MCSession = {
let session = MCSession(peer: self.myPeerId, securityIdentity: nil, encryptionPreference: .required)
session.delegate = self
return session
}()
override init() {
self.serviceAdvertiser = MCNearbyServiceAdvertiser(peer: myPeerId, discoveryInfo: nil, serviceType: ColorServiceType)
self.serviceBrowser = MCNearbyServiceBrowser(peer: myPeerId, serviceType: ColorServiceType)
super.init()
self.serviceAdvertiser.delegate = self
self.serviceAdvertiser.startAdvertisingPeer()
self.serviceBrowser.delegate = self
self.serviceBrowser.startBrowsingForPeers()
}
deinit {
self.serviceAdvertiser.stopAdvertisingPeer()
self.serviceBrowser.stopBrowsingForPeers()
}
func send(colorName : String) {
NSLog("%@", "sendColor: \(colorName) to \(session.connectedPeers.count) peers")
if session.connectedPeers.count > 0 {
do {
try self.session.send(colorName.data(using: .utf8)!, toPeers: session.connectedPeers, with: .reliable)
}
catch let error {
NSLog("%@", "Error for sending: \(error)")
}
}
}
}
extension ColorService : MCNearbyServiceAdvertiserDelegate {
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) {
NSLog("%@", "didNotStartAdvertisingPeer: \(error)")
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {
NSLog("%@", "didReceiveInvitationFromPeer \(peerID)")
invitationHandler(true, self.session)
}
}
extension ColorService : MCNearbyServiceBrowserDelegate {
func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) {
NSLog("%@", "didNotStartBrowsingForPeers: \(error)")
}
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
NSLog("%@", "foundPeer: \(peerID)")
NSLog("%@", "invitePeer: \(peerID)")
browser.invitePeer(peerID, to: self.session, withContext: nil, timeout: 10)
}
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
NSLog("%@", "lostPeer: \(peerID)")
}
}
extension ColorService : MCSessionDelegate {
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
NSLog("%@", "peer \(peerID) didChangeState: \(state.rawValue)")
self.delegate?.connectedDevicesChanged(manager: self, connectedDevices:
session.connectedPeers.map{$0.displayName})
}
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
NSLog("%@", "didReceiveData: \(data)")
let str = String(data: data, encoding: .utf8)!
self.delegate?.colorChanged(manager: self, colorString: str)
}
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
NSLog("%@", "didReceiveStream")
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
NSLog("%@", "didStartReceivingResourceWithName")
}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
NSLog("%@", "didFinishReceivingResourceWithName")
}
}
@@ -4,16 +4,21 @@ class ColorSwitchViewController: UIViewController {
@IBOutlet weak var connectionsLabel: UILabel!
let colorService = ColorService()
override func viewDidLoad() {
super.viewDidLoad()
colorService.delegate = self
}
@IBAction func redTapped() {
self.change(color: .red)
colorService.send(colorName: "red")
}
@IBAction func yellowTapped() {
self.change(color: .yellow)
colorService.send(colorName: "yellow")
}
func change(color : UIColor) {
@@ -23,3 +28,26 @@ class ColorSwitchViewController: UIViewController {
}
}
extension ColorSwitchViewController : ColorServiceDelegate {
func connectedDevicesChanged(manager: ColorService, connectedDevices: [String]) {
OperationQueue.main.addOperation {
self.connectionsLabel.text = "Connections: \(connectedDevices)"
}
}
func colorChanged(manager: ColorService, colorString: String) {
OperationQueue.main.addOperation {
switch colorString {
case "red":
self.change(color: .red)
case "yellow":
self.change(color: .yellow)
default:
NSLog("%@", "Unknown color value received: \(colorString)")
}
}
}
}

0 comments on commit 59012ca

Please sign in to comment.