I have a object in swift that manages MCSessions and connects to any that it finds. However, there always seems to be some issue so that while it is connecting to the session, it disconnects.
func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
browser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 10)
print("Found someone looking for a session to join: " + peerID.displayName);
}
//Error function
func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError) {
print(error.localizedDescription)
}
func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
//Do something when we lost a connection to someone.
}
// Remote peer changed state.
func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState){
print("WE HAVE A PEER THATS CHANGING");
var str = "";
switch(state){
case .NotConnected: str = "Not Connected";
case .Connecting: str = "Connecting";
case .Connected: str="Connected";
}
print("Count: " + String(session.connectedPeers.count) + " State: " + str);
}
Looking at other issues people have had with this, it's almost always caused by differing MCPeerID's between advertiser, browser, and session. However, I explicity set a constant peerID for the entire class.
let devicePeerID = MCPeerID(displayName: UIDevice.currentDevice().name)
I'm testing between an iPhone 5S and the simulator.